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”.
Write a C program to find the reverse of the number.
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.
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
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 */
long num, reverse = 0, temp, remainder;
printf(“Enter the number:\n”);
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:
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
Given number = 42394
Reverse of a Number is 49324