12/16/2020
Recursive Subprograms
Recursion is the primary control mechanism for repeating sequences of
statements. Recursion in the form of recursive subprogram calls, is one of the
most important sequence-control structure in programming.
Recursive subprogram is one that calls itself (directly or indirectly) repeatedly
having two properties
It has a terminating condition or base criteria for which it doesn’t call itself
Every time it calls itself, it brings closer to the terminating condition
In Recursive subprogram calls A subprogram may call any other subprogram
including A itself, a subprogram B that calls A or so on.
The only difference between a recursive call and an ordinary call is that the
recursive call creates a second activation of the subprogram during the
lifetime of the first activation.
Both CIP and CEP are used to implement recursive subprogram
1
12/16/2020
Types of Recursion
Direct Recursion
A function is called a recursive function if it calls itself again and again .
void RecFun()
{
// Some code....
RecFun();
// Some code...
}
Indirect Recursive Function
Indirect recursion is when a function calls another function and the called
function in turn calls the calling function.
That is if function 1 calls function 2 and then function 2 calls function 1
resulting in a cycle.
2
12/16/2020
Example – Indirect Recursion
// An example of indirect recursion
void RecFun1() {
// Some code...
RecFun2();
// Some code...
}
Void RecFun2()
{ // Some code...
RecFun1();
// Some code...
}
Tail Recursion
A recursive function is tail recursive when recursive call is the last thing
executed by the function.
For example the following C++ function print() is tail recursive.
Example
void print(int n)
{
if (n < 0) return;
cout << " " << n;
// The last executed statement is recursive call
print(n-1);
}
3
12/16/2020
Tail Recursion- Benefit
The tail recursive functions considered better than non tail recursive functions as
tail-recursion can be optimized by compiler.
The idea used by compilers to optimize tail-recursive functions is simple, since the
recursive call is the last statement, there is nothing left to do in the current
function, so saving the current function’s stack frame is of no use