![]() |
VOOZH | about |
Recursion is the process in which a function calls itself directly or indirectly to perform the same task it is doing but for some other data. It is possible by adding a call to the same function inside its body.
According to the number and position of this call, recursion can be classified into the following types:
Let's take a look at each of them one by one.
This is the simplest and most common form of recursion. In direct recursion, a function calls itself directly within its own body. For Example:
5 4 3 2 1
In this example, the show() function is directly calling itself with a smaller value of n. We can clearly see that the function call is present in its body.
Direct recursion can be further classified into two more types:
In head recursion, the recursive call is made before any other statement in the function. So, the function first calls itself and then processes the result. For Example,
1 2 3 4 5
Here, the printing happens after the recursive call, which means the function first goes deep into recursion and then starts printing while returning.
Tail recursion is the opposite of head recursion. In this, the function performs its task first and then calls itself. The recursive call is the last operation in the function. For Example,
5 4 3 2 1
Tail recursion is more memory-efficient than head recursion and can sometimes be optimized by the compiler. To know more, refer to the article - Tail Call Optimisation in C - GeeksforGeeks
In tree recursion, a function makes more than one recursive call to itself within its body. As a result, the recursion tree branches out. For Example,
3 2 1 1 2 1 1
As you can see, the function is called twice for each value, which leads to a tree-like recursive structure.
Nested recursion occurs when a recursive functionโs argument itself is a recursive function call. For Example,
91
This type of recursion is more complex and is rarely used unless required for specific logic.
In indirect recursion, a function doesnโt call itself directly. Instead, it calls another function, which in turn calls the first one. This chain can involve more than two functions. For example,
10 9 4 3 1
Here, funcA() calls funcB(), and funcB() calls funcA(). They are indirectly recursive.