Example: C++ Program to Reverse an Integer
#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.
Let us see this process in greater detail:
- In the first iteration of the loop,
n = 12345
remainder 12345 % 10 = 5
reversedNumber = 0 * 10 + 5 = 5
- In the second iteration of the loop,
n = 1234
remainder 1234 % 10 = 4
reversedNumber = 5 * 10 + 4 = 54
And so on, until n == 0
.
Finally, the reversedNumber (which contains the reversed number) is printed on the screen.