Adsense 728 * 15

Search

Custom Search

Reverse a Number using Recursion in C, C++

Write a program to reverse a number using recursion in C, C++.

I have already discuss two approaches to reverse a number in my previous posts.

Program to reverse a number - Iterative approach

Reverse a string using stack

In this program, I'll show how to reverse a number using a recursion technique. Let's first understand, what is recursion.
In recursion, A function call itself until the base or termination condition is met. A program written using recursive approach is clean and short compared to iterative approach.

Difference between recursion and iteration

Recursion objective questions for practice

Programming questions on strings

Sorting algorithms and their time complexity

Reverse Number using Recursion in C

#include <stdio.h>

int reverse(int num) {
 
   static temp,sum;
 
   if(num>0){
  
      temp = num%10;
      sum = sum*10 + temp;

      /* Recursive call, A function call itself. */

      reverse(num/10);

   } else {
  
      return sum;
   }
 
 }

int main() {
 
   int num,rev;
 
    /* Taking input. */

    printf("Enter number\n");
    scanf("%d",&num);
 
    /* Called reverse function .*/

    rev = reverse(num);
 
    printf("\nReverse of a input number is %d\n",rev);
 
    return 0;
}




C, C++ Interview Questions with Answers 

Reverse Number using Recursion in C++

#include <iostream.h>
using namespace std;

int reverse(int num) {
 
   static temp,sum;
 
   if(num>0){
  
      temp = num%10;
      sum = sum*10 + temp;

      /* function call itself. */

      reverse(num/10);

   } else {
  
     return sum;
   }
 
}

int main() {
 
  int num,rev;
 
   /* Taking input. */

   cout<<"Enter number";
   cin >> num;
 
   /* Called reverse function .*/

   rev = reverse(num);
 
   cout << "Reverse of a input number is" << rev;
 
   return 0;
}





Output:

Enter number : 3456

Reverse of a input number is : 6543

No comments:

Post a Comment