← All coursesDSA Foundations

Lesson 14 of 19

Recursion

To find the sum from 1 to n, add n to the sum of a smaller range. Each call pauses until the smaller call returns. At zero, we already know the answer.

Each call remembers its unfinished work

A recursive function solves a smaller version of its own problem. Its base case supplies a direct answer. Each waiting call keeps a stack frame with the work still to do. When the base case returns, the most recent waiting call resumes first.

Work through an example

For the sum of the integers from 1 to 2, how many calls are on the stack when sum(0) begins, and what comes back up?

Step-by-step solution
  1. sum(2) pauses with 2 to add. sum(1) pauses with 1 to add. sum(0) begins, so there are three calls on the stack.
  2. sum(0) returns 0. The waiting sum(1) can now return 1 + 0, which is 1.
  3. sum(2) returns 2 + 1, which is 3. Each call needed its own place to remember the addition it had postponed.
JavaScript example
// n is a nonnegative integer.
function sum(n) {
  if (n === 0) return 0;
  return n + sum(n - 1);
}
sum(2); // 3
DSA compiler

Try it yourself

Finish the animation to unlock this question.

Which rule lets sum(n) = n + sum(n − 1) stop for nonnegative n?

Related exercise · Solve the Tower of Hanoi · Take the end-of-stage challenge