C++ Program to reverse integer or number entered by the user in C++ programming. This problem is solved by using while loop in this example.
To understand this Program to reverse integer or number, you should have the knowledge of following C++ programming topics:
- C++ while and do…while Loop
Program to Reverse Integer or Number
#include <iostream> using namespace std; int main() { int n, reversedNumber = 0, remainder; cout << "Enter an integer: "; cin >> n; while(n != 0) { remainder = n%10; reversedNumber = reversedNumber*10 + remainder; n /= 10; } cout << "Reversed Number = " << reversedNumber; return 0; }
Output
Enter an integer: 12345 Reversed number = 54321
This program takes an integer input from the user and stores it in variable n.
Then the while loop is iterated until n != 0 is false.
In each iteration, the remainder when the value of n is divided by 10 is calculated, reversedNumber is computed and the value of n is decreased 10 fold.
Finally, the reversedNumber (which contains the reversed number) is printed on the screen.
Related Programs
- C++ Program to Generate Multiplication Table
- C++ Program to Display Fibonacci Series
- C++ Program to Find GCD
- C++ Program to Find LCM
Ask your questions and clarify your/others doubts on Reverse a Number by commenting. Documentation