Yavatmal Zilha Akhil Kunbi Samaj Dwara Sanchalit,
Gopikabai Sitaram Gawande Mahavidyalaya, Umarkhed
Department of Computer Application
Name of Topic :- Unit II - Recursion
Subject :- Data Structure
Created by : Pravin Nakhate
Email:-nakhate@gsgcollege.edu.in
Mobile No. +919420621381
Class :- BCA – II
Learning Objectives:-
Introduction:-
Recursion:-
Iteration vs. Recursion:-
Iteration | Recursion |
It is a process of executing a statement or a set of statements repeatedly, until some specified condition is specified. | Recursion is the technique of defining anything in terms of itself. |
Iteration involves four clear-cut steps like initialization, condition, execution and updating. | There must be an exclusive if statement inside the recursive function, specifying stopping condition. |
Any recursive problem can be solved iteratively. | Not all problems have recursive solution. |
Iterative counterpart of a problem is more efficient in terms of memory utilization and execution speed. | Recursion is generally a worse option to go for simple problems, or problems not recursive in nature. |
Examples of Recursion:-
1. To calculate the factorial of number we can use recursive function.
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d", f);
}
int fact(int n)
{
if ( n == 1)
return 1;
else
return n*fact(n-1);
}
2. Let's see an example to find the nth term of the Fibonacci series
.
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d ",f);
}
int fibonacci (int n)
{
if (n==0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);
}
A recursive solution to conversion
function convert(in pre:string, out post:string)
ch = first character of pre
delete first character of pre
if ch is an operand
post = post + ch //concatenate
else
// recursion to convert 1st
convert(pre, post)
// recursion to convert 2nd
convert(pre, post)
// concatenate the operator
post = post + ch
endif
endfunction
Translation from prefix to postfix simulation recursion.
Disadvantages of Recursion:-
TOWER OF HANOI:-
Now let us look at the Tower of Hanoi and see how we can use recursive technique to produce a logical and elegant solution.
Click below To View animation of Tower of Hanoi
The problem setup is as below :-
Here we have to transfer all the disks from source Tower A to the destination Tower C by using an intermediate Tower B. Following are the rules to be followed during transfer:-
Thank You