You are here

C program to reverse a number

C program to reverse a number: This program reverses the number entered by the user and then print it on the screen. For example, if a user will enter 123 as input then 321 will be printed as output. In our program, we use modulus (%) operator to obtain the digits of a number. To invert number look at it and write it from opposite direction or the output of the program is a number obtained by writing the original number from right to left. To reverse or invert large numbers use long data type or long long data type if your compiler supports it, if you still have large numbers then use a string or other data structure.

C program to find reverse of a number

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

Download Reverse number program.

Output of program:
Reverse number C program output

Reverse number C program using recursion

#include <stdio.h>
 
long reverse(long); 
 
int main()
{
   long n, r;
 
   scanf("%ld", &n);
 
   r = reverse(n);
 
   printf("%ld\n", r);
 
   return 0;
}
 
long reverse(long n) {
   static long r = 0;
 
   if (n == 0) 
      return 0;
 
   r = r * 10;
   r = r + n % 10;
   reverse(n/10);
   return r;
}