Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to reverse of a number using recursion.

C Code Example — Function Programs

ADVERTISEMENT

C Program to reverse of a number using recursion.

Objective

Write a C program to reverse a number using Recursion.

Algorithm / Approach

  1. In main(), use a loop to count the number of digits (length) in the number.
  2. Call rev(num, length).
  3. In the function, the Base Case is if (len == 1) return n;.
  4. 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 while loop (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.
ADVERTISEMENT