C Program to to reverse a number

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

How to reverse a number in C?

This c program helps to reverse a number. Reversing a given number means we need to write that number in reverse order. The logic used in this c program is elementary, get the number from the user by using proper printf and scanf statements. Here we choose long int for better programming. By using long int, users can input big value.

Explain a while loop in C?

To reverse the number, we use a 'while loop' after storing the number into a temporary variable. We use the 'mod operator' to extract the last digit of the number as the remainder. Add the remainder to the reverse variable, which is multiplied by 10. Now divide the number by 10 to remove the last element and repeat the loop. Finally, print the rev variable to display the output. Here 'while loop' is used. The syntax of the while loop is:

while (testExpression)

        // codes inside the body of a while

Here test expression checks whether the condition is true or false before the execution of the loop. If the test expression is true or non zero, code inside 'while loop' is executed, then the test expression is re-evaluated. This process continues until the expression becomes false; in this condition, 'while loop' is terminated, source code for reversing a number.



STEP 1: Include the header files to use the built-in Functions files into the C program.

STEP 2: Declare the variables num, rev, temp, digit as long.

STEP 3: Accept the number from the user and store it into 'num'.

STEP 4: Store the number into a temporary variable 'temp'.

STEP 5: Using a while loop, with the condition num>0, do the following steps.

STEP 6: digit = num.

STEP 7: Take the Last Digit of the number using rev = rev * 10 + digit.

STEP 8: num = num / 10.

STEP 9: Repeat step 5.

STEP 10: Display the given number as temp using printf.

STEP 11: Display the Reverse of the number as rev.

C Source Code

                                          #include <stdio.h>

void main() {
  long num, rev = 0, temp, digit;
  printf("Enter the number\n"); /*we use long int to declare number' */
  scanf("%ld", & num);
  temp = num;
  while (num > 0) {
    digit = num%10;
    rev = rev * 10 + digit; /*calculating the reverse using mod operator*/
    num /= 10;
  printf("Given number   = %ld\n", temp); /*display both numbers as output*/
  printf("Its reverse is = %ld\n", rev);


Enter the number

Given number   = 123456
Its reverse is = 654321