×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

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

Submitted by Shubh Pachori, on August 05, 2022

Problem statement

Given a number, we have to reverse it using class and object approach.

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) »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.