In C programming, reversing a number means moving the digit at the last position to the first position and vice versa.
For example, if the given number is “1234”, the reverse number will be “4321”.
Problem Description
Write a C program to find the reverse of the number.
Problem Solution
1. Take the number as input.
2. Store the number in a variable.
3. Take the number and divide it by 10 and store the remainder in a variable.
4. Add the remainder to the sum where sum multiplies its previous value by 10.
5. Repeat the process until the number is not 0.
6. Return the sum.
There are several ways to reverse a number in C language. Let’s take a detailed look at all the approaches to reverse a number in C.
Example:
The following C program uses a while loop to reverse the digits of the number and display it on the output of the terminal.
For example, 323441 becomes 144323
Program/Source Code
Here is source code of the C program to reverse a given number using while loop. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
Check this: Computer Science MCQs | BCA MCQs
/* C program to reverse a number */
#include
int main(void)
{
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(“Reverse of a Number is %ld\n”, reverse);
}
Runtime Test Cases
Testcase 1: In this case, we are entering the number “323441” as input.
Enter the number:
323441
Given number = 323441
Reverse of a Number is 144323
Testcase 2: In this case, we are entering the number “42394” as input.
Enter the number
42394
Given number = 42394
Reverse of a Number is 49324