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.
factorial(n) winds down, then unwindsfactorial(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.
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.
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.