The Wayback Machine - https://web.archive.org/web/20241126193439/https://www.geeksforgeeks.org/cpp-recursion/
Open In App

C++ Recursion

Last Updated : 22 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Assume that you have to paint a few balls. If you do it alone, it will take a lot of time. One thing you can do is to take help from your friend. Assuming that you have the same work speed, the task will be done in half of the time. Now, instead of taking help from only one of your friends, you take help from multiple friends such that each friend have only one ball to paint. The task will be done much faster as compared to when you were doing it alone. Recursion is a problem-solving technique that works in a similar way.

C++ Recursion

Recursion in C++ is a technique in which a function calls itself repeatedly until a given condition is satisfied. In other words, recursion is the process of solving a problem by breaking it down into smaller, simpler sub-problems.

Syntax Structure of Recursion

return_type recursive_func {
....
// Base Condition
// Recursive Case
....
}

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. This process continues until a base case is reached, which is a condition that stops the recursion and returns a value.

Base Condition

The base condition is the condition that is used to terminate the recursion. The recursive function will keep calling itself till the base condition is satisfied.

Recursive Case

Recursive case is the way in which the recursive call is present in the function. Recursive case can contain multiple recursive calls, or different parameters such that at the end, the base condition is satisfied and the recursion is terminated.

Example of C++ Recursion

The following C++ program illustrates how to perform recursion.

C++
// C++ Program to calculate the sum of first N natural
// numbers using recursion
#include <iostream>
using namespace std;

int nSum(int n)
{
    // base condition to terminate the recursion when N = 0
    if (n == 0) {
        return 0;
    }

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

    return res;
}

int main()
{
    int n = 5;

    // calling the function
    int sum = nSum(n);

    cout << "Sum = " << sum;
    return 0;
}

Output
Sum = 15

In the above example,

  • Recursive Function: nSum() is the Recursive Function
  • Recursive Case: The expression, int res = n + nSum(n – 1) is the Recursive Case.
  • Base Condition: The base condition is if (n == 0) { return 0;}

Working of Recursion in C++

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);

2. In the example, n = 5, so as nSum(5)’s recursive case, we get

int res = 5 + nSum(4);

3. In nSum(4), the recursion case and everything else will be the same, but n = 4. Let’s evaluate the recursive case for n = 4,

int res = 4 + nSum(3);

4. Similarly, for nSum(3), nSum(2) and nSum(1)

int res = 3 + nSum(2);    // nSum(3)
int res = 2 + nSum(1); // nSum(2)
int res = 1 + nSum(0); // nSum(1)

Let’s not evaluate nSum(0) and further for now.

5. Now recall that the return value of the nSum() function in this same integer named res. So, instead of the function, we can put the value returned by these functions. As such, for nSum(5), we get

int res = 5 + 4 + nSum(3);

6. Similarly, putting return values of nSum() for every n, we get

int res = 5 + 4 + 3 + 2 + 1 + nSum(0);

7. In nSum() function, the base condition is

if (n == 0) {
return 0;
}

which means that when nSum(0) will return 0. Putting this value in nSum(5)’s recursive case, we get

int res = 5 + 4 + 3 + 2 + 1 + 0;
= 15

8. At this point, we can see that there are no function calls left in the recursive case. So the recursion will stop here and the final value returned by the function will be 15 which is the sum of the first 5 natural numbers.

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,

  • The function call is made before returning the value, so the stack frame for the progressive recursive calls is stored on top of existing stack frames in the stack memory.
  • When the topmost function copy returns some value, its stack frame is destroyed and the control comes to the function just before that particular copy after the point where the recursive call was made for the top copy.
  • The compiler maintains an instruction pointer to track where to return after the function execution.

Let’s consider the above example and understand the memory management of nSum(5) function.

Step 1: When nSum() is called from the main() function with 5 as an argument, a stack frame for nSum(5) is created.

call stack at step 1

Call Stack at Step 1

Step 2: While executing nSum(5), a recursive call is encountered as nSum(4). The compiler will now create a new stack frame on top of the nSum(5)’s stack frame and maintain an instruction pointer at the statement where nSum(4) was encountered.

call stack at step 2

Call Stack at Step 2

Step 3: The execution of nSum(4) will start, but just like the previous function, we encounter another recursive call as nSum(3). The compiler will again follow the same steps and maintain another instruction pointer and stack frame for nSum(3).

call stack at step 3

Call Stack at Step 3

Step 4: The same thing will happen with nSum(3), nSum(2), and nSum(1)’s execution.

Step 5: But when the control comes to nSum(0), the condition (n == 0) becomes true and the statement return 0 is executed.

call stack at step 5

Call Stack at Step 5

Step 6: As the value is returned by the nSum(0), the stack frame for the nSum(0) will be destroyed, and using the instruction pointer, the program control will return to the nSum(1) function and the nSum(0) call will be replaced by value 0.

call stack at step 6

Call Stack at Step 6

Step 7: Now, in nSum(1), the expression int res = 1 + 0 will be evaluated and the statement return res will be executed. The program control will move to the nSum(2) using its instruction pointer.

call stack at step 7

Call Stack at Step 7

Step 8: In nSum(2), nSum(1) call will be replaced by the value it returned, which is 1. So, after evaluating int res = 2 + 1, 3 will be returned to nSum(3). Same thing will keep happening till the control comes to the nSum(5) again.

call stack at step 8

Call Stack at Step 8

Step 9: When the control reaches the nSum(5), the expression int res = 5 + nSum(4) will look like int res = 5 + 10. Finally, this value will be returned to the main() function and the execution of nSum() function will stop.

call stack at step 9

Call Stack at Step 9

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 Recursion in C++

There are two different types of recursion 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.

Examples of Recursion in C++

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

Example 1: Fibonacci Series using Recursion

C++
// C++ Program to find fibonacci series using recursion
#include <iostream>
using namespace std;

// Function for fibonacci
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));
}

// Driver Code
int main()
{
    // Initialize variable n.
    int n = 5;
    cout << "Fibonacci series of 5 numbers is: ";
    // for loop to print the fibonacci series.
    for (int i = 0; i < n; i++) {
        cout << fib(i) << " ";
    }
    return 0;
}

Output
Fibonacci series of 5 numbers is: 0 1 1 2 3 

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.

Example 2: Print Array in reverse order using recursion.

C++
// C++ Program to print array using
// recursion
#include <iostream>
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()
{
    // declaring array
    int arr[5] = { 1, 2, 3, 4, 5 };
    // calling function
    pArray(arr, 5);
    return 0;
}

Output
5 4 3 2 1 

Applications of Recursion

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

  • Solving: Fibonacci sequences, Factorial Function, Reversing an array, Tower of Hanoi.
  • Backtracking: It is a technique for solving problems by trying out different solutions and undoing them if they do not work. Recursive algorithms are often used in backtracking.
  • Searching and Sorting Algorithms: Many searching and sorting algorithms, such as binary search and quicksort, use recursion to divide the problem into smaller sub-problems.
  • Tree and Graph Traversal: Recursive algorithms are often used to traverse trees and graphs, such as depth-first search and breadth-first search.
  • Mathematical Computations: Recursion is also used in many mathematical computations, such as the factorial function and the Fibonacci sequence.
  • Dynamic Programming: It is a technique for solving optimization problems by breaking them down into smaller sub-problems. Recursive algorithms are often used in dynamic programming.

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

  • Performance: Recursive algorithms can be less efficient than iterative algorithms in some cases, particularly if the data structure is large or if the recursion goes too deep.
  • Memory usage: Recursive algorithms can use a lot of memory, particularly if the recursion goes too deep or if the data structure is large. Each recursive call creates a new stack frame on the call stack, which can quickly add up to a significant amount of memory usage.
  • Code complexity: Recursive algorithms can be more complex than iterative algorithms.
  • Debugging: Recursive algorithms can be more difficult to debug than iterative algorithms, particularly if the recursion goes too deep or if the program is using multiple recursive calls.
  • Stack Overflow: If the recursion goes too deep, it can cause a stack overflow error, which can crash the program.

Summary

  • There are two types of cases in recursion i.e. recursive case and a base case.
  • Infinite recursion may lead to running out of stack memory.
  • Each recursive call makes a new copy of that method in the stack memory.
  • The base case is used to terminate the recursive function when the case turns out to be true.
  • Examples of Recursive algorithms: Merge Sort, Quick Sort, Tower of Hanoi, Fibonacci Series, Factorial Problem, etc.

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.

FAQs on C++ Recursion

Q1. What is the difference between iteration and recursion?

Answer:

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

  • Recursion occurs when a statement in a function calls itself repeatedly while the iteration occurs when a loop repeatedly executes until the controlling condition becomes false.
  • Recursion is a process always applied to a function while iteration is applied to the set of instructions which we want to be executed repeatedly.

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



Previous Article
Next Article

Similar Reads

Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Practice questions for Linked List and Recursion
Assume the structure of a Linked List node is as follows. C/C++ Code struct Node { int data; struct Node *next; }; // This code is contributed by SHUBHAMSINGH10 C/C++ Code struct Node { int data; struct Node *next; }; Java Code static class Node { int data; Node next; }; // This code is contributed by shubhamsingh10 C/C++ Code class Node: def __ini
11 min read
Practice Questions for Recursion | Set 1
Explain the functionality of the following functions. Question 1 C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } C/C++ Code int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } Java Code static int fun1(int x, int y) { if (x == 0) return y; else return fun1(x - 1, x + y); } C/C
5 min read
Practice Questions for Recursion | Set 2
Explain the functionality of the following functions. Question 1 C/C++ Code /* Assume that n is greater than or equal to 1 */ int fun1(int n) { if (n == 1) return 0; else return 1 + fun1(n / 2); } Java Code /* Assume that n is greater than or equal to 1 */ static int fun1(int n) { if (n == 1) return 0; else return 1 + fun1(n / 2); } C/C++ Code # As
3 min read
Practice Questions for Recursion | Set 4
Question 1 Predict the output of the following program. C/C++ Code #include <iostream> using namespace std; void fun(int x) { if(x > 0) { fun(--x); cout << x <<" "; fun(--x); } } int main() { int a = 4; fun(a); return 0; } // This code is contributed by SHUBHAMSINGH10 C/C++ Code #include<stdio.h> void fun(int x)
6 min read
Practice Questions for Recursion | Set 5
Question 1Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int a, int b) { if (b == 0) return 0; if (b % 2 == 0) return fun(a + a, b/2); return fun(a + a, b/2) + a; } int main() { cout << fun(4, 3) ; return 0; } // This code is contribut
5 min read
Practice Questions for Recursion | Set 7
Question 1 Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include <iostream> using namespace std; int fun(int n, int* fp) { int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f; } int main() { int x = 15; cout << fun(5, &x) <<
4 min read
Print 1 to 100 in C++ Without Loops and Recursion
We can print 1 to 100 without using loops and recursion using three approaches discussed below: 1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. Example: C/C++ Code // CPP Program to print 1 to 100 // without loops and recursion #include <iostream> using namespac
3 min read
Juggler Sequence | Set 2 (Using Recursion)
Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : [Tex]a_{k+1}=\begin{Bmatrix} \lfloor a_{k}^{1/2} \rfloor & for \quad even \quad a_k\\ \lfloor a_{k}^{3/2} \rfloor & for \q
4 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head->prev and head->next If prev = NULL it means that list is fully reversed. Else reverse(head->p
9 min read
Sum of natural numbers using recursion
Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum().Examples : Input : 3 Output : 6 Explanation : 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : 1 + 2 + 3 + 4 + 5 = 15 Below is code to find the sum of natural numbers up to n using recursion : C/C++ Code // C++ program to find
3 min read
Product of 2 Numbers using Recursion
Given two numbers x and y find the product using recursion. Examples : Input : x = 5, y = 2 Output : 10 Input : x = 100, y = 5 Output : 500 Method 1) If x is less than y, swap the two variables value 2) Recursively find y times the sum of x 3) If any of them become zero, return 0 C/C++ Code // C++ Program to find Product // of 2 Numbers using Recur
4 min read
Program for length of a string using recursion
Given a string calculate length of the string using recursion. Examples: Input : str = "abcd" Output :4 Input : str = "GEEKSFORGEEKS" Output :13 We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C? Algorithm: recLen(str) { If str is NULL return 0 Else return 1 + recLe
3 min read
Print a character n times without using loop, recursion or goto in C++
Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion, and goto. Examples : Input : n = 10, c = 'a'Output : aaaaaaaaaa Input : n = 6, character = '@'Output : @@@@@@ In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While d
2 min read
Print alternate nodes of a linked list using recursion
Given a linked list, print alternate nodes of this linked list. Examples : Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 Output : 1 -> 3 -> 5 -> 7 -> 9 Input : 10 -> 9 Output : 10 Recursive Approach : Initialize a static variable(say flag) If flag is odd print the node increase head and flag by 1,
6 min read
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca
2 min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Product of 2 numbers using recursion | Set 2
Given two numbers N and M. The task is to find the product of the 2 numbers using recursion.Note: The numbers can be both positive or negative. Examples: Input : N = 5 , M = 3 Output : 15 Input : N = 5 , M = -3 Output : -15 Input : N = -5 , M = 3 Output : -15 Input : N = -5 , M = -3 Output:15 A recursive solution to the above problem for only posit
8 min read
Program to check if an array is palindrome or not using Recursion
Given an array. The task is to determine whether an array is a palindrome or not using recursion. Examples: Input: arr[] = {3, 6, 0, 6, 3}Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5}Output: Not Palindrome Approach: Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome
4 min read
Sum of the series 1^1 + 2^2 + 3^3 + ..... + n^n using recursion
Given an integer n, the task is to find the sum of the series 11 + 22 + 33 + ..... + nn using recursion. Examples: Input: n = 2 Output: 5 11 + 22 = 1 + 4 = 5 Input: n = 3 Output: 32 11 + 22 + 33 = 1 + 4 + 27 = 32 Approach: Starting from n, start adding all the terms of the series one by one with the value of n getting decremented by 1 in each recur
3 min read
Print Fibonacci Series in reverse order using Recursion
Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion. Examples: Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are - 0 1 1 2 3. Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0 Approach: The idea is to use recursion in a way that keeps calling the same function again till N is gr
3 min read
Find the node with maximum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with maximum value. Examples: Input: Output: 22 Approach: Just traverse the node from root to right recursively until right is NULL. The node whose right is NULL is the node with the maximum value. Below is the implementation of the above approach: C/C++ Code // C++ implementation of the appr
7 min read
Programs to print Triangle and Diamond patterns using recursion
This article is aimed at giving a recursive implementation for pattern printing. Pattern 1: Example:Input: 5 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *Implementation: C/C++ Code // Program to print the given pattern #include <iostream> using namespace std; void print_asterisk(int asterisk) { if (asterisk == 0) return;
15+ min read
Decimal to Binary using recursion and without using power operator
Given an integer N, the task is convert and print the binary equaiva;ent of N.Examples: Input: N = 13 Output: 1101Input: N = 15 Output: 1111 Approach Write a recursive function that takes an argument N and recursively calls itself with the value N / 2 as the new argument and prints N % 2 after the call. The base condition will be when N = 0, simply
3 min read
Sort the Queue using Recursion
Given a queue and the task is to sort it using recursion without using any loop. We can only use the following functions of queue: empty(q): Tests whether the queue is empty or not. push(q): Adds a new element to the queue. pop(q): Removes front element from the queue. size(q): Returns the number of elements in a queue. front(q): Returns the value
10 min read
Convert a String to an Integer using Recursion
Given a string str representing a string, the task is to convert the given string into an integer.Examples: Input: str = "1234" Output: 1234Input: str = "0145" Output: 145 Approach: Write a recursive function that will take the first digit of the string and multiply it with the appropriate power of 10 and then add the recursive result for the subst
4 min read
Sum of even elements of an Array using Recursion
Given an array arr[] of integers, the task is to find the sum of even elements from the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 20 2 + 4 + 6 + 8 = 20Input: arr[] = {4, 1, 3, 6} Output: 10 4 + 6 = 10 Approach: Write a recursive function that takes the array as an argument with the sum variable to store the sum and the index
5 min read
Traverse Linked List from middle to left-right order using recursion
Given a Linked List. The task is to traverse the Linked List from middle to left-right order using recursion.For Example: If the given Linked List is: 2 -> 5 -> 8 -> 3 -> 7 -> 9 -> 12 -> NULL The Middle to left-right order is : 3, 8, 7, 5, 9, 2, 12 Explanation: Middle of the given linked list is '3' so, we start traversing from
15+ min read
Count Set-bits of number using Recursion
Given a number N. The task is to find the number of set bits in its binary representation using recursion. Examples: Input : 21 Output : 3 21 represented as 10101 in binary representation Input : 16 Output : 1 16 represented as 10000 in binary representation Approach: First, check the LSB of the number.If the LSB is 1, then we add 1 to our answer a
4 min read
Find Maximum Level Sum in Binary Tree using Recursion
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it and print the maximum sum.Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 6 Sum of all nodes of the 1st level is 4. Sum of all nodes of the 2nd level is -3. Sum of all nodes of the 3rd level is 6. Hence, the maximum sum is 6. Input: 1 / \ 2
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg