OSW Recursion
OSW Recursion
Text Book(s)
1 Introduction
2 Types of Recursion
3 Recursion Tracing
5 Case Study
7 Review Questions
The given problem is divided into various sub-problems, the consecutive sub
problems are solved to obtain the solution of the given problem.
Two most essential elements of the recursion are base case and recursive state-
ment.
Base case is a case where terminating condition becomes true, terminat-
ing condition is a condition that indicates the termination of the recursive
function and prevent the recursion from the infinite loop.
Indirect recursion:
If the recursive statement is in another function or we can say if the call is
made by another function its known as indirect recursion call.
void main(){
printf("%d", add(5));
}
#include<stdio.h>
int multiply(int m, int n)
{
int ans;
if (n == 1)
ans = m; /* base case */
else
ans = m + multiply(m, n - 1); /* recursive statement */
return (ans);
}
void main(){
int c;
c=multiply(6,3);
printf("ANSWER %d", c);
}
Recursion: Iteration:
- When a function calls itself di- - When some set of instructions
rectly or indirectly. are executed repeatedly.
- Implemented using function - Implemented using loops.
calls. - Includes initializing control vari-
- Base case and recursive relation able, termination condition, and
are specified. update of the control variable.
- The function state approaches - The control variable approaches
the base case. the termination value.
- Uses stack memory to store local - Does not use memory except ini-
variables and parameters. tializing control variables.
- It will cause stack overflow er- - It will cause an infinite loop if
ror and may crash the system if the the control variable does not reach
base case is not defined or is never the termination value.
reached.
OSW 3541 (ITER, BBSR) Recursion 13 / 19
Difference between Recursion and Iteration(Cont..)
- If recursive statement has no base case, recursion may result into infinite
loop of function calls till the whole memory is used.
- A run time error message noting stack overflow or an action violation is
an indicator that a recursive function is not terminating.
- The recopying of large arrays or other data structures can quickly con-
sume all available memory. Such copying should be done inside a recur-
sive function only.
- On most systems, pressing a control character sequence (e.g., Control S)
will temporarily stop output to the screen.
Questions
1) Write a program for counting the occurrences of a character in a string.
2) Write a program to find capital letters in a string using recursive func-
tion?
3) Write a program to find Fibonacci series using recursive function?
4) Write a program for recursive selection sort?
5) Write a program to find GCD of two integers using recursive function?