CS U111 · Lecture 10 · Notes: the revision map

Recursion, in one page

Rule cards, the in-class activity solved, three predict-the-output examples at exam level, two slide corrections, and the trap table. First time with recursion? Start with the lesson, which has the call-stack stepper.

Start here · what's in scope

Scope: Lecture 10, Recursion in C, the last lecture in the mid-sem syllabus. Reading: Hanly & Koffman ch. 9. The instructor asks for conceptual, breadth coverage of lectures (depth is reserved for Lab Sheets up to 5a), and excludes slide 21 (recursion on arrays, sumArrayHelper). So the likely questions are: trace a call and give its value, predict what gets printed, count calls, spot why a function crashes or returns garbage, and true/false on recursion vs iteration.

Recursion is new to nearly everyone. It isn't in the school syllabus, and none of the three past CS F111 mid-sem papers on the past-papers page asks about it, so nobody has drilled these questions. It leans on one thing you already have: how a function call works (own frame, own copies of the parameters, return goes back to the caller).

The whole thing in one idea

A recursive function answers a question by asking the same question one size smaller and doing one small step with the answer. Every call gets its own frame with its own n. Calls pile up while going down (winding), stop at a base case that answers directly, then finish in reverse order on the way back up (unwinding).

CallWinding (going down)Unwinding (coming back)
factorial(3)3 * factorial(2) … paused3 * 2 = 6
factorial(2)2 * factorial(1) … paused2 * 1 = 2
factorial(1)1 * factorial(0) … paused1 * 1 = 1
factorial(0)base case: returns 1 directly. Unwinding starts here.

Rule cards

1 · Two parts, base case first

Every recursive function.

int factorial(int n) {
    if (n == 0) return 1;              /* base case: answer directly         */
    return n * factorial(n - 1);       /* recursive case: smaller question   */
}

factorial(n) makes n + 1 calls; at the deepest point n + 1 frames exist at once.

2 · Design by trusting the smaller call

Writing one: base case → assume the smaller call works → build on it.

int computePower(int base, int exponent) {
    if (exponent == 0) return 1;
    return base * computePower(base, exponent - 1);    /* computePower(2, 5) = 32 */
}

Trace to check or debug; don't trace to design.

3 · Every call must move toward the base case

Checking any recursive function, yours or the examiner's.

return n * f(n + 1);    /* moves AWAY from n == 0: crash          */
if (n == 0) … f(n - 2)   /* odd n jumps OVER 0: crash; use n <= 0 */

No base case, or one that's never reached → stack overflow (a crash, reported as a segmentation fault), not a freeze.

4 · Every path of a non-void function returns

Any recursive case that "computes" its answer.

n * faultyFactorial(n - 1);          /* WRONG: computed, then thrown away  */
return n * faultyFactorial(n - 1);   /* right                              */

clang: "expression result unused" and "non-void function does not return a value in all control paths". The value that comes back is undefined.

5 · Before the call: calling order. After the call: reversed

Every "what does this print" question.

printf(…n…); f(n - 1);        /* f(3) prints 3 2 1 */
f(n - 1); printf(…n…);        /* f(3) prints 1 2 3 */

A print on both sides gives a mirror: confusingPrint(3) → Winding 3, 2, 1 then Unwinding 1, 2, 3.

6 · Two calls make a tree; count its nodes

fibonacci, mystery, anything with two recursive calls.

calls(n) = 1 + calls(n - 1) + calls(n - 2),   calls(0) = calls(1) = 1
n:      0  1  2  3  4   5   6
calls:  1  1  3  5  9  15  25        /* counted by the compiled program */

The whole left branch finishes before the right one starts (on clang; C doesn't fix the order of the two sides of +). Repeated subtrees are wasted work: in fib(4), fib(2) runs twice and fib(1) three times.

7 · Direct, mutual, tail

Vocabulary MCQs.

f calls f                                /* direct                              */
isEven calls isOdd calls isEven          /* indirect (mutual): needs a prototype */
return tailFactorial(n - 1, n * acc);    /* tail: the call is the LAST action    */

return n * f(n - 1); is not tail recursive: the multiply waits for the call. Tail calls can reuse one frame (tail call optimisation), on some compilers.

8 · Recursion vs iteration

True/false and "which is better" questions.

Loops: one set of variables, generally faster, failure is an infinite loop (hangs). Recursion: one frame per call, extra cost per call, often shorter and closer to the maths, failure is a stack overflow (crashes). Neither is strictly better. Use loops for counting, totals and plain traversal; use recursion when the problem is defined by a smaller copy of itself.

Three worked examples at evaluation level

Worked example 1 · the in-class activity, parts 1–2

Trace mystery(5) by hand

int mystery(int n) {
    if (n <= 1) return n;
    return mystery(n-1) + mystery(n-2);
}

What does mystery(5) return? Identify the base case and recursive case. Does the argument move toward the base case every call?

  1. Name the parts. Base case: n <= 1, which returns n itself (so mystery(1) = 1 and mystery(0) = 0). Recursive case: the sum of the two calls one and two smaller. This is the lecture's fibonacci in disguise.
  2. Converges? Yes. Both calls make n smaller. Stepping down by 1 or 2 from any n ≥ 2 lands on 1 or 0, and <= 1 catches both. (If the test were n == 1, then mystery(2) would call mystery(0), which calls mystery(-1), and so on. The compiled version of that crashes with exit status 139.)
  3. Don't expand the whole tree; build small values up. Each value only needs the two below it:
    callworks out asvalue
    mystery(0)base case0
    mystery(1)base case1
    mystery(2)mystery(1) + mystery(0) = 1 + 01
    mystery(3)mystery(2) + mystery(1) = 1 + 12
    mystery(4)mystery(3) + mystery(2) = 2 + 13
    mystery(5)mystery(4) + mystery(3) = 3 + 25
  4. Answer: 5 (compiled: mystery(5)=5). If a question asks how many calls are made, use card 6: 15, counting the first call.

The bottom-up table is the safe way to trace any two-call recursion on paper: the real program recomputes values, but the values themselves never change.

Worked example 2 · the in-class activity, parts 3–4

Write digitSum(n), then trace digitSum(123)

Recursively sum the digits of a positive integer (digitSum(1234) = 10). Find your own base case first.

  1. Two facts from Lab 4's digit loops. n % 10 is the last digit and n / 10 drops it: 123 % 10 = 3, and 123 / 10 = 12 (integer division).
  2. Base case. The simplest number is a single digit, whose digit sum is itself: if (n < 10) return n;
  3. Trust and build. Assume digitSum(n / 10) correctly sums all the digits except the last. Then add the last one.
    int digitSum(int n) {
        if (n < 10) return n;                 /* one digit: its own sum          */
        return n % 10 + digitSum(n / 10);     /* last digit + sum of the rest    */
    }
  4. Trace digitSum(123), going down and then coming back:
    phasecallwhat happens
    windingdigitSum(123)123 ≥ 10: needs 3 + digitSum(12). Pauses.
    windingdigitSum(12)12 ≥ 10: needs 2 + digitSum(1). Pauses.
    basedigitSum(1)1 < 10: returns 1.
    unwindingdigitSum(12)2 + 1 = returns 3.
    unwindingdigitSum(123)3 + 3 = returns 6.
    The compiled program, with a print at each call and return, shows exactly this:
    call digitSum(123)
      call digitSum(12)
        call digitSum(1)
        digitSum(1) returns 1
      digitSum(12) returns 3
    digitSum(123) returns 6
  5. Another valid base case. if (n == 0) return 0; also works, with one extra call at the bottom (compiled: 6 for 123, and 0 for 0). Either is fine in an exam if it's correct. What's not fine is no base case, or one the argument can't reach.

Worked example 3

Predict-the-output, MCQ style: three quick ones

(a) What does show(5) print?

void show(int n) {
    if (n <= 0) return;
    printf("%d ", n);
    show(n - 2);
    printf("%d ", n);
}
  1. The calls are show(5) → show(3) → show(1) → show(-1), which is a base case (-1 <= 0, so it returns and prints nothing).
  2. The prints before the call come out in calling order: 5 3 1. The prints after the call come out reversed: 1 3 5 (card 5).
  3. Output: 5 3 1 1 3 5 (compiled). The <= matters: with == 0, the steps 5, 3, 1, −1 jump over 0 and the program crashes.

(b) What does f(6) return?

int f(int n) {
    if (n == 0) return 0;
    return n % 2 + 10 * f(n / 2);
}
  1. Winding: f(6) needs 0 + 10·f(3); f(3) needs 1 + 10·f(1); f(1) needs 1 + 10·f(0); f(0) = 0.
  2. Unwinding: f(1) = 1 + 0 = 1. f(3) = 1 + 10 = 11. f(6) = 0 + 110 = 110.
  3. That's 6 written in binary. The remainders % 2 are produced last-digit-first, and the 10 * on the way back up puts them in the right order (Lecture 3's divide-by-2 method, done by recursion). Compiled: f(6)=110, and f(13)=1101.

(c) faultyFactorial(3) (the one with the missing return, card 4) returns:
(i) 6   (ii) 0   (iii) 3   (iv) an undefined value: the compiler warns, and the result depends on the machine

  1. The recursive case computes n * faultyFactorial(n - 1) and throws it away, then falls off the end of an int function without a return.
  2. Answer: (iv). On this Mac it happened to print 1 for every n from 0 to 5. That's not a value you can predict on paper, which is the point.
Two slide corrections (checked with clang)

1. Slide 17, mutual recursion. The slide says "isEven(3) calls isOdd(2), which calls isEven(1), which calls isOdd(0) — true." But isOdd(0) is a base case that returns false, and that false is passed back up unchanged. So isEven(3) is false, which is right, because 3 is odd. Compiled: isEven(3)=0 isOdd(3)=1 isEven(4)=1.

2. Slide 15, "C evaluates depth-first, left to right". C doesn't guarantee which side of fibonacci(n - 1) + fibonacci(n - 2) is called first; the standard leaves the order of the operands of + unspecified. clang does call the left one first (checked by printing each call: 4 3 2 1 0 1 2 1 0), so the slide's tree order is what you'll see on a Mac. The value is the same either way. Only output printed inside the calls could come out in a different order on another compiler.

Two smaller points. Slide 13 quotes GCC's warnings; clang's wording for the same problems is "expression result unused" and "non-void function does not return a value in all control paths". And slide 11's "Segmentation fault (core dumped)" is the Linux wording; on a Mac the program is killed by the same signal (exit status 139). Also, clang warns about slide 11's missing base case ("all paths through this function will call itself"), but says nothing about slide 12's n + 1, which crashes just the same.

Classic traps: the standard ways marks are lost

The mistakeWhat you seeThe fix
No base caseStack overflow: segmentation fault. clang: "all paths through this function will call itself"Write the base case first
Argument moves away: f(n + 1) toward a base case of 0Same crash, and no warningCheck every call makes the argument strictly closer
Steps jump over the base case: n == 0 with f(n - 2) and odd n7, 5, 3, 1, −1, … crashn <= 0
Forgot return in the recursive caseUndefined value (1 for every n on this Mac). Two warningsreturn n * f(n - 1);
Printing order read top-downWriting 3 2 1 when the print is after the callCard 5: after the call = reversed
Expanding a two-call tree in your headLost place, wrong totalBuild values bottom-up (worked example 1)
Call count off by onefactorial(3) "makes 3 calls"Count the first call and the base-case call: 4
"Recursion always uses more memory than a loop" marked trueTail calls can reuse one frame (tail call optimisation)"Generally", not "always"
"A stack overflow makes the program hang"It crashes: the stack runs out of memoryHanging is the infinite loop; recursion crashes
Mutual recursion without a prototypeclang on the Mac: undeclared function, an errorDeclare bool isOdd(int n); above isEven
n * f(n - 1) called tail recursiveThe multiply runs after the callTail = the call is the last action

Minimal prerequisite kit

FactWhere it's used
A call gets its own frame and its own copies of the parameters; return sends one value back to the caller (functions notes)Every trace: each n is separate
A function must be declared before it's called: a prototype (functions notes)Mutual recursion
n % 10 = last digit, n / 10 drops it; int ÷ int drops the fraction (loops notes)digitSum, f(n / 2)
Dividing by 2 and collecting remainders gives binary (number systems)Worked example 3(b)
n! = n × (n − 1) × … × 1, with 0! = 1; Fibonacci 0, 1, 1, 2, 3, 5, 8The lecture's examples

What to practise

SkillDrill it onTextbook backup Hanly ch. 9How many
Winding and unwindingThe lesson's stepper: predict each step before clicking, for confusingPrint(4)The chapter's early tracing examples2 runs · 10 min
Predict the output / the valueThe recursion drillSelf-check exercises in the first sections, odd-numbered1 sheet · 15 min
Two-call trees and call countsWorked example 1, then mystery(6) (answer 8, 25 calls)—2 · 10 min
Spot the bugThe trap table: for each row, write a 3-line function with that bug and say what happensThe chapter's "common programming errors" section4 · 10 min
Write one from scratchdigitSum, sumTo, computePower, typed blind, then runEnd-of-chapter programming exercises, odd-numbered3 · 15 min

Section titles rather than numbers, because editions renumber; check your copy of the 8th edition. Skip anything with array or string parameters (that's the excluded slide 21), and Towers of Hanoi, unless the instructor names them.

Don't do this before the mid-sem

Don't start memoisation, Towers of Hanoi, recursive binary search, permutations or "top 50 recursion interview problems". None of it is in Lecture 10, and slide 21 (recursion on arrays) is explicitly out. The lecture is tested for breadth: tracing, printing order, call counts, bugs, and the comparison with loops.