Week 11
Week 11
Week 11
Lecture Link:
https://www.youtube.com/watch?v=dTUuazeX2Mk&list=PLVEVLI2v6thVDz7Ux
UPnURUKaqWFK7Z7v&index=32
Recursion
x10 = x * x9
x9 = x * x8
x8 = x * x7
……
xn = x * xn-1
Recursive Functions: Factorial
n! = n * (n-1) * (n-2) …….. 3 * 2 * 1
5! = 5 * 4 * 3 * 2 * 1
4! = 4 * 3 * 2 * 1
5! = 5 * 4!
0! = 1
Recursive Functions: Factorial
#include<iostream>
using namespace std;
int fibo(int n);
int main()
{
int n,i=0;
cout<<"\nEnter How Many Terms You Want To Print Fibonacci Series ";
cin>>n;
cout<<"\nFibonnaci Series Is Given Below\n\n";
while(i<n)
{
cout<<" "<<fibo(i);
i++;
}
cout<<" \n\n";
return 0;
}
int fibo(int n)
{
if((n==1)||(n==0))
{
return(n);
}
else
{
return(fibo(n-1)+fibo(n-2));
}
}
Example
The Fibonacci Series
Set of recursive calls to function
fibonacci
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Advantages and Disadvantages of
Recursion
Roughly speaking, recursion and iteration perform the same kinds of tasks:
Solve a complicated task one piece at a time, and combine the results.
Emphasis of iteration:
Emphasis of recursion:
Solve a large problem by breaking it up into smaller and smaller pieces until you
can solve it; combine
the results.e.g.,
recursive factorial function