Introduction
Reversing a number involves changing its digits’ order. For example, reversing 1234 results in 4321. We can achieve this using recursion by isolating the last digit and combining it with the reversed version of the remaining digits.
#include <stdio.h>
int reverseNumber(int num, int reversed) {
// Base case: if num is 0, return the reversed number
if (num == 0) {
return reversed;
}
// Recursive case: add last digit to reversed number
reversed = reversed * 10 + (num % 10);
return reverseNumber(num / 10, reversed);
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
int reversed = reverseNumber(number, 0);
printf("Reversed number: %d\n", reversed);
return 0;
}
Explanation
- Function Definition:
- The function
reverseNumbertakes two parameters:num(the number to reverse) andreversed(the reversed number so far). - Base Case: If
numis 0, it returns thereversednumber, ending the recursion. - Recursive Case:
- The last digit of
numis obtained usingnum % 10. - The
reversednumber is updated by multiplying it by 10 (to shift left) and adding the last digit. - The function calls itself with the remaining digits (
num / 10) and the updatedreversednumber.
- The last digit of
- The function
- Main Function:
- It prompts the user to input a number.
- It calls
reverseNumberwith the input number and initializesreversedto 0. - Finally, it prints the reversed number.
Input and Output Example
Input:
Enter a number: 1234
Output:
Reversed number: 4321
Conclusion
This C program successfully reverses a number using recursion. The recursive approach breaks down the problem by handling one digit at a time, making it easy to understand and implement. While this method is efficient for relatively small numbers, be cautious with large numbers due to potential stack overflow issues with deep recursion.