Warm-up 8/27
Reminder: IN setup, FlipGrid video, and classroom supply due Monday
2
Repl.it 01-04.exploreUnicode
© A+ Computer Science - www.apluscompsci.com
Recursion occurs when a method calls itself.
A recursive method must have a stop condition or base case. Recursive calls will continue until the stop condition is met.
Recursion
© A+ Computer Science - www.apluscompsci.com
Recursion occurs when a method calls itself.
Be ready to answer the following questions after watching the video:
1. What is the first thing you have to "get happy about" when making recursive calls according to Professor Brailsford?
2. What solves this problem that Professor Brailsford describes?
Computerphile (begin at 4:00)
Recursion and the call stack
© A+ Computer Science - www.apluscompsci.com
During the method execution the code can only access the values in the current (i.e. top-most) stack frame.�
This way a single (local) variable can seemingly have many different values at the same time (as when a recursive method calls itself multiple times).
The Stack
© A+ Computer Science - www.apluscompsci.com
SF1- method() call
The Stack
© A+ Computer Science - www.apluscompsci.com
SF1- method() call
SF2- method() call
The Stack
© A+ Computer Science - www.apluscompsci.com
SF1- method() call
SF2- method() call
SF3- method() call
The Stack
© A+ Computer Science - www.apluscompsci.com
SF1- method() call
SF2- method() call
SF3- method() call
SF4- method() call
The Stack
© A+ Computer Science - www.apluscompsci.com
SF1- method() call
SF2- method() call
SF3- method() call
The Stack
© A+ Computer Science - www.apluscompsci.com
SF1- method() call
SF2- method() call
The Stack
© A+ Computer Science - www.apluscompsci.com
SF1- method() call
The Stack
As each call to the method completes, the instance of that method is removed from the stack.
13
Repl.it 01-05.Cat in the Hat - recursion 2
14
Repl.it 01-05.Cat in the Hat - recursion 3
© A+ Computer Science - www.apluscompsci.com
Write implementations using:
public int bunnyEars2(int bunnies)
{
return 2 * bunnies + (bunnies/2);
}
CodingBat: bunnyEars2
© A+ Computer Science - www.apluscompsci.com
Write implementations using:
b) iterative
int output = 0;
for (int i = 1; i <= bunnies; i++)
{
if (i%2 == 0)
{
output += 3;
}
else
{
output+= 2;
}
}
return output;
CodingBat: bunnyEars2
© A+ Computer Science - www.apluscompsci.com
Write implementations using:
c) recursion
if (bunnies == 0)
{
return 0;
}
else if (bunnies % 2 ==0)
{
return 3 + bunnyEars2(bunnies-1);
}
else
{
return 2 + bunnyEars2(bunnies-1);
}
CodingBat: bunnyEars2
© A+ Computer Science - www.apluscompsci.com
Share solutions.
a) iterative
CodingBat: fibonacci
© A+ Computer Science - www.apluscompsci.com
Share solutions.
b) recursive
CodingBat: fibonacci
© A+ Computer Science - www.apluscompsci.com
Repl.it: Fibonacci - recursively
© A+ Computer Science - www.apluscompsci.com
Homework