A directory of Objective Type Questions covering all the Computer Science subjects.
Here you can access and discuss Multiple choice questions and answers for various competitive exams and interviews.

This C program reverse a given number. To reverse a given number, last digit of the number is obtained using the modulus operator (remainder left after division by 10). After this the last digit is cut off using the integer division of the number by 10. This cycle continues until the number becomes 0.

C program to reverse a number - Source code

/* C program to reverse a given number */
#include <stdio.h>
int main()
{
long num, reverse = 0, temp, remainder;
printf("Enter the number\n");
scanf("%ld", &num);
temp = num;
while (num > 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
printf("Given number = %ld\n", temp);
printf("Its reverse is = %ld\n", reverse);
return 0;
}

Program Output

Enter the number
12345
Given number = 12345
Its reverse is = 54321

Program Explanation

1. Take the number which you have to reverse as the input and store it in the variable num.
2. Copy the input number to the another variable temp. This is done to preserve the original number for printing in the end.
3. Firstly initialize the variable reverse to zero.
4. Obtain the remainder of the input number using the modulus operator (num%10).
5. Multiply the variable reverse with 10 and add the Obtained remainder to it and store the result in the same variable.
6. Obtain the quotient of the input number (integer division by 10) and considering this as input number repeat the steps as mentioned above until the obtained quotient becomes zero.
7. When it becomes zero, print the given number and its reverse using variables temp and reverse respectively as output.