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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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”.

  1. Thus the program execution is completed.

Output:

reverse of a number

reverse of a number

TO DOWNLOAD THE PROGRAM CODE :CLICK HERE

 

You may also like...

8 Responses

  1. om badhe says:

    very simple

  2. Keya Patel says:

    So easy

  3. Shashank gupta says:

    Thanks

  4. Yash says:

    Thanks and very useful

  5. Anshul says:

    Thanks sir

  6. Iqra says:

    Very useful, explained nicely.

Leave a Reply

Your email address will not be published. Required fields are marked *