Reverse a Number in C++

Last Updated : 18 Aug, 2026

Reversing a number means arranging its digits in the opposite order, so the last digit becomes the first.

  • The last digit is obtained using the modulo (%) operator.
  • The reversed number is built by repeatedly shifting existing digits left and adding the extracted digit.

Algorithm to Reverse a Number

Consider num as the input number and revNum as the reversed number.

1. Initialize revNum to 0.

2. Repeat the following steps while num > 0:

  • Extract the last digit using num % 10.
  • Add the digit to revNum using revNum = revNum * 10 + num % 10.
  • Remove the last digit from num using num = num / 10.

3. Return revNum.

C++
#include <bits/stdc++.h>
using namespace std;

// Iterative function to
// reverse digits of num
int reverseDigits(int num)
{
    int rev_num = 0;
    while (num > 0) {
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}

// Driver code
int main()
{
    int num = 4562;
    cout << "Reverse of num is " << reverseDigits(num);

    getchar();

    return 0;
}

Output
Reverse of num is 2654

Flow of Program To Reverse a Number

The below image illustrates the flow of the program to reverse the digits of a number.

Flowchart for reversing a number
  • The flowchart illustrates the process of finding the reverse of a given number.
  • It reads the number n and initializes rev = 0.
  • It repeatedly extracts the last digit using n % 10, adds it to rev, and removes the last digit using n / 10.
  • The loop continues until n becomes 0, after which the reversed number is printed.
Try It Yourself
redirect icon
Comment