AP® Computer Science A · Unit 4 · Topic 4.16

What Makes a Method Recursive

A recursive method is one that calls itself with a smaller version of the same problem, and it only finishes because a base case stops the chain and lets the answers return back up.

A recursive method solves a problem by calling itself on a smaller piece of that same problem. For this to ever finish, the method needs a base case: a condition simple enough to answer directly, with no further calls. Every recursive call has to move toward that base case, usually by shrinking some parameter. Without a base case, or without progress toward it, the calls never stop and the program crashes with a stack overflow.

Each call to a recursive method gets its own copy of the parameters and local variables, stored in its own frame on the call stack. factorial(4) calls factorial(3), which calls factorial(2), which calls factorial(1), which calls factorial(0) and hits the base case, returning 1. That 1 travels back up: factorial(1) returns 1·1=1, factorial(2) returns 2·1=2, factorial(3) returns 3·2=6, factorial(4) returns 4·6=24. Nothing is overwritten along the way because each level keeps its own n and its own pending multiplication, waiting on the stack until the call below it returns.

This is what separates recursion from a loop dressed up to look fancy. A loop reuses one set of variables, updating them each pass. Recursion instead breaks the problem into a smaller version of itself and trusts that smaller version to solve itself, with its own fresh variables, until the base case bottoms out. That structure is exactly what makes recursion a natural fit for the searches, sorts, and tree-like traversals coming next in this unit, where splitting a problem into smaller copies of itself is the whole strategy.

Key terms

base case
The condition simple enough for a recursive method to answer directly, without making another call.
call stack
The structure that stores each method call's own parameters and local variables while it waits for calls below it to finish.
recursive case
The part of a recursive method where it calls itself on a smaller version of the problem.
stack overflow
A crash that happens when recursive calls never reach a base case and the call stack runs out of space.

Watch it explained

  1. How it worksHow does a base case cut the chain of calls and start the answers coming back?
  2. Worked exampleTrace factorial(4) and find the value returned at each level on the way back up.
  3. How it worksHow does every recursive call get its very own copy of the parameters?
  4. Common mistakeWhy isn't recursion simply a loop written in a more confusing way?

Check yourself

Your turn1 of 2
A recursive method sumTo(k) returns 0 when k is 0, and otherwise returns k + sumTo(k - 1). What does sumTo(15) return?

End of topic.