Table of Contents
Introduction
In this program, you will learn to reverse the digits of the integer value entered by the user in the C++ language.
For example, if the number is 98542, then this code will reverse the number, and the output will be 24589.
To understand the program, learn the following basic concepts of C++ programming
1. Operators
2. while and do-while loop
Program
#include<iostream> using namespace std; int main() { int n; cout<<"Enter an integer: "; cin>>n; int rem=0; // rem is used for the remainder int z=0; while(n>0) { rem=n%10; // fetching the last digit z=z*10+rem; // formation of reversed integer n=n/10; // elimination of the last digit } cout<<"Reversed number is: "<<z; return 0; }
Output
Explanation
‘n’ will store the integer entered by the user.
int rem=0;
‘rem’ variable is initialized with a 0 value to find the remainder.
int z=0; ‘z’ variable is initialized with a 0 value to hold the reversed integer.
The value of ‘n’ is 9850023
while(n>0)
the above condition is true
rem=n%10; this will return rem=9850023%10=3
z=z*10+rem;
Since z is 0, therefore, from the above statement, z=0*10+3=3
n=n/10; the value of ‘n’ is updated to 9850023/10=985002, thus vanishes the last digit.
Again, the condition in the while loop will become true, and the same procedure will take place for n=985002
rem=985002%10=2
z=3*10+2=32
n=985002/10=98500
Again, the condition in the while loop will become true, and the same procedure will take place for n=98500
rem=98500%10=0
z=32*10+0=320
n=98500/10=9850
Again, the condition in the while loop will become true, and the same procedure will take place for n=9850
rem=9850%10=0
z=320*10+0=3200
n=9850/10=985
Again, the condition in the while loop will become true, and the same procedure will take place for n=985
rem=985%10=5
z=3200*10+5=32005
n=985/10=98
Again, the condition in the while loop will become true, and the same procedure will take place for n=98
rem=98%10=8
z=32005*10+8=320058
n=98/10=9
Again, the condition in the while loop will become true, and the same procedure will take place for n=9
rem=9%10=9
z=320058*10+9=3200589
n=9/10=0
Now the condition in the while loop becomes false, and the loop terminates.
Thus, the final value of ‘z’ is 3200589.
0 Comments