# C++ Program to Reverse a Number

C++ProgrammingServer Side Programming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Reversing a number means storing its digits in reverse order.

For example: If the number is 6529, then 9256 is displayed in the output.

A program to reverse a number is given as follows −

## Example

Live Demo

#include <iostream>
using namespace std;
int main() {
int num = 63972, rev = 0;
while(num > 0) {
rev = rev*10 + num%10;
num = num/10;
}
cout<<"Reverse of number is "<<rev;
return 0;
}

## Output

Reverse of number is 27936

In the above program, the number that needs to be reversed is 63972. It is stored in the variable num. The reversed number will be stored in the variable rev. The main logic of the program is in the while loop. The while loop will run till the number is greater than 0.

For each iteration of the while loop, rev is multiplied with 10 and added to num modulus 10. Then this is stored in rev. Also num is divided by 10 in each loop iteration.

This is demonstrated by the following code snippet.

while(num > 0) {
rev = rev*10 + num%10;
num = num/10;
}

Eventually, rev stores the reverse number of that in num and the value of num is zero. After that rev is displayed.

This can be seen in the following code snippet −

cout<<"Reverse of number is "<<rev;