When a function is called within another function, it is referred to as recursion. A recursive function calls the same function, while a tail recursion calls itself without performing any tasks after the call. In tail recursion, the same function is typically called with the return statement.
Recursive functions are defined as functions that call themselves. When a recursive function is invoked, it runs a sequence of instructions before calling itself to repeat the process with a smaller input. This process continues until it reaches a base case, which is a condition that terminates the recursion and returns a value.
The base condition is the condition that causes the recursion to terminate. The recursive function will repeatedly call itself until the basic condition is met.
The recursive case describes how the recursive call appears in the code. The recursive case can include numerous recursive calls or varied parameters so that the base condition is satisfied and the recursion is terminated.
There are two types of recursion, as follows:
Direct recursion occurs when a function contains one or more recursive calls to itself. In direct recursion, the function calls itself directly, with no intervening functions. Direct recursion can also be categorized into three types based on the number of recursive calls in the function's body.
In head recursion, the recursive call occurs at the beginning of the function. It is a type of linear recursion in which just one recursive call is made.
Tail recursion is a linear recursion in which a single recursive call occurs at the end of the function. The recursive call is usually the last statement in the function. The significance of tail recursion lies in the fact that we can use tail call optimization to reduce memory consumption.
The function's body contains many recursive calls. Tracing tree recursion yields a tree-like structure with numerous recursive calls branching from a single function.
When a function uses indirect recursion, it calls another function first, which in turn calls the original function, generating a cycle of function calls.