Visualize

Pattern visualizer

Factorial & the Call Stack

Recursion solves a problem by calling itself on a smaller input and trusting that smaller answer. The hidden machinery is the call stack: every call pushes a frame holding its paused work, and answers flow back as frames pop in reverse order. Each cell here is one stack frame — watch them pile up to the base case, then unwind carrying the products home. Animated on: Compute factorial(5) = 5 x 4 x 3 x 2 x 1 recursively, watching the call stack grow to depth 5 and then unwind..

Frames push down to the base case, answers unwind back up

time O(n)space O(n)step 1 / 11
f(5)
[0]
line 6

Call factorial(5). A frame for it is pushed onto the call stack — the stack is how the program remembers who is waiting for whom.

Pseudocode
1FUNCTION factorial(n):
2 IF n == 1:
3 RETURN 1 (base casestops the descent)
4 (pause here until the smaller call answers)
5 RETURN n * factorial(n - 1)
6call factorial(5)

← / → step · space play · Home restart

Where to practice Recursion