C++ Recursion (original) (raw)

Last Updated : 04 Mar, 2025

In C++, **recursion is a technique in which a function calls itself repeatedly until a given condition is satisfied. It is used for solving a problem by breaking it down into smaller, simpler sub-problems. Then finding the solution of it and combining this solution to find the global solution.

**Basic Example:

C++ `

#include using namespace std;

void printHello(int n) { if (n == 0) return; cout << "Hello" << endl; printHello(n - 1); }

int main() { printHello(5); return 0; }

`

Output

Hello Hello Hello Hello Hello

In the above program, we used a function named **printHello() that takes a number **n and prints ****"Hello"** once and call itself for with decremented argument. This goes on till n = 0. When argument **n is **5, it prints ****"Hello"** 5 times.

**Recursive Function

A function that calls itself is called a **recursive function. When a recursive function is called, it executes a set of instructions and then calls itself to execute the same set of instructions with a smaller input. A recursive function should contain,

According to this, from the first example, we can deduce that:

**Base Condition

if (n == 0) return;

**Recursive Case

printHello(n - 1);

Let's take a look at another example. This program finds the sum of first N natural numbers.

C++ `

#include using namespace std;

int nSum(int n) {

// Base condition to terminate
// recursion when N = 0
if (n == 0)
    return 0;

// recursive case / recursive call
int res = n + nSum(n - 1);
return res;

}

int main() {

// Calling the function
int sum = nSum(5);

cout << sum;
return 0;

}

`

In the above example,

Working of Recursion

To understand how C recursion works, we will again refer to the example above and trace the flow of the program.

**1. In the nSum() function, **Recursive Case is

int res = n + nSum(n - 1);

Let's see this recursive case in all recursive calls.

The below image lists the recursive case for each of the recursive call.

recursion tree diagram of nSum(5)

Recursion Tree Diagram of nSum(5) Function

Memory Management in C++ Recursion

Like all other functions, the recursive function's data is stored in the stack memory in the form of a stack frame. This stack frame is deleted once the function returns some value. In recursion,

Refer to this article to know more - Function Call Stack

What is Stack Overflow?

Stack overflow is one of the most common errors associated with the recursion which occurs when a function calls itself too many times. As we know that each recursive call requires separate space in the limited stack memory. When there is a large number of recursive calls or recursion goes on infinite times, this stack memory may get exhausted and may not be able to store more data leading to programs' termination.

**Types of Recursions in C++

There are two different types of recursions which are as follows:

  1. Direct Recursion
  2. Indirect Recursion

**1. Direct Recursion

In direct recursion, the function contains one or more recursive calls to itself. The function directly calls itself in the direct recursion and there is no intermediate function. Direct recursion can also be classified into three types based on how and how many recursive calls are present in the body of the function.

**a) Head Recursion: In head recursion, the recursive call is present at the start of the function. It is a kind of linear recursion where only a single recursive call is used.

**b) Tail Recursion: Tail recursion is a linear recursion where it's one and only recursive call is present at the end of the function. The recursive call is generally the last statement in the function. The significance of tail recursion is that we can reduce its memory consumption by using tail call optimization.

**c) Tree Recursion: In Tree Recursion, there are multiple recursive calls present in the body of the function. While tracing tree recursion, we get a tree-like structure where multiple recursive calls branch from one function.

**2. Indirect Recursion

In indirect recursion, the function does not call itself directly but instead, it calls another function which then eventually calls the first function creating a cycle of function calls.

**Practical Examples

The following examples will improve the understanding of C++ recursion:

**Fibonacci Series using Recursion

C++ `

#include using namespace std;

int fib(int n) {

// Stop condition
if (n == 0)
    return 0;
    
// Stop condition
if (n == 1 || n == 2)
    return 1;
    
// Recursion function
else
    return (fib(n - 1) + fib(n - 2));

}

int main() { int n = 5; for (int i = 0; i < n; i++) cout << fib(i) << " "; return 0; }

`

In this example, the Fibonacci function calls itself with smaller inputs (n - 1 and n - 2) until it reaches the base case (n <= 1) and returns a value.

C++ `

#include using namespace std;

// Recursive function to print array void pArray(int* arr, int n) {

// Base condition
if (n == 0)
    return;

// Recursive call
cout << arr[n - 1] << ' ';
pArray(arr, n - 1);  

}

int main() { int arr[5] = { 1, 2, 3, 4, 5 }; pArray(arr, 5); return 0; }

`

Applications of Recursion

Recursion has many applications in computer science and programming. Here are some of the most common applications of recursion:

Overall, recursion is a powerful and versatile technique that can be used to solve a wide range of problems in programming and computer science.

Drawbacks of Recursion

Difference between Iteration and Recursion

**Recursion and Iteration both repeatedly execute the set of instructions. The major difference between them is as follows:

To know more differences, refer to this article - Difference between Recursion and Iteration

Summary

Recursion can be a powerful tool for solving complex problems, but it can also be inefficient and can lead to stack overflow errors if not used properly. It's important to use recursion carefully and make sure that the base case is reached in a reasonable amount of time.