14a Recursion
14a Recursion
You know that, if the base case hasn't been reached, there is more
than 1 bunny. Hence, return 2 (because you know 1 bunny has 2
ears), plus another call to the method with one less bunny.
Explanation of recursive code
In our example, if our base case is reached – if the bunnies
parameter is 1 – we immediately return 2. Otherwise, we
(recursively) call the method again, returning the value of 2
plus whatever the method with the bunnies parameter
decremented by 1 returns.
<stunned silence>
Explanation (cont'd)
For a method call numEars(4):
You could of course easily calculate the above using loops! However,
this can also be done in a fairly intuitive way using recursion:
In the end, the method calls for factorial look like the following:
return 5 * factorial(4);
return 5 * (4 * factorial(3));
return 5 * (4 * (3 * factorial(2)));
return 5 * (4 * (3 * (2 * factorial(1))));
return 5 * (4 * (3 * (2 * (1))));
The last method call (the base case) doesn't return another method call, it returns a
value, which returns values to previous calls.
Factorial example (cont'd)
Recursion works in a "top down" manner, until the base case is reached.
Upon reaching the base case, recursive calls "unravel" back up the chain:
Tracing recursive method calls
What does the following code return when mystery(5) is called?
else
return 1 + mystery(n – 1);
}
Method calls go on a stack
When a program calls multiple methods, a data structure
called a stack is used to remember them; think of stacking
lunch trays up in the cafeteria.
• numEars method
• factorial method
• fibonacci method
The two parts of a recursive algorithm
Every recursive algorithm always has at least 2 parts:
• Base case(s)
o These determine when to stop (when no more
• Recursive call(s)
o Calls the same algorithm (i.e., itself) to assist in
int a = 4;
System.out.print(a++); //line 2
System.out.print(" " + a);
Would print: 4 5
else
return 2 + numEars(bunnies--);
}
Recursion takes quite a while to get good at, and you do NOT
need to be a recursion expert for the AP exam, you simply
need to be able to trace recursive method calls.
For more help with tracing recursive method calls, this site
helps explain the "stack-based" methodology (that I favor as it
tends to work for many students) very well:
apcomputersciencetutoring.com/exam-review/trace-recursive-methods/