CS U111 · Lecture 10 · Lesson: first time through

Recursion, from the beginning

One idea at a time, with the reasoning before the code. Allow about 45 minutes, and try each "check yourself" before you open it. The short version, with the in-class activity solved, is on the notes page.

Start here · what's actually new

Recursion is new to almost everyone in the batch. School Python and the JEE syllabus barely touch it, so nobody is a year ahead of you here. And most of it rests on something you've already done: calling a function (Lecture 7). The one new idea is that a function is allowed to call itself. Everything else (each call gets its own copy of its variables, return sends a value back to the caller) works exactly as it did for celsiusToFahrenheit.

Scope: Lecture 10, Recursion in C, which is the last lecture in the mid-sem syllabus. Reading: Hanly & Koffman ch. 9. The announcement asks for conceptual, breadth coverage of lectures, so expect tracing, "what does this print", and "spot the bug", not long recursive programs. Slide 21 (recursion on arrays, sumArrayHelper) is excluded by the instructor, so this page leaves it out.

1 · A problem that contains a smaller copy of itself

Write out 5! (five factorial):

5! = 5 × 4 × 3 × 2 × 1

Look at the tail: 4 × 3 × 2 × 1 is just 4!. So

5! = 5 × 4!

and in general n! = n × (n − 1)!. The answer to the big question is written in terms of the same question, one size smaller. That's all "recursive" means.

The lecture's way of saying it: "I don't know what 100! is. But if someone tells me 99!, I can multiply by 100." You do one tiny piece of work (the multiply) and hand the rest to someone else, who does the same thing one step smaller. Somebody at the bottom must know an answer without asking anyone: 0! = 1. That bottom is what stops the chain.

2 · The two parts every recursive function has

PartIts jobIn factorial
Base caseThe smallest version, answered directly. No further calls.if (n == 0) return 1;
Recursive caseDo a little work and delegate the rest to a smaller call.return n * factorial(n - 1);
int factorial(int n) {
    if (n == 0) {                       /* 1. base case: answer directly      */
        return 1;
    } else {
        return n * factorial(n - 1);    /* 2. recursive case: smaller question */
    }
}

Compiled and run, factorial(5) prints 120 and factorial(3) prints 6. Notice how closely the code reads like n! = n × (n − 1)!.

The lecture's golden rule: write the base case first. It plays the same role as the condition of a while loop that eventually turns false. Without it, nothing ever stops.

Check yourself: what does factorial(1) do? How many times is factorial called in total?

factorial(1) is not the base case (1 ≠ 0), so it returns 1 * factorial(0). factorial(0) is the base case and returns 1. So the answer is 1 × 1 = 1, from 2 calls: factorial(1) and factorial(0). In general factorial(n) makes n + 1 calls.

3 · How to write one: trust the smaller call

Here's the part that surprises people. To design a recursive function you should not trace it all the way down. Tracing 50 paused calls in your head is exhausting and you'll lose your place. Instead, borrow the idea of induction from maths, in three steps:

  1. Base case. What's the simplest version I can answer straight away?
  2. Assume. Pretend the call on a smaller input already works and gives the right answer.
  3. Build. Use that trusted answer to finish the bigger problem.

The lecture's example is be. The simplest exponent is 0, and anything to the power 0 is 1. If someone hands me be−1, I get be by multiplying once more by b.

int computePower(int base, int exponent) {
    if (exponent == 0) {                                   /* 1. base case        */
        return 1;
    }
    int smallerAnswer = computePower(base, exponent - 1);  /* 2. trust this       */
    return base * smallerAnswer;                           /* 3. build on it      */
}

computePower(2, 5) prints 32, and at no point did we follow the exponent down to 0 to write it. Design by trusting; trace only to check or to debug. (In an exam that asks "what does this print", you do have to trace. The next section shows how to do that without getting lost.)

Check yourself: write sumTo(n), which returns 1 + 2 + … + n, using the three steps. What should sumTo(4) give?

Base case: sumTo(0) is 0. Assume sumTo(n - 1) correctly gives 1 + … + (n − 1). Build: add n.

int sumTo(int n) {
    if (n == 0) return 0;
    return n + sumTo(n - 1);
}

sumTo(4) = 4 + 3 + 2 + 1 = 10 (compiled and run: 10).

4 · What C actually does: a new frame for every call

Recall from Lecture 7: every time a function is called, C makes a stack frame, a private box holding that call's parameters and local variables. Recursion uses exactly the same mechanism. When factorial(3) calls factorial(2), C does not jump back to the top and overwrite n. It pauses the factorial(3) frame (with its n = 3 still inside) and makes a brand-new frame with its own n = 2. Because C passes arguments by value, the frames never share n.

So a recursive call runs in two phases:

Tracing factorial(3). Left arrows: winding (each call pauses). Right arrows: unwinding (answers flow back up). At the deepest point, four factorial frames exist at once, each with its own n.

Step through it yourself. Pick a function and an n, then press Step. The newest frame is on top, as on a real call stack, and a paused frame says what it's waiting for.


  

Blue frame: running now. Grey frame: paused, waiting for the call above it. Green: about to return. The box under the stack shows what has been printed so far.

Check yourself: during factorial(4), how many factorial frames are on the stack at the deepest point? Which one returns first?

Five: factorial(4), (3), (2), (1) and (0). The last one called returns first: factorial(0) returns 1 before anything else can finish. That's why it's called a stack: last in, first out.

5 · Code before the call vs code after it

This is the single most testable idea in the lecture. Look where the two printfs sit relative to the recursive call:

void confusingPrint(int n) {
    if (n == 0) { return; }
    printf("Winding: %d\n", n);      /* BEFORE the call */
    confusingPrint(n - 1);
    printf("Unwinding: %d\n", n);    /* AFTER the call  */
}

Run in the widget above with n = 3, or compiled:

Winding: 3
Winding: 2
Winding: 1
Unwinding: 1
Unwinding: 2
Unwinding: 3

Why: a frame prints its "Winding" line as it goes down, so those come out in calling order, 3, 2, 1. Its "Unwinding" line can't run until the call below it has completely finished. The deepest frame (n = 1) finishes first, so those come out reversed: 1, 2, 3.

The rule to carry into the exam

Before the call → printed in calling order. After the call → printed in reverse order. A print in both places gives a mirror image.

Check yourself: what do up(4) and down(4) print?
void up(int n)   { if (n == 0) return; up(n - 1);   printf("%d ", n); }
void down(int n) { if (n == 0) return; printf("%d ", n); down(n - 1); }

down prints before its call, so it's in calling order: 4 3 2 1. up prints after, so it's reversed: 1 2 3 4. (Compiled: 1 2 3 4 | 4 3 2 1.) The only difference between the two functions is which line comes first.

6 · Three ways a recursive function goes wrong

Each of these was compiled with clang -Wall -Wextra on a Mac and run. The messages below are clang's own words.

1 · No base case: it never stops

int infiniteFactorial(int n) {
    return n * infiniteFactorial(n - 1);    /* n: 3, 2, 1, 0, -1, -2 ... forever */
}

clang warns at compile time: "all paths through this function will call itself". If you run it anyway, the frames pile up until the memory set aside for the call stack runs out, and the operating system kills the program: a stack overflow, reported as a segmentation fault (exit status 139). This is recursion's version of an infinite loop. It crashes rather than hanging, because each call uses up more memory.

2 · A base case that's never reached

int badFactorial(int n) {
    if (n == 0) {
        return 1;
    } else {
        return n * badFactorial(n + 1);     /* n grows: 3, 4, 5 ... never 0 */
    }
}

Having a base case isn't enough: each call must move closer to it. n + 1 moves away from 0. This one is nastier, because clang prints no warning at all. It still crashes with a segmentation fault when run.

3 · Forgetting to return the result

int faultyFactorial(int n) {
    if (n == 0) {
        return 1;
    }
    n * faultyFactorial(n - 1);    /* computed... then thrown away */
}

clang gives two warnings: "expression result unused" on the multiply line, and "non-void function does not return a value in all control paths" at the closing brace. (The slide quotes GCC's wording for the same two problems: "value computed is not used" and "control reaches end of non-void function".) It runs, but what comes back is undefined. On this Mac, faultyFactorial(3) printed 1, and so did every n from 0 to 5: right for 0 and 1, wrong for everything else. On another machine it might print something else. Every path through a non-void function must return a value.

Check yourself: int count(int n) { if (n == 0) return 0; return 1 + count(n - 2); }. What happens for count(6)? For count(7)?

count(6): 6 → 4 → 2 → 0, so it hits the base case and returns 1 + 1 + 1 + 0 = 3. count(7): 7 → 5 → 3 → 1 → −1 → −3 … It jumps over 0 and never reaches it, so it's bug 2: a stack overflow. The fix is if (n <= 0) return 0;, after which count(7) returns 4 (compiled: count(7)=4 count(6)=3). Testing == 0 when the steps can skip over 0 is a classic exam trap.

7 · When one call becomes two: Fibonacci

The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, …: each is the sum of the two before it. The definition is recursive with two smaller copies, so the code makes two calls:

int fibonacci(int n) {
    if (n == 0) return 0;
    else if (n == 1) return 1;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Now each call can spawn two more, which can spawn four. A stack picture gets messy, so we draw a recursion tree: every node is one call, and its children are the calls it makes.

The recursion tree of fib(4), drawn from the code's own calls. The small number above each node is the order in which the call starts. Shaded nodes repeat work that was already done elsewhere in the tree.

Two things the tree shows:

n0123456
fibonacci(n)0112358
total calls (counted by the compiled program)113591525
Check yourself: how many calls does fibonacci(5) make, counting the first one? (Use the tree: fib(5) = one node plus the trees of fib(4) and fib(3).)

1 + 9 + 5 = 15. The rule behind it: calls(n) = 1 + calls(n − 1) + calls(n − 2), with calls(0) = calls(1) = 1. Its value, fibonacci(5), is 5.

8 · Recursion through a partner: mutual recursion

So far every function called itself by name. That's direct recursion. It can also go round a loop of two (or more) functions, which is called indirect or mutual recursion:

bool isOdd(int n);                 /* prototype: isEven uses isOdd before it's defined */

bool isEven(int n) {
    if (n == 0) return true;
    return isOdd(n - 1);
}
bool isOdd(int n) {
    if (n == 0) return false;
    return isEven(n - 1);
}

The idea: n is even exactly when n − 1 is odd. isEven(3) → isOdd(2) → isEven(1) → isOdd(0), which is a base case returning false. That false is passed straight back up, so isEven(3) is false, which is correct, since 3 is odd. (Compiled: isEven(3)=0 isOdd(3)=1 isEven(4)=1. The slide ends this chain with "— true". isOdd(0) returns false, so the chain's answer is false.)

The prototype line on top is Lecture 7's rule at work: isEven calls isOdd before the compiler has seen it, and clang on the Mac rejects an undeclared call as an error.

9 · Tail recursion: nothing left to do after the call

In return n * factorial(n - 1); the multiply has to wait until the call comes back, so every frame must be kept. Compare:

int tailFactorial(int n, int accumulator) {
    if (n == 0) return accumulator;
    return tailFactorial(n - 1, n * accumulator);   /* multiply BEFORE the call */
}

Here the multiplication happens before the call, and the call is the very last thing the function does. That's tail recursion. The running product travels down in accumulator: tailFactorial(3, 1) → (2, 3) → (1, 6) → (0, 6), which returns 6. The 6 just gets passed back unchanged (compiled: 6; and tailFactorial(5, 1) = 120).

Since no frame has work left, some compilers reuse one frame for the whole chain (tail call optimisation). So "recursion always uses more memory" isn't strictly true.

Check yourself: is return n + sumTo(n - 1); tail recursive? What about return isOdd(n - 1);?

sumTo: no. The n + still has to happen after the call returns. isEven's return isOdd(n - 1);: yes. The call's answer is returned as it is, with nothing left to do.

10 · Recursion or a loop?

FactorIteration (loops)Recursion
Memorylow: one set of variableshigher: one frame per call
Speedgenerally fasterextra cost for every call
Code lengthcan be longer for nested logicoften shorter, closer to the maths
Best forcounting, totals, simple traversalproblems defined by a smaller copy of themselves
When it goes wronginfinite loop (hangs)stack overflow (crashes)

Neither is "better". They're two shapes for repetition. If you're forcing recursion onto plain counting, a loop was the right tool.

Check yourself (an MCQ the lecture invites): "A recursive function with a reachable base case can still crash with a stack overflow." True or false?

True, in two ways. The arguments might jump past the base case (like count(7) in section 6). Or the base case is reachable but very far away, e.g. factorial(1000000) needs a million frames, which is more than the stack holds. The lecture's own summary: "A missing or non-converging base case causes a stack overflow, not a freeze."

11 · You're ready: what to do next

Asking an AI well: three prompts pinned to Lecture 10

"I'm learning recursion in C (Hanly & Koffman ch. 9, no pointers, no arrays in recursion yet). Give me six short recursive functions that print before and/or after the recursive call. Let me predict the output for one small input each, then show the winding and unwinding trace."

"Give me five recursive C functions, each with exactly one bug: missing base case, argument moving away from the base case, a base case the steps jump over, or a missing return. Don't tell me which. I'll name the bug and say what happens when it runs."

"Here is my digitSum [paste it]. Don't rewrite it. Ask me questions that would make me check my base case, and whether the argument always gets closer to it."

Trace by hand first. In the exam there is no compiler.