In this example, we will learn a C++ program to reverse numbers. This program takes one number from the user and programs reverses it. Like a number 235 after reverse become 532.
Example: C++ program to 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
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 store it in the “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.