Parents : Working of Recursion
| Date and time note was created | $= dv.current().file.ctime |
| Date and time note was modified | $= dv.current().file.mtime |
Understand the concept of Call Stack before reading this.
Example: To get the grip on how recursion flows, we can see the two following functions
Function 1 (Print reverse array of numbers from n to 1)
First printing is done and then recursive calls are made.
Here we assume/hypothesize that the function will work for n-1 and will give us the result for n-1 value i.e
solve(n-1) will give us 4 , 3 , 2 , 1 Thus what left is to induct the last value i.e 5 for that we put the conditioncout<<ibefore the hypothesis part.
void solve(i){
if(i==0) // Base condition
return ;
cout<<i; // induction
solve(i-1);// hypothesis
}
int main(){
solve(5);
}Output
5 , 4 , 3 , 2 , 1
Function 2 ( Print array of numbers from 1 to n)
First recursive calls are made and then printing is done.
Here we assume/hypothesize that the function solve will work for n-1 and will give us the result for n-1 value i.e
solve(n-1) will give us 1 , 2 , 3 , 4
Thus what left is to induct the last value i.e 5 for that we put the conditioncout<<iafter the hypothesis.
void solve(i){
if(i==0) // Base condition
return ;
cout<<i; // induction
solve(i-1); // hypothesis
}
int main(){
solve(5);
}Output
1 , 2 , 3 , 4 , 5