SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
38.
0 1 2 3 4 5
0 1 1 2 3 5
Fibonacci Sequence
Every number is the sum of the
two previous, when possible.nth
fib
39.
base case
Ask, when do we not need to do any
computation? When can we simply return a number
rather than doing any addition?
Determining the
0 1 2 3 4 5
0 1 1 2 3 5
40.
Ask, when do we not need to do any
computation? When can we simply return a number
rather than doing any addition?
Determining the
0 1 2 3 4 5
0 1 1 2 3 5
base case
42.
0 1 2 3 4 5
base case
Ask, when do we not need to do any
computation? When can we simply return a number
rather than doing any addition?
Determining the
0 1 1 2 3 5
82.
static int fib(int n) {
if (n == 0) { return 0; }
if (n == 1) { return 1; }
else {
return fib(n-1) + fib(n-2); }
}
Think, when do I not have to do any computation?
This will also be when my code stops.
base case
SUMMARY
base case
83.
static int fib(int n) {
if (n == 0) { return 0; }
if (n == 1) { return 1; }
else {
return fib(n-1) + fib(n-2); }
}
When I do have to compute something, what is the
pattern? If I can prove it for one case, it should
work for them all.
recursive case
SUMMARY
base case
base case
85.
SUMMARY
• Recursion is just another way of looping, with information
changing each time.
• Recursion consists of a recursive call and a base case.
• If there is code after a recursive call it must be executed
and will be executed in reverse order.
• Recursion is a natural solution if you can visualise the call in
any instance i.e. Fibonacci numbers.
86.
WILL I SEE RECURSION
AGAIN?
• Yes, sorry.
• But it will give you more of a chance to understand it.
• Modules which touch on recursion (at least): DST (Semester
2, 1st year) and Algorithm Modules.