A recursive function solves a problem by calling itself on a smaller instance. Correctness depends on knowing when to stop and why each recursive step gets closer to that stopping case.
Worked example
To sum a list, define the empty-list sum as zero. For a nonempty list, add its first value to the sum of the remaining values. The number of remaining elements decreases by one on each call, so the process eventually reaches the empty list. The same total can be computed with a loop and a running accumulator.
What to check
Account for the call stack when estimating memory. A straightforward recursive scan takes linear stack space, while the accumulator loop can use constant extra space. In languages with limited recursion depth, a mathematically terminating definition can still fail on a long input. Prefer recursion when the structure of the problem makes the calls easier to follow and the depth is controlled.
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithms Made Simple.
Companion article for Algorithms Made Simple, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
