Reverse a Number in C++ Program Code

A simple C++ program in which user enter a number, program reverse it and display reversed number on the console.
For example: If input number is 12345
Then reversed number will be 54321

Concept used: for loop, modulus operator

Post Contains:
  1. Logic making and explanation
  2. Reverse number program code 
  3. Image view of code
  4. Dry run the program step by step



Logic Explanation:
  • To make a program like that we need to access every digit individually of entered number from last
  • Modulus operator provides such condition so first we take modulus of number until it become zero and add the every single digit which produce by modulus operator into our new integer variable which is named as reverse in the program with at each iteration of for loop
  • When for loop is break variable revers will have the reverse of entered number


Code:

#include<iostream>
using namespace std;

int main() {
int number, reverse = 0;
cout<<"Input a Number to Reverse and press Enter: ";
 cin>> number;     // Taking Input Number in variable number

   for( ; number!= 0 ; )
   {
      reverse = reverse * 10;
      reverse = reverse + number%10;
      number = number/10;
   }
   cout<<"New Reversed Number is:  "<<reverse;
   return 0;

}



We can also use while(number!=0) instead of for( ; number!=0 ; )

Image view of code:

Program output:




Dry Running The Program

Let input number is 123
so number=123 and reverse=0

number!=0 for loop condition true
      reverse = reverse * 10;                         reverse=0
      reverse = reverse + number%10;        reverse= 0 + 123%10= 3
      number = number/10;                         number=123/10=  12
  
number=12 for loop condition(number!=0) true
for loop iteration
      reverse = 3 * 10;                                   reverse=30
      reverse = reverse + number%10;        reverse= 30 + 12%10= 32
      number = number/10;                         number=12/10= 1
  
number=1 for loop condition(number!=0) true
for loop iteration      reverse = reverse * 10;                         reverse=320
      reverse = reverse + number%10;        reverse= 320 + 1%10= 321
      number = number/10;                         number=1/10=  0  


number=0 for loop condition false loop will break and display the output value of reverse.
Bookc
Admin

Hopefully the information we provide can be useful.

Press ESC to close