Write a C++ program using the concept of OOP to find the reverse of an integer number


Write a C++ program using the concept of OOP to find the reverse of an integer number.

Algorithm:

  1. Define a class Number with a private member variable num and a public member function getReverse().
  2. In the constructor of the class, prompt the user to enter a number and store it in the num variable.
  3. In the getReverse() function, initialize a variable reverse to 0 and a variable temp to the value of num.
  4. Use a while loop to iterate until temp is not equal to 0. In each iteration, multiply reverse by 10, add the last digit of temp to reverse, and divide temp by 10.
  5. Return the value of reverse as the reverse of the number.
  6. In the main() function, create an object of the Number class.
  7. Use the object's getReverse() function to get the reverse of the number and print it.
  8. Exit the program.

Coding:

#include <iostream>
using namespace std;
 
class Number {
    private:
        int num;
    public:
        Number() {
            cout << "Enter a number: ";
            cin >> num;
        }
        int getReverse() {
            int reverse = 0;
            int temp = num;
            while (temp != 0) {
                reverse = reverse * 10 + temp % 10;
                temp /= 10;
            }
            return reverse;
        }
};
 
int main() {
    Number n;
    cout << "Reverse of the number: " << n.getReverse() << endl;
    return 0;
}
 
#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment