In C, a Reverse a Number program takes a number and reverses its digits. For example, if the input is 12345, the output will be 54321. This is typically done using a combination of mathematical operations like modulo (%
) and division (/
).
Logic to Reverse a Number:
- Extract the last digit using the modulo operator (
%
). - Build the reverse number by appending the extracted digit.
- Remove the last digit from the original number using division (
/
). - Repeat the process until all digits are reversed.
Program:
Explanation:
Variables:
int num
: This stores the original number input by the user.int reversed
: This stores the reversed number, initialized to 0.int remainder
: This stores the remainder, which is the last digit of the original number.
Input:
scanf("%d", &num);
takes the input number from the user.
Reversing Logic:
- Extract the Last Digit:
remainder = num % 10;
extracts the last digit ofnum
. - Build the Reverse Number:
reversed = reversed * 10 + remainder;
appends the extracted digit toreversed
. Initially,reversed
is 0, so for each digit, it multiplies by 10 and adds the new digit. - Remove the Last Digit:
num = num / 10;
removes the last digit from the original number by dividing it by 10.
- Extract the Last Digit:
Loop:
- The process is repeated inside the
while (num != 0)
loop until the original number becomes 0, meaning all digits have been reversed.
- The process is repeated inside the
Output:
- The program prints the reversed number using
printf
.
- The program prints the reversed number using
Sample Output:
Example 1:
Example 2:
Key Points:
- Modulo Operation (
%
) is used to extract the last digit of the number. - Division by 10 (
/
) is used to remove the last digit from the number. - The reversed number is built by multiplying the current reversed value by 10 and adding the extracted digit.
This is a common beginner-level program in C, helping you understand loops, arithmetic operations, and basic input/output handling.