 # C++ Program to Reverse a Number

Example to reverse an integer entered by the user in C++ programming. This problem is solved by using while loop in this example.

To understand this example, you should have the knowledge of the following C++ programming topics:

## 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:

1. In the first iteration of the loop,
`n = 12345`
`remainder 12345 % 10 = 5`
`reversedNumber = 0 * 10 + 5 = 5`
2. 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.