What is recursion in c++


  • A function that calls itself is said to be recursive. This process can also be performed indirectly if the function first calls another function or multiple functions before it is called once more.
  • But a break criterion is always necessary to avoid having the function call itself infinitely.
  • The concept of local objects makes it possible to define recursive functions in C++.
  • Recursion requires local objects to be created each time the function is called, and these objects must not have access to any other local objects from other function calls.
  • What effectively happens is that the local objects are placed on the stack, and thus the object created last is destroyed first.
  • Recursion occurs when a function calls itself directly or indirectly. Some programming functions lend themselves naturally to recursive algorithms, such as the factorial.
  • A recursive function must follow two basic rules:
    • It must have an ending point.
    • It must make the problem simpler.

Types of Recursion

    Types of recursion in c++ language

Example

    #include <iostream>
    using namespace std;
    //Factorial function
    int f(int n){
       /* This is called the base condition, it is
        * very important to specify the base condition
        * in recursion, otherwise your program will throw
        * stack overflow error.
        */
       if (n <= 1)
            return 1;
       else
           return n*f(n-1);
    }
    int main(){
       int num;
       cout<<"Enter a number: ";
       cin>>num;
       cout<<"Factorial of entered number: "<<f(num);
       return 0;
    }
    

Output

    Enter a number: 5
    Factorial of entered number: 120