C++ program to find the reverse of a number using class

Given a number, we have to reverse it using class and object approach.
Submitted by Shubh Pachori, on August 05, 2022

Example:

Input:
1234

Output:
4321

C++ Code to find the reverse of a number using class and object approach

#include <iostream>
using namespace std;

// Create a class
class Reverse {
  // Private data member
 private:
  int number;

  // Public function with an int type parameter
 public:
  void reverse(int n) {
    // Copying value of parameter in the data member
    number = n;

    // Declaring two int type variable for storing reversed
    // number and operations
    int remain, reverse = 0;

    // While loop for reversing the number
    while (number) {
      // The last digit of number is stored in remain
      // by % operator
      remain = number % 10;

      // The number which is in remain will be added in reverse
      // with a multiply of 10 at each iteration
      reverse = (reverse * 10) + remain;

      // Number is divided by 10 to discard the last digit
      number = number / 10;
    }

    // Printing the reversed number
    cout << "Reverse of " << n << " is " << reverse << endl;
  }
};

int main() {
  // Create an object
  Reverse R;

  // int type variable to store number
  int number;

  cout << "Enter Number: ";
  cin >> number;

  // calling function using object
  R.reverse(number);

  return 0;
}

Output

RUN 1:
Enter Number: 34561
Reverse of 34561 is 16543

RUN 2:
Enter Number: 5612
Reverse of 5612 is 2165

Explanation:

In the above code, we have created a class named Reverse, one int type data member number to store the number, and a public member function reverse() to reverse the given integer number.

In the main() function, we are creating an object R of class Reverse, reading an integer number by the user, and finally calling the reverse() member function to reverse the given integer number. The reverse() function contains the logic to reverse the given number and printing the reversed number.

C++ Class and Object Programs (Set 2) »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.