Thursday, October 13, 2011

Reversing a Number in C

Objective : You are given a  number and you have to find the reverse of the given number in C. reverse of 1234 will be 4321.

Programming logic: The logic lies in constructing the reverse numbers from the digits of the given number. So we extract each digit with % modulus operator and then build the number up.To build the number we simply multiply the reverse number by 10 and then add the next remainder to it.
Like 1234:
1234%10=4 (remainder). rev=4.
123%10= 3. rev=4x10+3=43.
12%10=2 rev=43x10+2=432.
1%10=1 rev=432x10+1=4321.


Code:
#include<stdio.h>
int main()
{
    int k;
   printf("\n enter a number=");
   scanf("%d",&k);
   printf("\n Reverse of the number is=%d",reverse(k));
   return 0;
}
int reverse(int x)
{
    int ans=0,r;
    while( x > 0 )
    {
        r=x%10;//extract last digit
        ans=ans*10+r;// multiply by 10 and then add the remainder
          x=x/10;//reduce number
    }
   return(ans);

}

No comments:

Post a Comment