Stacks exist because one situation shows up again and again in computing: the most recent unfinished thing has to be finished first. A function that called another function can't continue until that call returns. An editor's undo must reverse your latest change before older ones. A closing bracket must match the latest opening bracket. Whenever "latest first" is the rule, a stack is the natural tool.
Every time a function is called, your computer pushes a frame onto the call stack: the function's local variables and the place to come back to when it finishes. When the function returns, its frame is popped and the caller carries on exactly where it paused. Recursion is nothing more than this stack growing and shrinking:
Members only · free account
The rest of this lesson, with 6 more sections, 3 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson