Tuesday, June 12, 2012

C program to reverse a number | Source code and Algorithm explanation

In order to reverse a number you should first input the number and then extract the digits of number one by one. In order to extract digit you can use % operator which results in remainder of division operation. 13%10 is  3. Thus by doing mod 10 you can get rightmost digit of number. After extracting digit you can remove the same from number by storing result of /10 in integer variable. Eg 13/10 is 1.3 but on storing it in integer variable only 1 is stored.

In order to reverse a number using while loop in c language you must run the loop till the number is not 0 that is all the digits haven't been extracted. Assuming that you want reverse of number in variable called y (initial value of y should be zero), you should write y=y*10+extracted digit in while loop.

Consider test input of a=123,y=0

iteration 1
y=0*10+3=3, a=12
iteration 2
y=3*10+2=32, a=1
iteration 3
y=32*10+1=321 a=0

thus we get reverse of number in y.

Here is source code of c program to reverse a number


 int main()  
 {  
   int a;  
   printf("Enter a number :");  
   scanf("%d",&a);  
   int y=0;  
   while(a)  
   {  
     y=y*10+a%10;  
     a=a/10;  
   }  
   printf("\nreverse= %d",y);  
   getch();  
   return 0;  
 }  

1 comment: