C++ Tutorial C++ Advanced C++ References

C++ - Recursive Function



A function which can call itself is known as recursive function. A recursive function generally ends with one or more boundary conditions which defines exit conditions from the function, otherwise it will go into an infinite loop.

Example: Factorial of a number

The factorial of a positive integer is the multiplication of all positive integer less than or equal to that number.

factorial of number n = n! = n(n-1)(n-2)...1

In the example below, a recursive function called factorial() is used to calculate factorial of a number.

#include <iostream>
using namespace std;
int factorial(int x); 

int main (){
  cout<<"3! =  "<<factorial(3)<<"\n"; 
  cout<<"5! =  "<<factorial(5)<<"\n";
  cout<<"10! =  "<<factorial(10)<<"\n";
  return 0;
}

int factorial(int x){
  if(x==0)
    return 1;
  else
    return x*factorial(x-1); 
}

The output of the above code will be:

3! =  6
5! =  120
10! =  3628800

Example: Fibonacci Sequence

Fibonacci terms are generally represented as Fn. A Fibonacci term is the sum of two previous terms and starts with 0 and 1. Mathematically, it can be represented as:

Fn = Fn-1 + Fn-2

With boundary conditions: F0 = 0 and F1 = 1

The Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233...

In the example below, a recursive function called fib() is created to find out the nth term of Fibonacci sequence.

#include <iostream>
using namespace std;

static int fib(int);

static int fib(int n) {
  if (n == 0)
    {return 0;}
  else if (n == 1)
    {return 1;}
  else
    {return fib(n-1) + fib(n-2);}
}

int main() {
  cout<<"Fibonacci 5th term: "<<fib(5)<<"\n";
  cout<<"Fibonacci 6th term: "<<fib(6)<<"\n";
  cout<<"Fibonacci 7th term: "<<fib(7)<<"\n";
  return 0;
}

The above code will give the following output:

Fibonacci 5th term: 5
Fibonacci 6th term: 8
Fibonacci 7th term: 13

❮ C++ - Functions

5