C Program to reverse of a number using recursion.
Objective
Write a C program to reverse a number using Recursion.
Algorithm / Approach
- In
main(), use a loop to count the number of digits (length) in the number. - Call
rev(num, length). - In the function, the Base Case is
if (len == 1) return n;. - The Recursive Step extracts the last digit, shifts it left by its mathematical place value (
pow(10, len-1)), and adds it to a recursive call of the remaining chopped-off number.
main.c
#include<stdio.h>
#include<math.h>
int rev(int, int);
int main() {
int num, res;
int length = 0, temp;
printf("Enter a number: ");
scanf("%d", &num);
temp = num;
while (temp != 0) {
length++;
temp = temp / 10;
}
res = rev(num, length);
printf("Reverse = %d\n",res);
return 0;
}
int rev(int n, int len) {
int x;
if (len == 1) {
return n;
}
else {
x = ((n % 10) * pow(10, len-1));
return ( x + rev(n / 10, --len));
}
}
Expected Output
Enter a number: 1234 Reverse = 4321
Explanation of the Program
- Reversing a number using recursion requires knowing exactly how many digits it has so you can mathematically shift the extracted numbers into their correct mirrored positions.
- While this is a great exercise to learn advanced recursion, using a simple
whileloop (as seen in earlier topics) is significantly easier to read and mathematically more efficient than using recursion for this specific problem.
Complexity
Time Complexity
O(log₁₀ n)
Space Complexity
O(log₁₀ n) - Call stack depth.