Program code to find Reverse of a Number in C:
#include<stdio.h> #include<conio.h> void main() { int n,a,r,s=0; clrscr(); printf("n Enter The Number:"); scanf("%d",&n); a=n; //LOOP FOR FINDING THE REVERSE OF A NUMBER while(n>0) { r=n%10; s=s*10+r; n=n/10; } printf("n The Reverse Number of %d is %d",a,s); getch(); }
Related: Reverse of a Number using while loop in C++
Working:
- First the computer reads a number from the user.
- Then using while loop the reverse number is calculated and stored in the variable ‘s’.
- Finally the reverse of a given number is printed.
Step by step working of the above C program:
Let us assume a number entered is 123.
So n=123 , s=0
- n>0 (123>0) while loop condition is true
r=n%10 (r=123%10) So r=3
s=s*10+r (s=0*10+3) So s=3
n=n/10 (n=123/10) So n=12
- n>0 (12>0) while loop condition is true
r=n%10 (r=12%10) So r=2
s=s*10+r (s=3*10+2) So s=32
n=n/10 (n=12/10) So n=1
- n>0 (1>0) while loop condition is true
r=n%10 (r=1%10) So r=1
s=s*10+r (s=32*10+1) So s=321
n=n/10 (n=1/10) So n=0
- n>0 (0>0) while loop condition is false
It comes out of the while loop and prints the reverse number which is stored in variable “s”.
- Thus the program execution is completed.