C Program To Reverse a Number

If a integer number is input through the keyboard, write a program to reverse the input number and display it on the console window.

For Example: If user enters 135, reversed number must be 531.

Related Read:
Basic Arithmetic Operations In C
while loop in C programming
Calculate Sum of Digits: C Program
Check whether a Number is Palindrome or Not: C Program

Note: We assign variable reverse = 0 to avoid garbage values in variable reverse.

Reversing a Number Logic

If user enters 456, we apply the modulo division to get the individual values.
Ex:
456 % 10 = 6
45 % 10 = 5
4 % 10 = 4

After each iteration of while loop we add the reminder to the previous value of variable reverse. We also multiply the variable reverse with 10, to increment the decimal place.

We get 456, 45 and 4 by dividing the original value by 10.
Ex:
456 user entered value.
456 / 10 = 45
45 / 10 = 4

Now the reverse:

reverse = (reverse * 10 ) + rem;

06 = (010) + 6
65 = (6
10) + 5
654 = (65*10) + 4

So finally the reversed number is 654.

Video Tutorial: C Program To Reverse a Number



YouTube Link: https://www.youtube.com/watch?v=D8Yum35k6a0 [Watch the Video In Full Screen.]


Source Code: C Program To Reverse a Number

#include<stdio.h>

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

    printf("Enter a integer number\n");
    scanf("%d", &num);

    while(num)
    {
        rem = num % 10;
        reverse = (reverse * 10) + rem;
        num     = num / 10;
    }

    printf("Reversed number is %d\n", reverse);

    return 0;
}

Output 1:
Enter a integer number
1023
Reversed number is 3201

Output 2:
Enter a integer number
159
Reversed number is 951

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert