C program to find reverse of any number

Write a C program to input a number from user and find reverse of the given number using for loop. How to find reverse of any number using loop in C program. Logic to find reverse of a number in C programming.

Example

Input

Input number: 1234

Output

Reverse of 1234 = 4321

Required knowledge

Basic C programming, While loop

Logic to find reverse of a number

Step by step descriptive logic to find reverse of a number.

  1. Input a number from user to find reverse. Store it in some variable say num.
  2. Declare and initialize another variable to store reverse of num, say reverse = 0.
  3. Extract last digit of the given number by performing modulo division. Store the last digit to some variable say lastDigit = num % 10.
  4. Increase the place value of reverse by one. To increase place value multiply reverse variable by 10 i.e. reverse = reverse * 10.
  5. Add lastDigit to reverse i.e. reverse = reverse + lastDigit.
  6. Since last digit of num is processed hence, remove last digit of num. To remove last digit divide num by 10 i.e. num = num / 10.
  7. Repeat step 3 to 6 till num is not equal to (or greater than) zero.

Let us implement the above logic in a C program.

Program to find reverse of any number

/**
 * C program to find reverse of any number
 */

#include <stdio.h>

int main()
{
    int num, reverse = 0;

    /* Input a number from user */
    printf("Enter any number to find reverse: ");
    scanf("%d", &num);

    /* Repeat the till 'num' becomes 0 */
    while(num != 0)
    {
        /* 
         * Increase place value of reverse and 
         * add last digit to reverse 
         */
        reverse = (reverse * 10) + (num % 10);

        /* Remove last digit from 'num' */
        num /= 10;
    }

    printf("Reverse = %d", reverse);

    return 0;
}

Take a step forward and learn this program using recursive approach.

Learn more - Program to find reverse of any number using recursion.

Output

Enter any number to find reverse: 1234
Reverse = 4321

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>