- A recursive method calls itself on a smaller version of the same problem.
- First handle the BASE CASE (stopping condition).
- Keys: a branch to separate cases, a recursive call on a SMALLER argument, and a base case with no recursion.
🎯 How this can come up · 1 question
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.
🎯 How this can come up · 1 question
Infinite recursion in Java eventually causes:
Correct: StackOverflowError.
- Every recursive method can be rewritten iteratively.
- Recursion uses more memory (a stack frame per call) and is often slower; but can be clearer.
- Tail recursion: the recursive call is the last action.
- n! = n × (n − 1)!, with 0! = 1! = 1.
🎯 How this can come up · 1 question
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).
🎯 How this can come up · 1 question
With fib(0) = 0 and fib(1) = 1, fib(6) is:
Correct: 8.
- Two base cases: fib(0) = 0, fib(1) = 1. Naïve recursion repeats work exponentially.
- power(base, exp) = base × power(base, exp − 1); power(base, 1) = base.
🎯 How this can come up · 1 question
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); }
No slides match this filter.