C Program to Reverse a Number
In this tutorial, we’ll develop a C program that reverses a given number. The program will prompt the user to input a number, and it will then reverse the digits of that number. We’ll provide a step-by-step explanation of the algorithm, the C code implementation, and examples of the program’s output.
Algorithm for Reversing a Number
- Input: Accept a number from the user.
- Initialization: Set variables
num
to the input number andreverse
to 0. - Loop:
- In a loop, extract the last digit of
num
using the modulo operator (%). - Multiply the current value of
reverse
by 10 and add the extracted digit to it. - Update the value of
num
by removing its last digit using integer division (/). - Repeat the loop until
num
becomes 0.
- In a loop, extract the last digit of
- Output: Display the reversed number stored in the variable
reverse
.
C Program for Reversing a Number
#include <stdio.h>
int main() {
int num, originalNum, remainder, reverse = 0;
// Input a number from the user
printf("Enter an integer: ");
scanf("%d", &num);
// Store the original number for comparison later
originalNum = num;
// Reverse the digits of the number
while (num != 0) {
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
// Display the original and reversed numbers
printf("Original number: %d\n", originalNum);
printf("Reversed number: %d\n", reverse);
return 0;
}
Output Example
Example: Reverse a Number (e.g., 12345)
Enter an integer: 12345
Original number: 12345
Reversed number: 54321
Explanation
- Input: The user is prompted to enter an integer (e.g., 12345).
- Initialization: Variables
num
andoriginalNum
store the input number,remainder
stores the last digit, andreverse
is initialized to 0. - Loop:
- In each iteration of the loop, the last digit of
num
is extracted using the modulo operator (%). - The current value of
reverse
is multiplied by 10, and the extracted digit is added to it. - The last digit is removed from
num
using integer division (/). - The loop continues until
num
becomes 0.
- In each iteration of the loop, the last digit of
- Output: The original and reversed numbers are displayed.
Conclusion
This C program illustrates how to reverse the digits of a given number using a loop and basic arithmetic operations. The algorithm efficiently extracts and accumulates the digits in reverse order. Feel free to run the program with different numbers to observe the reversal process. If you have any questions or need further clarification, please don’t hesitate to ask!