Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to reverse of a number using recursion.

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to reverse of a number using recursion.

Objective

Write a C++ program to reverse a number using Recursion.

Algorithm / Approach

  1. Calculate the total number of digits (length) of the number.
  2. Call rev(num, length).
  3. Base Case: If len == 1, return the number.
  4. Recursive Step: Extract the last digit, multiply it by 10^(length-1), and add it to the recursive call of the remaining digits.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int rev(int, int);
int main() {
 int num, res;
 int length = 0, temp;
 cout<<"Enter a number: ";
 cin>>num;
 temp = num;
 while (temp != 0) {
  length++;
  temp = temp / 10;
 }
 res = rev(num, length);
 cout<<"Reverse = "<< res<< endl;
 return 0;
}

int rev(int n, int len) {
 int x;
 cout<< " this is x"<< n<< endl;
 if (len == 1) {
  return n+1;
 }
 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

  • This applies recursion to a math problem by stripping the last digit off, shifting it all the way to the front using math (10^length-1), and recursively doing the same for the remaining digits.
  • Note on the provided code: The base case returns n + 1. This is a logical bug that will artificially inflate the final reversed number by 1!

Complexity

Time Complexity O(log₁₀ n)
Space Complexity O(log₁₀ n) - Call stack size equals the number of digits.

Common Mistakes

  • Logical Error: The recursive base case returns n + 1 instead of just n, corrupting the final mathematical result.
ADVERTISEMENT