C program to reverse a number | C code champ

C program to reverse a number | C code champ


C program to reverse a number : Write a program in C which accepts a number as input and displays the number in reverse order in the output. Suppose number is 12345, so its output will be 54321. Let see how this thing can be achieved in general maths logic.

Normally we can achieve this things using remainder logic ( called as modulus in terms of C language). Say my number is 12345.

Input Num = 12345, Intialize reverse num =0

Rev Num =Rev Num * 10  (i.e. Rev Num = 0 * 10)

In second step we gonna need first digit of reversed number which can be achieved as below :

Rev Num =Rev Num + Remainder of (12345/10) i.e. Rev  Num = 0 + 5 = 5

Then we need to use the remaining number for next iteration:

Num = Quotient of (12345/10) = 1234

Now Repeating the above iteration until Num =0 will give us the desires solution i.e. 54321

Lets see how we are going to implement to reverse a number, the below program will accept a input number from the user as input and produces the reversed number as output.

C program to reverse a number  using while loop :

#include <stdio.h>

   int n, reverse = 0;

   printf("Enter a input number to reversed\n");

   while (n != 0)
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;

   printf("The Reversed number of entered number is = %d\n", reverse);

   return 0;

Note : To reverse large use long data type or long long data type if your compiler supports it, if you still have large numbers then use or other data structure.

We hope you all have enjoyed the C code of reversing a number. If you have any doubt then you can ask us in form of comments.