Recursion in C++

Recursion in C++

Recursion in C++ is defined as when function is called within the same function. And the function which calls the same function this function is called as recursive function.Recursion is the process in which a function calls itself directly or indirectly. It is the process of calling the function by itself.

Working of Recursion

void recursion()
{
    ... .. ...
    recursion();
    ... .. ...
}

int main()
{
    ... .. ...
    recursion();
    ... .. ...
}

Program of Recursion in C++

#include <iostream>
using namespace std;

int fact(int n);

int main()
{
    int n;

    cout << "Enter a number: ";
    cin >> n;

    cout << "Factorial of " << n << " = " << fact(n);

    return 0;
}

int fact(int n)
{
    if(n > 1)
        return n * fact(n - 1);
    else
        return 1;
}

Output

Enter a number: 6

Factorial of 6 = 720

Advantages of Recursion

  • Recursion makes our code shorter and cleaner.It helps to reducing the time complexity and solve the stack evaluation and prefix,infix,postfix evaluation
  • It is required in problems concerning advanced algorithms, such as Graph and Tree Traversal.
  • In recursion program used less number of code hence the code looks shorter
  • Recursion is easy to approach to solve the problems involving data structure and algorithms like graph and tree

Disadvantage of Recursion

Recursion consume lot of stack space and use more processor time.

 

Read more, Storage class in C++

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *