Thursday 12 May 2016

Reverse numbers #1 : C program.

Reverse number, as the name suggest no need to define this word.
Exactly as you are thinking , the reverse of 123 is 321. Today, we are going to ponder about how to get this reverse number, how to tell computer to reverse a number. Perhaps , after reading this you will find this very easy!

Program #1 : Print reverse number of n , where n is entered by user

We are going to use simple operators and a loop. i.e. "%" , "/" and "*".
We will understand this by an example , lets take 549.

  • Initialize the reverse number 'r' equals to zero.
  • Run a loop while n does bot become zero.
  • Assign r=r*10. and then r=r+n%10. Here n%10 will give us a unit place of number n.
  • Assign n=n/10, this will give us the updated n , say 54 here , because we don't need 9 now as we already stored it in r.
  • Now , 2nd time when loop runs, we have n=54 , and r=9.
  • This will become , first r=90, then 94.
  • when 3rd time loop runs we have r=94, and n=5.
  • this will become ,first  r=940 and then 945 , Which is the number that we want .
  • In next step the loop will not run as n=5/10 would be zero.
  • In this way we got our reverse number.

C Program : Reverse Number !



#include  < stdio.h > 
int main()
{
   int n, r = 0;
   printf("Enter a number to reverse\n");
   scanf("%d", &n);
   while (n!= 0)
   {
      r = r * 10;
      r = r + n%10;
      n = n/10;
   }
   printf("Reverse of entered number is = %d\n", r);
   return 0;
}

Thanking you !

No comments :

Post a Comment