How recursion works: base case and the call stack

Video lessonComing soon

1 A smaller copy of the same problem

Our running problem is to count the digits of a number n, where n ≥ 0. For n = 4072, the answer is 4.

A loop can do this, but there is another way to see it. Removing the last digit of 4072 leaves 407. So 4072 has one digit more than 407. In the same way, 407 has one more than 40, and 40 has one more than 4. The number 4 needs no more work. It has 1 digit.

Each question holds a smaller copy of itself. A function can answer it by calling itself on that smaller copy. A function that calls itself is recursive, and the idea is recursion. Trees, backtracking and dynamic programming are all built on it.

2 The base case and the step

Every recursive function has two parts:

  • The base case. An input small enough to answer directly, with no call. Any n below 10 has 1 digit.
  • The recursive step. For any other input, the function calls itself on a smaller input and builds its answer from the result. Here the answer is 1 plus the digit count of n / 10.

The step must move the input towards the base case. Each n / 10 drops one digit, so after a few calls n is below 10 and the calls stop.

It returns 4 for 4072, 1 for 7, and 1 for 0. Whole-number division drops the remainder, so 4072 / 10 gives 407. Python writes it as n // 10, and JavaScript as Math.floor(n / 10).

3 What the call stack holds

When countDigits(4072) calls countDigits(407), the first call is not finished. It still has to add 1 to whatever comes back. So the program remembers two things about it:

  • Its own variables. This call's n is 4072. The next call gets its own n, 407, in a separate place. Changing one never touches the other.
  • Where to carry on. This call stopped in the middle of 1 + countDigits(n / 10). When the answer comes back, it carries on from there.
4072n1 + ?waits at
Frame of countDigits(4072)
407n1 + ?waits at
Frame of countDigits(407)

The program keeps these in a frame, one per call. The frames sit on the call stack. It works like the stack from the standard library lesson: last in, first out.

  • A call pushes a new frame on top.
  • A return pops the top frame and hands its value to the frame below.
  • Only the top frame runs. Every frame under it waits.

4 The trip down and back up

Here is countDigits(4072) step by step. The last column counts the countDigits frames on the stack during that step.

StepnWhat happensFrames
14072Calls on 407, waits1
2407Calls on 40, waits2
340Calls on 4, waits3
44Base case: returns 14
540Gets 1, returns 1 + 1 = 23
6407Gets 2, returns 32
74072Gets 3, returns 41

Steps 1 to 4 are the trip down. Each call pushes a frame and waits, and no answer exists yet. Step 4 reaches the base case, the first call that returns without calling.

Steps 5 to 7 are the trip back up. Each waiting frame gets an answer from above, adds 1, and pops. Finally main, the code that made the first call, receives 4.

mainn = 4072n = 407top →
Step 2: going down
mainn = 4072n = 407n = 40n = 4 → 1top →
Step 4: deepest point
mainn = 4072n = 407 → 3top →
Step 6: coming back up

Steps 2 and 6 have the same frames. At step 2, the frame for 407 is still waiting. At step 6, it has its answer and returns 3.

5 Work before or after the call

The two trips give us two places to put work:

  • Before the call. The work runs on the trip down, from the first call to the last.
  • After the call. The work runs on the trip up, from the last call back to the first.

Two functions show it. Both stop at n = 0 and call themselves on n − 1. They differ only in where the print sits.

For n = 3, the calls are the same in both. Only the moment of each print changes:

TripnprintDown printsprintUp prints
Down33—
Down22—
Down11—
Base0——
Up1—1
Up2—2
Up3—3

So printDown(3) prints 3, 2, 1 and printUp(3) prints 1, 2, 3. In printUp, each frame keeps its own n while it waits. The first print happens at n = 1, just after the base case returns.

6 When the calls never stop

The call stack has limited memory. If the calls never reach a base case, frames pile up until that memory runs out. This is a stack overflow, and the program stops with a Runtime Error. Three mistakes cause it:

  • No base case. Without its if, countDigits(4072) calls on 407, 40, 4, 0, then 0 again forever, because 0 / 10 is 0.
  • An input the base case misses. printUp stops at n == 0. Called with n = −1, it goes to −2, −3 and on, and never meets 0. A base case of n <= 0 catches every input below.
  • A step that does not shrink. Calling countDigits(n) inside countDigits(n) repeats the same input, so the base case never comes.

The first mistake looks like this:

countDigits(n)
    return 1 + countDigits(n / 10)     // no base case

7 Depth is a space cost

Time. Each call does a few steps of its own work. So the time is the number of calls times the work per call. countDigits makes one call per digit, at most 10 for an int. printUp(n) makes n + 1 calls, so it takes O(n) time.

Space. A frame stays on the stack until its call returns. The most frames on the stack at once is the recursion depth, and the extra space is O(depth). countDigits goes at most 10 frames deep. printUp(n) goes n + 1 deep, so it uses O(n) space, even though it stores no array. A loop that prints 1 to n uses O(1).

When we give the space of a recursive solution, we count the depth. Very deep recursion, in the millions of frames, can overflow the stack even with a correct base case. For a plain count from 1 to n, a loop is the safer choice.

A function that calls itself twice, like Fibonacci, makes far more calls than its depth. The lesson on the recursion tree counts them.

8 Trusting the recursive call

Tracing every call works for 4072. It does not work for a call 10⁵ deep, or for a function that calls itself twice. To write recursion, we stop tracing and trust the call instead. We check three things:

  1. The base case is right. countDigits(7) returns 1. We check it by hand.
  2. The step is right if the call is right. We assume countDigits(407) returns 3, without tracing it. Then 1 + 3 = 4 is right for 4072.
  3. Every input reaches the base case. Each n / 10 is smaller, until n is below 10.

When all three hold, the function is right for every input. The base case is right for the smallest inputs. Each bigger input is right because the smaller one below it is right.

We reach for recursion when the answer for an input can be built from the answer for a smaller copy of it: n − 1, n / 10, or a shorter array. The problems in this section, from the sum of the first n numbers to Fibonacci, all have this shape. The next lesson shows two ways to carry the answer: passing it down as a parameter, or returning it up as countDigits does.

The habit to keep: write the base case first. Then write the step as if the call already works, and name the input that shrinks on every call.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.