Lecture11-Recursion 1
Lecture11-Recursion 1
• Fibonacci series
(1,1,2,3,5,8,13,21,....)
Recursion execution
fact(4)
if (4 = = 1) return (1);
else return (4 * fact(3));
6
if (3 = = 1) return (1);
else return (3 * fact(2));
2
if (2 = = 1) return (1);
else return (2 * fact(1));
1
if (1 = = 1) return (1);
else return (1 * fact(0));
Recursion execution
int f (int n)
{
if(n>=0){
if (n < 2)
return (n);
else
return ( f(n − 1) + f(n − 2) );
}
}
Notable Point
• Sometimes, if the function being computed has a nice recurrence form, then a
recursive code may be more readable
When you write a recursive function
• First write the terminating/base condition
• Then write the rest of the function
• Always double-check that you have both
Example:
}
else {
printf(“%d”, i%10);
printReversed(i/10);
}
}
Recursion versus Iteration:
Repetition
• Iteration: explicit loop
• Recursion: repeated nested function calls
Termination
• Iteration: loop condition fails
• Recursion: base case recognized
Both can have infinite loops
How are recursive calls implemented?
What we have seen ....
• Activation record gets pushed into the stack when a function call is made.
• Activation record is popped off the stack when the function returns.
In recursion, a function calls itself.
• Several function calls going on, with none of the function calls returning back.
Activation records are pushed onto the stack continuously.
Large stack space required.
Activation records keep popping off, when the termination condition of
recursion is reached.
Activation records -local variables, return address, return value
Thanks
Any Questions?