▶  Watch

Recursion vs Iteration: Two Shapes for the Same Job (and Why One Crashes)

Recursion solves a problem by having a function call a smaller version of itself down to a base case, then combines the answers back up — a natural fit for self-similar problems. Iteration solves the same problem with a loop and a running total, and never grows the call stack.

CS Fundamentals Algorithms
What this teaches

Recursion calls a smaller version of itself down to a base case, then combines the answers back up — code that mirrors self-similar problems like trees, graphs, and divide-and-conquer. Iteration carries a running total through a loop in a single flat pass. The catch: every open recursive call waits on the call stack, one frame per call, so a deep enough recursion overflows the stack, while a loop never grows it at all — same answer, very different memory.

Transcript

Every programmer hits this fork: solve a repeating problem with a loop, or with a function that calls itself. Same job, two very different shapes. Recursion is Russian nesting dolls; iteration is climbing stairs. So which shape fits your problem — and why does one of them crash?

Recursion is a function that calls a SMALLER version of itself — opening doll after doll — until it hits the smallest one: the base case. Then it combines the answers back up. The code mirrors the problem: factorial of n is n times factorial of n-minus-one. Elegant for anything self-similar.

Iteration is a loop: a worker climbing stairs one at a time, carrying a running total in a variable, ticking a counter until the job is done. No function calls itself, no dolls to reopen — just one flat pass, updating state as it goes. Natural for linear, straight-line repetition.

Here's the catch that bites everyone. Each open recursive call waits on the CALL STACK — one frame for every doll you haven't closed yet. Go too deep, and the stack overflows — that's the crash. A loop keeps its state in plain variables and never grows the call stack. Same answer, very different memory.

So reach for recursion when the problem is self-similar — trees, graphs, divide-and-conquer — where the recursive code mirrors the structure beautifully. Reach for iteration for flat, linear work — or when depth could be huge and recursion would blow the stack. Any recursion converts to a loop, sometimes with an explicit stack.

Same power, different shape: recursion nests a function inside itself down to a base case; iteration lines the work up in a row and carries the state. So next time you're stuck choosing, ask one thing: does my problem nest inside itself, like dolls — or line up in a row, like stairs?

← All videos · Vibe Engines · 2026