C program to find reverse of any number

Previous Program Next Program

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

Example

Input

Input number: 1234

Output

Reverse of 1234 = 4321

Required knowledge

Basic C programming, For loop

Logic to find reverse

I have divided the logic to find reverse of any number in four simple steps.

  1. Extract the last digit of the given number by performing modulo operation.
  2. Increase the place value of reverse. For that multiply reverse variable by 10.
  3. Add the last digit computed above, with reverse.
  4. Remove the last digit by dividing the number by 10. As it is not needed anymore.

Let us implement the 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;

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

    /* Repeat the till num becomes 0 */
    while(num != 0)
    {
        /* Multiple rev by 10 and adds the last digit to it*/
        reverse = (reverse * 10) + (num % 10);

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

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

    return 0;
}

Note: Take your skills to next level. Learn this program using recursive approach.

Output
Enter any number to find reverse: 1234
Reverse = 4321

Happy coding ;)

You may also like

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment