![]() |
VOOZH | about |
Recursion is a process where a function calls itself, either directly or indirectly to repeat the same task for smaller data. In C++, recursion occurs by writing a function that includes a call to itself within its body.
Based on how and where this function calls are present, recursion in C++ can be classified into the following types:
Letβs look at each type one by one.
Direct recursion occurs when a function calls itself directly from within its body. This is the most common and straightforward form of recursion.
Example:
5 4 3 2 1
In this example, the show() function calls itself directly with a reduced value of n.
Direct recursion can be divided into:
In head recursion, the recursive call happens before any processing in the function. The function calls itself first and processes later.
0 1 2 3 4 5
Here, the function goes deep into recursion first and processes while returning.
π head_recursion_in_cIn tail recursion, the function processes first and the recursive call is the last operation.
5 4 3 2 1
Tail recursion can be more memory-efficient and may benefit from compiler optimizations.
π tail_recursion_in_cTree recursion happens when a function calls itself more than once within its body, forming a tree-like structure.
3 2 1 1 2 1 1
The function calls itself twice for each value, branching like a tree.
π LightboxNested recursion means the argument to a function is itself a recursive call.
91
This type of recursion is complex and used only when necessary.
In indirect recursion, a function does not call itself directly. Instead, it calls another function that eventually calls the first one, creating a chain of calls.
10 9 4 3 1
Here, funcA() calls funcB(), which calls funcA() again, forming indirect recursion.
π indirect_recursion_in_c