You are here

C program to reverse a number

C program to reverse a number: This program reverses a number entered by a 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 a 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.

C program to find reverse of a number

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int n, reverse = 0;
  6.  
  7.    printf("Enter a number to reverse\n");
  8.    scanf("%d", &n);
  9.  
  10.    while (n != 0)
  11.    {
  12.       reverse = reverse * 10;
  13.       reverse = reverse + n%10;
  14.       n       = n/10;
  15.    }
  16.  
  17.    printf("Reverse of entered number is = %d\n", reverse);
  18.  
  19.    return 0;
  20. }

Output of program:
Reverse number C program output

Download Reverse number program.

Reverse number C program using recursion

  1. #include <stdio.h>
  2.  
  3. long reverse(long);
  4.  
  5. int main()
  6. {
  7.    long n, r;
  8.    
  9.    scanf("%ld", &n);
  10.  
  11.    r = reverse(n);
  12.  
  13.    printf("%ld\n", r);
  14.  
  15.    return 0;
  16. }
  17.  
  18. long reverse(long n) {
  19.    static long r = 0;
  20.    
  21.    if (n == 0)
  22.       return 0;
  23.    
  24.    r = r * 10;
  25.    r = r + n % 10;
  26.    reverse(n/10);
  27.    return r;
  28. }

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.