Recursion

Lesson 6 of 20

A function that calls itself: watch factorial stack its frames, hit the base case and unwind the answer.

The big picture

Solve big by thinking small

Recursion solves a problem by calling the same function on a smaller copy of it — until a trivial case returns.

Base case

The input where the function stops recursing and just returns — the exit door.

Recursive case

The function calls itself with a smaller input, trusting the smaller answer.

The call stack

Every pending call parks a frame on the stack — factorial(3) stacks three frames.

Unwinding

The base case returns first; answers combine as the frames pop.

No base case?

Frames pile up forever — the crash is called a stack overflow.