Recursion
Recursion
BCAC 102
USING
{C}
Recursion Programming
Sudip Barik
Department of Computer Application
Techno International New Town
What is Recursion?
Any function which calls itself is called recursive function and such function calls
are called recursive calls.
Recursion cannot be applied to all problems, but it is more useful for the tasks that
can be defined in terms of a similar subtask.
It is idea of representing problem a with smaller problems.
Any problem that can be solved recursively can be solved iteratively.
When recursive function call itself, the memory for called function allocated and
different copy of the local variable is created for each function call.
Some of the problem best suitable for recursion are
Factorial
Fibonacci
Tower of Hanoi
STACK
Sudip Barik BCAC 102 (PPS) – Recursion 4
Working of Recursive function
Working
void func1();
void main()
{
....
func1(); Return address of func1( )
.... Function
} call Return address of func1( )
STACK
Sudip Barik BCAC 102 (PPS) – Recursion 5
Recursion : infinite call
When a recursive function directly calls itself (or indirectly by another function)
without any base condition(or terminating condition) then infinite recursion occurs.
A very simple example of infinite recursion call is presented below:
Program
1 #include <stdio.h>
2 void main()
3 {
4 printf("This is an example of recursion\n");
5 main();
6 }
Output
This is an example of recursion
This is an example of recursion Execution must be terminated abruptly; otherwise
This is an example of recursion the execution will continue indefinitely.
. . . . .
The direct recursion called by the same function. The indirect function called by the other function.
In direct function, when function called next time, value In indirect recursion, value of the local variable will
of local variable will stored. automatically lost when any other function is called.
Direct function engaged memory location. The local variable of indirect function not engaged it.
Through base case, where there will be no When the termination condition for the
Termination
function call. iterator ceases to be satisfied.
Used when code size needs to be small, and Used when time complexity needs to be
Usage
time complexity is not an issue. balanced against an expanded code size.
Example call
return 0
Program
1 // An example of tail recursive function
2 void print(int n)
3 {
4 if (n < 0) return;
5 printf(“ %d”, n);
6
7 // The last executed statement is recursive call
8 print(n-1);
9 }
Thank you