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
numto the input number andreverseto 0. - Loop:
- In a loop, extract the last digit of
numusing the modulo operator (%). - Multiply the current value of
reverseby 10 and add the extracted digit to it. - Update the value of
numby removing its last digit using integer division (/). - Repeat the loop until
numbecomes 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
numandoriginalNumstore the input number,remainderstores the last digit, andreverseis initialized to 0. - Loop:
- In each iteration of the loop, the last digit of
numis extracted using the modulo operator (%). - The current value of
reverseis multiplied by 10, and the extracted digit is added to it. - The last digit is removed from
numusing integer division (/). - The loop continues until
numbecomes 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!