← All animations

๐Ÿช† Recursion & the Call Stack

A recursive function is one that calls itself on a smaller version of the problem, trusting that the smaller calls will work โ€” until it hits a base case small enough to answer outright. Each in-flight call gets its own frame on the call stack, the machine's memory of "where to return". Scroll through to watch that stack grow and unwind, see a real recursive algorithm solve Towers of Hanoi, and find out what happens when the stack runs out of room.

1. The call stack โ€” factorial(n) winds down, then unwinds

factorial(n) is defined recursively: n ร— factorial(nโˆ’1), with the base case factorial(0) = 1. Each call pushes a new frame onto the stack (its own local n) before it can return. Nothing multiplies until we reach the base case โ€” then frames pop off in reverse, each multiplying the result coming back up.

function factorial(n) {
  if (n === 0) return 1;  // base case
  return n * factorial(n - 1);  // recursive case
}
factorial(5) click Step โ–ถ

2. Towers of Hanoi โ€” recursion that does something

Move a stack of discs from the left peg to the right, one disc at a time, never placing a larger disc on a smaller one. The recursive idea is elegant: to move n discs, first move the top nโˆ’1 out of the way, then move the largest disc, then move the nโˆ’1 back on top. That always takes exactly 2n โˆ’ 1 moves โ€” the provable optimum.

Move 0 / 7

3. Base case, recursive case & the dreaded stack overflow

Every recursive function needs two things working together:

If the base case is missing (or never reached), the function calls itself forever, pushing frame after frame until the stack fills up and the program crashes with a stack overflow. Press Run faulty recursion to watch countDown(n) that forgot its base case bury the stack.

stack depth: 0