What three things does a correct recursive method need?
Compare with the model answer
A branch that separates cases; at least one recursive call on a smaller version of the problem; and a base case that stops without recursing.
Recursive methods, base cases and recursive cases, countdown, the call sequence, infinite recursion and stack overflow, recursion vs. iteration, tail recursion, factorial, Fibonacci, and a recursive power method.
Every original slide is shown unchanged. Yellow marks on a slide point to a numbered note: hover or tap a mark to jump to its note, and hover a note to see its marks. Questions tagged Past exam appeared on a real paper; Prediction questions are likely angles, not confirmed. Pick an answer to each question: a wrong pick tells you why it is wrong, so you can try again.
A recursive method calls itself on a smaller version of the same problem.
What three things does a correct recursive method need?
A branch that separates cases; at least one recursive call on a smaller version of the problem; and a base case that stops without recursing.
No base case (or not getting smaller) → infinite recursion → StackOverflowError.
Infinite recursion in Java eventually causes:
Recursion uses more memory (a stack frame per call) and is often slower; but can be clearer.
n! = n × (n − 1)!, with 0! = 1! = 1.
Write a recursive factorial method.
public static long factorial(long n) { if (n <= 1) return 1; return n * factorial(n - 1); }
Fibonacci: 0, 1, 1, 2, 3, 5, 8…; fib(n) = fib(n − 1) + fib(n − 2).
With fib(0) = 0 and fib(1) = 1, fib(6) is:
Two base cases: fib(0) = 0, fib(1) = 1. Naïve recursion repeats work exponentially.
Write a recursive power(base, exponent).
public static int power(int base, int exponent) { if (exponent == 1) return base; return base * power(base, exponent - 1); }