Recursion is a programming technique where a function calls itself repeatedly until a specific base condition is met. A function that performs such self-calling behavior is known as a recursive function, and each instance of the function calling itself is called a recursive call.
C
#include <stdio.h>
void rec(int n) {
// Base Case
if (n == 6) return;
printf("Recursion Level %d\n", n);
rec(n + 1);
}
int main() {
rec(1);
return 0;
}
OutputRecursion Level 1
Recursion Level 2
Recursion Level 3
Recursion Level 4
Recursion Level 5
This code demonstrates a simple recursive function that prints the current recursion level from 1 to 5. The function rec(n) calls itself with an incremented value of n until it reaches the base case n == 6, at which point the recursion stops.
Recursive Functions
A recursive function is a function that solves a problem by calling itself on a smaller subproblem. It typically consists of two main parts:
- Base Case – the condition under which the recursion stops.
- Recursive Case – where the function calls itself with modified arguments, gradually approaching the base case.
C++
returntype function(parameters) {
// base case
if (base condition) {
return base value;
}
// recursive case
return recursive expression involving function(modified parameters);
}
This structure allows problems to be broken down into simpler versions of themselves, making recursion a powerful tool for solving problems that can be defined in terms of smaller instances.
How Recursion works?
To understand how recursion works internally, it’s important to see how the call stack behaves during recursive calls. Each time a function calls itself, the current state is saved on the stack, and the new call begins. Once the base case is reached, the function starts returning back, one call at a time.
The following example demonstrates both the descending phase (going deeper into recursion) and the ascending phase (returning back from recursion):
C
#include <stdio.h>
void f(int n) {
printf("F(%d)'s Stack Frame Pushed\n", n);
if (n > 1) {
f(n - 1);
f(n - 1);
}
printf("F(%d)'s Stack Frame Removed\n", n);
}
int main() {
f(3);
return 0;
}
OutputF(3)'s Stack Frame Pushed
F(2)'s Stack Frame Pushed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(2)'s Stack Frame Removed
F(2)'s Stack Fr...
The function f begins by printing a message indicating that the current call's stack frame has been pushed. It then recursively calls itself twice with n - 1, provided n > 1. This continues until the base case is implicitly reached at n == 1, where no further recursive calls are made.
Once the base case is reached, the recursion starts to unwind. Each function call resumes after both recursive calls complete, and a message is printed showing that the corresponding stack frame is being removed.
This example illustrates the two key phases in recursion:
Descending Phase: The function continues to call itself with smaller arguments (n - 1) twice, creating a binary recursion. Each call pushes a new stack frame onto the call stack, deepening the recursion.
Ascending Phase: After reaching n == 1, the recursion begins to return. Each call completes and prints a message as its stack frame is removed, showing how the stack unwinds in reverse order.
Illustrations:
The above is an example of tree recursion, where a function makes multiple recursive calls (in this case, f(n - 1) is called twice). This leads to a branching structure resembling a tree, with each call generating two more until the base case is reached.
Recursion comes in various forms based on how recursive calls are structured—like tail recursion, head recursion, linear recursion, and more.
To learn about all types of recursion with clear examples, check out this article: Types of Recursion
Memory Management in Recursion
Like other functions, the data of a recursive function is stored in stack memory as a stack frame. This stack frame is removed once the function returns a value. In recursion,
- The function call occurs before returning a value, so the stack frames for each recursive call are placed on top of the existing stack frames in memory.
- Once the topmost function returns a value, its stack frame is removed, and control is passed back to the function just before it, resuming execution after the point where the recursive call was made.
- The compiler uses an instruction pointer to keep track of the location to return to after the function execution is complete.
- Unlike iteration, recursion relies on the call stack, making memory management a key differentiator between the two.
Refer these article to know more about Function Call Stack, Difference between recursion and iteration
Stack Overflow
The program's call stack has limited memory assigned to it by the operating system and is generally enough for program execution. But if we have a recursive function that goes on for infinite times, sooner or later, the memory will be exhausted, and no more data can be stored. This is called stack overflow. In other words,
Stack overflow is the error that occurs when the call stack of the program cannot store more data resulting in program termination.
Applications of Recursion
Recursion is widely used to solve different kinds of problems from simple ones like printing linked lists to being extensively used in AI. Some of the common uses of recursion are:
- Tree-Graph Algorithms
- Mathematical Problems
- Divide and Conquer
- Dynamic Programming
- In Postfix to Infix Conversion
- Searching and Sorting Algorithms
Advantages of Recursion
The advantages of using recursive methods over other methods are:
- Recursion can effectively reduce the length of the code.
- Some problems are easily solved by using recursion like the tower of Hanoi and tree traversals.
- Data structures like linked lists, trees, etc. are recursive by nature so recursive methods are easier to implement for these data structures.
Disadvantages of Recursion
As with almost anything in the world, recursion also comes with certain limitations some of which are:
- Recursive functions make our program a bit slower due to function call overhead.
- Recursion functions always take extra space in the function call stack due to separate stack frames.
- Recursion methods are difficult to understand and implement.
Similar Reads
C++ Recursion 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 Ex
8 min read
Types of Recursions What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inord
15+ min read
Types of Recursions What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inord
15+ min read
Practice Questions for Recursion | Set 6 Question 1 Consider the following recursive C function. Let len be the length of the string s and num be the number of characters printed on the screen. Give the relation between num and len where len is always greater than 0. C++ void abc(char *s) { if(s[0] == '\0') return; abc(s + 1); abc(s + 1);
4 min read
Practice Questions for Recursion | Set 4 Question 1 Predict the output of the following program. C++ #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 #incl
5 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++ #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,
5 min read