C++ Program to Reverse a Number


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;

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

909 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements