In this C++ tutorial, you will learn how to write a program to reverse a given number using While loop statement.

C++ Reverse a Number

To reverse a given number in C++, pop the last digit of the given number in a loop, and append it to a new number. At the end of iteration, we end up with the reversed number in the result.


In the following program, we read a number to n from user via console input, and reverse this number.


#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number  : ";
    cin >> n;
    int reversed = 0;
    int temp = n;
    while (temp > 0) {
        reversed = (reversed * 10) + (temp % 10);
        temp = temp / 10;
    cout << "Reversed Number : " << reversed << endl;


Enter a number  : 987654321
Reversed Number : 123456789
Program ended with exit code: 0
Enter a number  : 1122
Reversed Number : 2211
Program ended with exit code: 0

We have used C++ While Loop for iteration.



In this C++ Tutorial, we learned how to reverse a number in C++, with example program.