C++ program to reverse number

In this example, we will learn a c++ program to reverse numbers. This program takes one number from the user and programs reverse it. Like a number 235 after reverse become 532.

Prerequisite

Program: Reverse Numbers

Here is the code to take a number from the user. Programs reverse it and display it on the screen.

//C++ program to reverse number
#include <iostream>
using namespace std;
int main()
{
int number, revNum = 0, remainder;
cout << "Enter any number to reverse: ";
cin >> number;
while(number != 0)
{
remainder = number%10;
revNum = revNum*10 + remainder;
number = number/10;
}
cout << "Reversed number will be: " << revNum;
return 0;
}

Output

Enter any number to reverse: 235
Reversed number will be: 532

Description and working of this program

  • Initialize three variables and named them “number”, “revNum” and “remainder”
  • Take the input number value from the user and stores it in “number”  variable
  • Initialize while loop until the “number” value will not equal zero
  • Find reminders by using the formula reminder = number%10. Where 10 is the base of decimal numbers.
  • Now use formula to reverse number revNum = revNum *10 +reminder
  • Divide the number by 10 for the next iteration of the loop.
  • Repeat while loop until the number value does not go to zero.
  • When number values reach 0 print revNum.