Recursion
Recursion
Recursion
Recursion: An act of calling a function within its body is known as recursion.
void Rec()
{
.
.
.
Rec();
Recursion and Iteration: Any problem that is solved through iteration can also be solved with recursion and vice-
versa.
Example: To find GCD of two numbers a and b (Where b>a), We can use any of the following method.
2. Iteration executes faster than Recursion. 2. Due to function call overheads, Recursion
runs/executes slower as compared to Iteration.
Base case: The pre-defined condition given in a recursive function that is used to terminate recursive process is
known as Base Case.
Finite Recursion: Calling and invoking same function within itself in the presence of Base case is called Finite
Recursion.
Infinite Recursion: Calling and invoking same function within itself in the absence of Base case is called Finite
Recursion.
Direct Recursion: When a function calls itself within the same function repeatedly, it is called the direct recursion.
Indirect Recursion: Indirect recursion occurs when a function is called not by itself but by another function that it
called (either directly or indirectly). In other words, when a function is mutually called by another function in a
circular manner, the function is called an indirect or mutual recursion function.
Tail Recursion: A recursive function is called the tail-recursive if the recursive call is the last statement executes by
the function. After that, there is no statement is left to call the recursive function.
Head (No Tail) Recursion: A function is called the non-tail or head recursive if the recursive call will be the first
statement in the function. It means there should be no statement before the recursive calls.
Linear Recursion: A function is called the linear recursive if the function makes a single call to itself at each time the
function runs and grows linearly in proportion to the size of the problem.
Tree (Non-Linear) Recursion: A function is called the tree recursion, in which the function makes more than one call
to itself within the recursive function.
3
3* power(3, 0) // base case
1
Q: Write a function to find n! using recursive technique. Also show the dry run by taking one example.
2
2* fact (1) // base case
1
Points to remember:
1. A problem that can be solved through iteration can also be solved using recursive technique and vice-versa.
3. To make a function as recursive function there must be at least one base case and one recursive case.
4. Statement(s) before recursive call executes in FIFO (First In First Out) order whereas statement(s) after recursive
call executes in LIFO (Last In First Out) order.