Professional Documents
Culture Documents
Need of Recursion
Properties of Recursion
How are Recursive functions stored in memory?
What is the base condition in recursion?
Format for Base Condition
Why does Stack Overflow error occur in recursion?
What is the difference between direct and indirect
recursion?
Format for direct recursion
Format for indirect recursion
What is tail recursion?
Why do we care about tail recursion?
Problems
Q1: Write a Program and Recursive Relation to find
the Fibonnaci series of n.
1
Recursion
What is Recursion?
Need of Recursion
● Reduce the length of our code and make it easier to
read and write.
Properties of Recursion
● Base condition is needed to stop the recursion
otherwise infinite loop will occur.
2
● Performing the same operations multiple times with
different inputs.
3
// base case
if(n <= 1){
return 1;
}
4
Format for direct recursion
void directRecFun()
{
// Some code....
directRecFun();
// Some code...
}
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
5
indirectRecFun1();
// Some code...
}
6
7
Problems
Code In C++ :
#include<iostream>
using namespace std;
// Base case 1
if( n == 0 ){
return 0;
}
// Base case 2
if( n == 1 || n == 2 ){
return 1;
}
// Recursive function
else{
return (fibonacci(n-1) + fibonacci(n-2));
}
}
int main(){
8
cout << "Enter the number of iteration to
occur :" << endl;
int n;
cin>>n;
9
10