You are here

C program to reverse a number

C program to reverse a number and to print it on the screen. For example, if the input is 123, the output will be 321. In the program, we use the modulus operator (%) to obtain digits of the number. To invert the number write its digits from right to left.

C program to find reverse of a 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 the number = %d\n", r);

  return 0;
}

Output of program:
Reverse number C program output

Download Reverse number program.

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;
}

To reverse or invert large numbers, use long data type or long long data type if your compiler supports it.

For numbers which we can't store in built-in datatypes, use a string or some other data structure.