AlgoFrames

Recursion: base case, recursive case, the call stack

A recursive function solves a problem by calling itself on a smaller one until it reaches a base case. Watch frames push on each call and results flow back.

The idea

To count down from 3, you say 3 and then count down from 2. The task holds a smaller copy of itself.

A recursive function uses this idea. It solves a small part, then calls itself on the rest.

Intuition

fact(3) needs fact(2), which needs fact(1). Each waiting call keeps a frame on the call stack.

A frame holds one call's own n and the spot to resume. The top frame is the call running now.

fact(1) answers 1 at once: the base case. The answers then flow back up: 2 × 1 = 2, then 3 × 2 = 6.

Every recursive function has two parts. The base case answers directly. The recursive case calls itself on a smaller input and uses that answer.

Complexity

fact(n) makes n calls, each doing one multiply. Time is O(n).

The calls form a chain: fact(n), fact(n - 1), down to fact(1). There are n of them.

All n frames sit on the stack at the deepest point. Space is O(n), even with no array in the code.

The call stack is memory too. A loop version of factorial needs only O(1) space.

Variations

Sum of digits uses the same shape. Take the last digit and add the sum of the rest.

Work done after the call returns runs in reverse order. countUp lists 1, 2, 3 this way.

Code

Pseudocode

function fact(n)
  if n ≤ 1: return 1
  return n × fact(n - 1)

Python

def fact(n):
    if n <= 1:
        return 1
    return n * fact(n - 1)

JavaScript

function fact(n) {
  if (n <= 1) return 1;
  return n * fact(n - 1);
}

Java

static long fact(int n) {
    if (n <= 1) return 1;
    return n * fact(n - 1);
}

Practice problems (6)

Factorial trace Warm-up

This version of fact prints each result just before it returns. What does fact(4) print? Write the numbers in order, separated by spaces.

Sum of digits Warm-up

Return the sum of the decimal digits of n, using recursion. For example, 472 gives 4 + 7 + 2 = 13.

The last digit is n % 10 and the rest of the number is n / 10 rounded down.

Missing base case Standard

sumTo(n) should return 0 + 1 + … + n for any n ≥ 0. It works for sumTo(3) but crashes with a stack overflow for one input. Click the line with the bug, then fix it.

Countdown Standard

Return the list [n, n - 1, …, 1] using recursion and no loop. countdown(0) returns the empty list.

Follow the frames of fact(4) Standard

Follow fact(4) as frames push and pop. Answer each question before the step plays.

Print 1..n without loops Challenge

Return the list [1, 2, …, n] with no loop of any kind. countUp(0) returns the empty list.

The recursive call must still count down from n. Decide whether n goes before or after the result of the call.

Related topics

Next on the path: Recursion trees: Fibonacci and repeated work