Google Add

Search

Reverse a Number using Recursion in C, C++

Write a program to reverse a number using recursion in C, C++. Given an input number, write a program to reverse a number using recursion.

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

C Program to reverse a number and C++ program to reverse a number using Iterative approach

Reverse a string using stack

In this program, I'll show how to reverse a number using recursion. Let's first understand, what is recursion.

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 as compared to the iterative approach.

To learn about recursion, check my tutorials on recursion concept and practice questions.

Difference between recursion and iteration

Recursion objective questions for practice

Programming questions on strings

Sorting algorithms and their time complexity

Reverse a 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 an input number is %d\n",rev);
 
    return 0;
}




C, C++ Interview Questions with Answers 

Reverse a 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