Reverse of a Number using For loop in C
Program code to find Reverse of a Number in C:
#include<stdio.h> #include<conio.h> void main() { int i,n,r,s=0; clrscr(); printf("\n Enter The Number:"); scanf("%d",&n); //LOOP FOR FINDING THE REVERSE OF A NUMBER for(i=n;i>0; ) { r=i%10; s=s*10+r; i=i/10; } printf("\n The Reverse Number of %d is %d",n,s); getch(); }
Related: Reverse of a Number using For loop in C++
Working:
- First the computer reads a number from the user.
- Then using for 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 4321.
So i=4321 , s=0
- i>0 (4321>0) for loop condition is true
r=i%10 (r=4321%10) So r=1
s=s*10+r (s=0*10+1) So s=1
i=i/10 (i=4321/10) So i=432
- i>0 (432>0) for loop condition is true
r=i%10 (r=432%10) So r=2
s=s*10+r (s=1*10+2) So s=12
i=i/10 (i=432/10) So i=43
- i>0 (43>0) for loop condition is true
r=i%10 (r=43%10) So r=3
s=s*10+r (s=12*10+3) So s=123
i=i/10 (i=43/10) So i=4
- i>0 (4>0) for loop condition is true
r=i%10 (r=4%10) So r=4
s=s*10+r (s=123*10+4) So s=1234
i=i/10 (n=4/10) So i=0
- i>0 (0>0) for loop condition is false
It comes out of the for loop and prints the reverse number which is stored in variable “s”.
- Thus the program execution is completed.
Output:
TO DOWNLOAD THE PROGRAM CODE :CLICK HERE
very useful
very simple
So easy
Thanks
Thanks and very useful
Thanks sir
Very useful, explained nicely.
nice sir