C program to find reverse of any number

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

Input number: 1234
Output reverse: 4321

Required knowledge

Basic C programming, For loop

Logic to find reverse

Logic of reversing of any number is pretty simple if you know how to find last digit of any number. The process of reversing involves four basic steps:
  1. Multiply the rev variable by 10.
  2. Find the last digit of the given number.
  3. Add the last digit just found to rev.
  4. Divide the original number by 10 to eliminate the last digit, which is not needed anymore.
Repeat the above four steps till the original number becomes 0 and finally we will be left with the reversed number in rev variable.

Program to find reverse

 * C program to find reverse of any number

#include <stdio.h>

int main()
    int n, rev = 0;

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

    /* Repeats the steps till n becomes 0 */
        /* Multiples rev by 10 and adds the last digit to it*/
        rev = (rev * 10) + (n % 10);

        /* Eliminates the last digit from num */
        n = n/10;

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

    return 0;

Note: Don't forget to learn the recursive approach of finding reverse of any number.

Enter any number to find reverse: 1234
Reverse = 4321

Happy coding ;)

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
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment