Recursion

Lesson 6 of 20

Watch a method call itself: follow factorial down to its base case and back up as each stack frame unwinds.

The big picture

Shrink the problem

Recursion solves a big problem by calling itself on a smaller one — until the trivial case answers directly.

A method calls itself

factorial(n) is defined as n * factorial(n - 1): each call works on a smaller copy of the same problem.

Base case

The stop condition — the smallest input answered directly. Without it, the calls never end.

Recursive case

The method calls itself with input one step closer to the base case, like n - 1.

The stack remembers

Every pending call waits in its stack frame until the innermost call returns.