CS U111 · Lab 8 · Recursion

Lab 8, every problem worked

The three solved problems, all eight practice problems, the four debugging exercises, the four dry runs, the Change Maker challenge and recursive prime factorisation. Each one starts with its opening move, the base case and the smaller version of the same problem, before any code. Every program on this page was compiled with clang -Wall -Wextra -std=c11 and run against the sheet's own test cases. Every output shown is from a real run.

Start here · what's new and what isn't

Most of this sheet is Lecture 10 again: base case, recursive case, the call stack winding and unwinding, Fibonacci's tree, mutual and tail recursion. The recursion lesson and notes already cover all of that. If "winding" and "unwinding" aren't solid yet, do one sheet of the recursion drill first (15 minutes).

The new part is what the sheet asks you to build. Lecture 10 stopped at numbers. This lab adds recursion over arrays and strings (Lecture 10's slide 21, which was left out of the mid-sem), the wrapper/helper pattern, and problems where one call makes two, three or four calls: Hanoi, flood fill, the maze, exact change. None of this is school material, and JEE preparation doesn't cover writing recursive C. Everyone in the lab is meeting these problems for the first time.

Why it matters for marks: lab evaluations are unannounced and open book (10% across the semester), and the end-semester lab exam is open book at a keyboard (25%).

The opening move · three questions, before any code

If you understand a solution once you see it but can't get started yourself, the missing step is usually this one. Answer these three questions on paper first. The code then follows from your answers.

  1. What is the smallest input I can answer without thinking? That is the base case. It is usually 0, 1, an empty range (left > right), or "off the grid".
  2. If someone handed me the answer for a slightly smaller input, what one step would finish my job? That is the recursive case. Choose the smaller input so that the last step is easy.
  3. Does every call move toward the base case? Name the number that shrinks: n, size, right − left, the number of open cells. If you can't name one, the program will crash with a stack overflow.

The table below answers all three questions for every problem on the sheet. Read across a row, then cover it and try the next one yourself.

ProblemBase caseSmaller version + one stepWhat shrinks
Fast powerexp == 0 → 1xn/2, then square it (× x once more if n is odd)exp halves
Hanoi1 disk → move itmove n−1 out of the way, move the big disk, move n−1 back on topdisk count
Binary searchleft > right → −1; middle matches → midsearch one halfright − left halves
P1 digit sumn < 10 → ndigit sum of n / 10, + last digit n % 10one digit fewer
P2 binaryn < 2 → print nprint n / 2 in binary, then print n % 2n halves
P3 palindromeleft >= right → trueskip junk, or compare the ends and go inwardright − left
P4 flood filloff grid, or not the target colour → stoppaint this cell, then flood the 4 neighboursunpainted target cells
P5 exact changetarget == 0 → true; no coins or target < 0 → falseuse the last coin, or don'tcoins left
P6 mazeoff grid or a wall → false; open cheese cell → truecan I finish from the cell to the right? Or from the one below?distance to the corner
P7 Pascalk == 0 or k == n → 1add the two values aboverow n
P8 min stepsn == 1 → 01 + the best of the (up to) three movesn
Change Makertarget == 0 → 1 way; no coins or target < 0 → 0ways using the last coin again + ways never using ittarget or size
Prime factorsn == 1 → stop; divisor² > n → print ndivides? print it and factor n / d; else try d + 1n or √n − d
The two-hour path, in order
  1. 15 min: the four dry runs. Write your answer on paper before you open the box. Dry run 2 has a trap that catches most people.
  2. 15 min: the four debugging exercises. For each one, say the bug in a single sentence, then write the fix.
  3. 60 min: practice problems at the keyboard, shortest first: 1, 2, 7, 3, 6, 4. Fill in the opening-move row first, then write the code, then compare with this page.
  4. 15 min: what we found, to skim at the end.

Problems 5 and 8 and the two challenges are for a free evening. They all use "try every option and keep the best", which is the hardest idea on the sheet. The three solved problems (section 1) are already worked on the sheet. Read our notes on them only if their output or call counts surprise you.

On this page
  1. The sheet's three solved problems: fast power, Tower of Hanoi, recursive binary search
  2. Dry runs 1–4, with full call-stack traces
  3. Debugging exercises 1–4
  4. Practice problems: 1 · digit sum · 2 · binary · 3 · palindrome · 4 · flood fill · 5 · exact change · 6 · maze · 7 · Pascal · 8 · min steps
  5. Challenges: the Change Maker · recursive prime factorisation
  6. What we found when we ran the sheet

1 · The three solved problems (sheet §11)

The sheet gives full code for these, and each one compiled without warnings and printed what the sheet says. What follows is the opening move for each, the real output, and what the sheet leaves out.

Solved problem 1 · sheet §11.1

Fast power by halving

Lab sheet §11.1 · the question, as set

Write a recursive function to compute xn (where x is the base and n is a positive integer exponent) that requires significantly fewer steps than the standard sequential multiplication approach.

How to start. Base case: x0 = 1. Smaller version: xn/2 with integer division, so 10 → 5 → 2 → 1 → 0. One step: square it. If n was odd, the division dropped one factor of x, so multiply by x once more. 25 = (22)2 × 2 = 16 × 2. What shrinks: the exponent halves each call.

The sheet's code, with its comments shortened:

#include <stdio.h>

long long fastPower(int base, int exponent) {
    if (exponent == 0) {
        return 1;
    }
    long long halfPower = fastPower(base, exponent / 2);
    long long fullPower = halfPower * halfPower;
    if (exponent % 2 != 0) {
        fullPower = fullPower * base;
    }
    return fullPower;
}

int main(void) {
    int base = 2;
    int exp = 10;
    printf("%d raised to the power of %d is %lld\n",
           base, exp, fastPower(base, exp));
    return 0;
}
% ./a.out
2 raised to the power of 10 is 1024

The point of halving, measured. We counted calls for the sheet's fastPower and for the one-step-at-a-time computePower from §5.2:

% ./a.out
2^10: fast = 1024 (5 calls), slow = 1024 (11 calls)
3^5: fast = 243 (4 calls), slow = 243 (6 calls)
5^0: fast = 1 (1 calls), slow = 1 (1 calls)
2^62: fast = 4611686018427387904 (7 calls), slow = 4611686018427387904 (63 calls)
2^63: fast = -9223372036854775808 (7 calls), slow = -9223372036854775808 (64 calls)
3^40: fast = -6289078614652622815 (7 calls), slow = -6289078614652622815 (41 calls)
10^19: fast = -8446744073709551616 (6 calls), slow = -8446744073709551616 (20 calls)
fastPower(2, 100) makes 8 calls

The fast version needs ⌊log₂ n⌋ + 2 calls, and the slow one needs n + 1. The sheet's "about 7 recursive steps for 2100" is right: 8 calls in all, 7 of them recursive.

Classic trap · the answer doesn't fit

A long long holds at most 263 − 1 ≈ 9.2 × 1018. The run above shows what happens past that limit: 263 prints as −9223372036854775808, and 340 and 1019 print as nonsense negative numbers, with no error message. (-fsanitize=undefined does catch it: signed integer overflow: 4611686018427387904 * 2 cannot be represented in type 'long long'.) The sheet's own motivating example, 2100, can't be stored in any C integer type. Halving makes the calculation faster, but the result still has to fit in the variable.

The sheet also says "positive exponent". Pass a negative one and the function quietly gives a wrong answer: fastPower(2, -1) returned 2 and fastPower(2, -3) returned 8. That's because −1 / 2 is 0 in C (it rounds toward zero), and −1 % 2 is −1, which is not 0, so the "odd" branch runs.

Classic trap · calling the half-power twice

return fastPower(b, e/2) * fastPower(b, e/2); gives the right answer, but every call now makes two calls. The total goes back to about 2n calls, which is worse than the slow version. Store the half-power in a variable once, exactly as the sheet does.

Solved problem 2 · sheet §11.2

Tower of Hanoi

Lab sheet §11.2 · the question, as set

You are given three pegs (labeled A, B, and C) and N disks of different sizes that can slide onto any peg. Initially, all disks are stacked on Peg A in order of size, with the largest at the bottom and the smallest at the top. You must move the entire stack to Peg C, obeying three strict rules:

  1. You can only move one disk at a time.
  2. A disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.

Write a recursive function to print the exact sequence of moves required to solve the puzzle.

How to start. Think about the biggest disk only. It can move to C only when everything else is out of the way on B. Base case: 1 disk, so just move it. Smaller version: "move n−1 disks from one peg to another", which is the same puzzle with one disk fewer. Use it twice: once to clear the way (A → B), and once to put the stack back on top (B → C). What shrinks: the disk count.
#include <stdio.h>

void towerOfHanoi(int n, char source, char destination, char auxiliary) {
    if (n == 1) {
        printf("Move disk 1 from peg %c to peg %c\n", source, destination);
        return;
    }
    towerOfHanoi(n - 1, source, auxiliary, destination);
    printf("Move disk %d from peg %c to peg %c\n", n, source, destination);
    towerOfHanoi(n - 1, auxiliary, destination, source);
}

int main(void) {
    int numDisks = 3;
    printf("Steps to solve Tower of Hanoi with %d disks:\n", numDisks);
    towerOfHanoi(numDisks, 'A', 'C', 'B');
    return 0;
}
% ./a.out
Steps to solve Tower of Hanoi with 3 disks:
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C
T(1, A, C, B)#1 disk 1: A → C#2 disk 2: A → BT(1, C, B, A)#3 disk 1: C → BT(2, A, B, C)#4 disk 3: A → CT(1, B, A, C)#5 disk 1: B → A#6 disk 2: B → CT(1, A, C, B)#7 disk 1: A → CT(2, B, C, A)T(3, A, C, B) recursive callbase case (prints one move)#k = order printed
The call tree for towerOfHanoi(3, 'A', 'C', 'B'), drawn from the program's own recursion. The moves are numbered in the order they print, which is left to right along the bottom. Each T(2, …) prints three moves and the root adds one in the middle.

The four arguments are (how many, from, to, spare). In the first call, the spare and the destination swap places: T(n−1, source, auxiliary, destination). In the second call, the source and the spare swap: T(n−1, auxiliary, destination, source). If you get either one wrong, the program still prints 7 moves, but some of them break the rules. To check a printed solution, play it with three coins on your desk.

How many moves? We counted them for larger stacks:

% ./a.out
n =  1: 1 moves
n =  2: 3 moves
n =  3: 7 moves
n =  4: 15 moves
n = 10: 1023 moves
n = 20: 1048575 moves
n = 30: 1073741823 moves
Unpack this step: why the count is always 2n − 1

Moves(n) = Moves(n−1) + 1 + Moves(n−1) = 2 × Moves(n−1) + 1, starting from Moves(1) = 1. That gives 1, 3, 7, 15, …, which is one less than each power of 2. Every extra disk doubles the work, so 30 disks take over a billion moves.

Solved problem 3 · sheet §11.3

Recursive binary search with a wrapper

Lab sheet §11.3 · the question, as set

Write a recursive function to find a target number in a sorted array. The function should return the index of the target if found, and -1 if the target is not present in the array.

How to start. The loop version from Lab 6 kept left and right in variables. In the recursive version they become parameters. Base cases: an empty range (left > right) means not found, and a middle element that matches means found. Smaller version: the same search on one half. What shrinks: right − left roughly halves. The wrapper exists so that main never has to type 0, size − 1.
#include <stdio.h>

int binarySearchHelper(int arr[], int left, int right, int target) {
    if (left > right) {
        return -1;
    }
    int mid = left + (right - left) / 2;
    if (arr[mid] == target) {
        return mid;
    }
    if (arr[mid] > target) {
        return binarySearchHelper(arr, left, mid - 1, target);
    } else {
        return binarySearchHelper(arr, mid + 1, right, target);
    }
}

int binarySearch(int arr[], int size, int target) {
    return binarySearchHelper(arr, 0, size - 1, target);
}

int main(void) {
    int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
    int size = 10;
    int targets[] = {17, 2, 29, 4};
    for (int i = 0; i < 4; i++) {
        int target = targets[i];
        int result = binarySearch(primes, size, target);
        if (result != -1) {
            printf("Target %d found at index %d.\n", target, result);
        } else {
            printf("Target %d not found in the array.\n", target);
        }
    }
    return 0;
}

The sheet's main searches only for 17. Ours also tries both ends and a missing value:

% ./a.out
Target 17 found at index 6.
Target 2 found at index 0.
Target 29 found at index 9.
Target 4 not found in the array.

Here is the same helper with one print line added, showing each frame's range. Each indent is one level deeper in the stack:

% ./a.out
target 17:
helper(left=0, right=9) mid=4 arr[mid]=11
  helper(left=5, right=9) mid=7 arr[mid]=19
    helper(left=5, right=6) mid=5 arr[mid]=13
      helper(left=6, right=6) mid=6 arr[mid]=17 -> found, return 6
target 4:
helper(left=0, right=9) mid=4 arr[mid]=11
  helper(left=0, right=3) mid=1 arr[mid]=3
    helper(left=2, right=3) mid=2 arr[mid]=5
      helper(left=2, right=1) -> empty, return -1

The not-found case ends at left = 2, right = 1: the two indices have crossed, so the range is empty. That crossing is the only way a missing value stops the recursion. If the base case were left == right instead, a missing value would recurse forever.

2 · The four dry runs (sheet §14)

Write your answer down first, then open the box. Each answer was confirmed by compiling the exact code from the sheet. The printed output was copied straight from the run, including the trailing space that "%d " leaves.

Lab sheet §14.1 · Dry Run 1 · the question, as set

Trace the exact execution path of the provided functions.

#include <stdio.h>

void traceMe(int n) {
    if (n <= 0) {
        return;
    }

    printf("%d ", n);

    traceMe(n - 1);
    traceMe(n - 2);

    printf("%d ", n);
}

int main(void) {
    printf("Output: ");

    traceMe(4);

    printf("\n");
    return 0;
}
Dry run 1: a print before and after two calls

Output:

% ./a.out
Output: 4 3 2 1 1 2 1 1 3 2 1 1 2 4 

The opening move for tracing. Don't trace from the top. Work out the small cases first, then build up. Write S(n) for whatever traceMe(n) prints. Reading the body line by line, S(n) is: n, then S(n−1), then S(n−2), then n again. S(0) and S(−1) print nothing.

callprints
traceMe(1)1 · S(0) · S(−1) · 1 = 1 1
traceMe(2)2 · S(1) · S(0) · 2 = 2 1 1 2
traceMe(3)3 · S(2) · S(1) · 3 = 3 2 1 1 2 1 1 3
traceMe(4)4 · S(3) · S(2) · 4 = 4 3 2 1 1 2 1 1 3 2 1 1 2 4

The full call stack, from the same code with a print line added at each call and return. Each indent is one frame deeper. A "PRINT" line just below a call happens while the stack is winding (going deeper). A "PRINT … returns" line happens while it is unwinding (coming back up), once both of that frame's calls are done.

% ./a.out
call traceMe(4)
  PRINT 4
  call traceMe(3)
    PRINT 3
    call traceMe(2)
      PRINT 2
      call traceMe(1)
        PRINT 1
        call traceMe(0)  -> base, return
        call traceMe(-1)  -> base, return
        PRINT 1   (traceMe(1) returns)
      call traceMe(0)  -> base, return
      PRINT 2   (traceMe(2) returns)
    call traceMe(1)
      PRINT 1
      call traceMe(0)  -> base, return
      call traceMe(-1)  -> base, return
      PRINT 1   (traceMe(1) returns)
    PRINT 3   (traceMe(3) returns)
  call traceMe(2)
    PRINT 2
    call traceMe(1)
      PRINT 1
      call traceMe(0)  -> base, return
      call traceMe(-1)  -> base, return
      PRINT 1   (traceMe(1) returns)
    call traceMe(0)  -> base, return
    PRINT 2   (traceMe(2) returns)
  PRINT 4   (traceMe(4) returns)

There are 15 calls in all. Eight of them hit the base case straight away (traceMe(0) and traceMe(-1)). The stack is never more than 5 frames deep, because only one branch is active at a time.

Lab sheet §14.2 · Dry Run 2 · the question, as set

Your task is to manually trace the execution of the function call puzzleTrace(4, 3). You must determine the exact final integer value that will be printed in main.

#include <stdio.h>

int puzzleTrace(int a, int b) {
    if (a == 0) {
        return b;
    }

    if (a % 2 == 0) {
        return puzzleTrace(a / 2, b + 1) + a;
    } else {
        return puzzleTrace(a - 1, b + 2) - b;
    }
}

int main(void) {
    int startA = 4;
    int startB = 3;

    printf("Final Result: %d\n", puzzleTrace(startA, startB));

    return 0;
}
Dry run 2: what each frame adds on the way back
% ./a.out
Final Result: 8

Winding (each frame pauses, holding the work it still has to do):

framea, bbranchpauses on
14, 3evenpuzzleTrace(2, 4) + 4
22, 4evenpuzzleTrace(1, 5) + 2
31, 5oddpuzzleTrace(0, 7) − 5
40, 7basereturns b = 7

Unwinding (each frame finishes its line using its own a and b):

framecomputesreturns
37 − 52
22 + 24
14 + 48
Classic trap

In frame 3, - b subtracts that frame's b, which is 5. It does not use the 7 that was passed down. Each frame has its own copy of a and b (sheet §4.1, "independent stack frames"). If you subtract 7, you get 0, then 2, then a final answer of 6.

Lab sheet §14.3 · Dry Run 3 · the question, as set

Your task is to manually trace the execution of the function call mysteryTrace(6). Write down the exact sequence of characters and numbers that will be printed to the screen.

#include <stdio.h>

void mysteryTrace(int n) {
    if (n <= 0) {
        printf("! ");
        return;
    }

    if (n % 2 == 0) {
        printf("%d ", n);
        mysteryTrace(n / 2);
    } else {
        mysteryTrace(n - 2);
        printf("%d ", n);
    }
}

int main(void) {
    int startValue = 6;

    printf("Execution Output: ");

    // Perform a manual dry run to determine the exact output string.
    mysteryTrace(startValue);

    printf("\n");
    return 0;
}
Dry run 3: even prints on the way down, odd on the way up
% ./a.out
Execution Output: 6 ! 1 3 
phaseframewhat happensprinted so far
windmT(6)even: prints 6 before calling mT(3)6
windmT(3)odd: calls mT(1) first; its print waits6
windmT(1)odd: calls mT(−1) first; its print waits6
basemT(−1)−1 ≤ 0: prints ! , returns6 !
unwindmT(1)wakes up, prints 1 6 ! 1
unwindmT(3)wakes up, prints 3 6 ! 1 3
unwindmT(6)nothing left after its call6 ! 1 3

This is sheet §10.3 in one function. A print before the call comes out in calling order, and a print after the call comes out in reverse order. Note that n - 2 jumps from 1 to −1, skipping 0. The base case is n <= 0 rather than n == 0, and that is why the recursion still stops.

Lab sheet §14.4 · Dry Run 4 · the question, as set

Your task is to manually trace the execution of the program. Write down the exact sequence of text that will be printed to the console.

#include <stdio.h>

int verifySequence(int arr[], int size, int index) {
    if (index >= size) {
        return 1;
    }

    printf("Visited: %d\n", arr[index]);

    return (arr[index] % 2 == 0) && verifySequence(arr, size, index + 1);
}

int main(void) {
    int numbers[] = {14, 8, 7, 10, 12};
    int size = 5;

    printf("Execution Trace:\n");

    // Perform a manual dry run to see exactly what gets printed
    int result = verifySequence(numbers, size, 0);

    printf("Final Boolean Result: %d\n", result);

    return 0;
}
Dry run 4: && stops the recursion early
% ./a.out
Execution Trace:
Visited: 14
Visited: 8
Visited: 7
Final Boolean Result: 0
frameindexprintsleft side of &&so…
10Visited: 1414 even → 1must call frame 2
21Visited: 88 even → 1must call frame 3
32Visited: 77 odd → 0no call: 0 && anything is 0

Unwinding: frame 3 returns 0, frame 2 returns 1 && 0 = 0, and frame 1 returns 1 && 0 = 0. The values 10 and 12 are never visited, and the base case (index >= size) is never reached on this input.

Unpack this step: why the right side of && is skipped

a && b is true only if both sides are. When a is already 0, the answer is 0 whatever b is, so C doesn't evaluate b at all. Here b is the recursive call, so that call never happens. This is the short-circuit rule from the operators notes.

3 · The four debugging exercises (sheet §13)

For each one there are two parts: what the program actually does when you run it, then the fix. The crashes and warnings shown are the real ones from clang on a Mac. Two of these four bugs give the right answer on the test the sheet sets, so a correct-looking output does not prove the code is correct.

Debugging exercise 1

Post-increment in the recursive call

Lab sheet §13.1 · Debugging Exercise 1 · the question, as set

Identify the bug in this code and correct it.

#include <stdio.h>

/*
 * Reverses an array in-place.
 * The wrapper function would pass left = 0 and right = size - 1.
 */
void reverseArray(int arr[], int left, int right) {
    // Base case: If left pointer crosses or equals right pointer,
    // the middle of the array has been reached and we stop.
    if (left >= right) {
        return;
    }

    // Swap the elements at the current left and right indices
    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;

    // Recursive step: move both pointers inward to process the rest
    reverseArray(arr, left++, right--);
}

int main(void) {
    int arr[] = {1, 2, 3, 4, 5};
    int size = 5;

    // Expected to modify arr to: {5, 4, 3, 2, 1}
    reverseArray(arr, 0, size - 1);

    printf("Reversed array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

What happens. The program prints nothing at all and crashes:

% ./a.out
[killed by signal 11: segmentation fault, exit status 139]

left++ hands over the old value of left and increments the local copy only afterwards, when it no longer matters. right-- does the same. So every call receives exactly (0, 4) again, swaps elements 0 and 4 back and forth, and calls again. We added a print line at the top of the function to see the arguments:

% ./a.out
call 1: left = 0, right = 4
call 2: left = 0, right = 4
call 3: left = 0, right = 4
call 4: left = 0, right = 4
... (still the same arguments; stopping the demo here)

The arguments never change, so the base case left >= right is never reached. That makes this the "non-converging arguments" bug from sheet §10.1. The stack fills up and the operating system kills the program with a segmentation fault (exit status 139). printf("Reversed array: ") never runs, because it comes after the call.

Fix: pass the new values directly.

#include <stdio.h>

/*
 * Reverses an array in-place.
 * The wrapper function would pass left = 0 and right = size - 1.
 */
void reverseArray(int arr[], int left, int right) {
    // Base case: If left pointer crosses or equals right pointer,
    // the middle of the array has been reached and we stop.
    if (left >= right) {
        return;
    }

    // Swap the elements at the current left and right indices
    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;

    // Recursive step: move both pointers inward to process the rest
    reverseArray(arr, left + 1, right - 1);   // FIX: pass the NEW values
}

int main(void) {
    int arr[] = {1, 2, 3, 4, 5};
    int size = 5;

    // Expected to modify arr to: {5, 4, 3, 2, 1}
    reverseArray(arr, 0, size - 1);

    printf("Reversed array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
% ./a.out
Reversed array: 5 4 3 2 1 

With -O2, the same buggy program does not crash. It hangs instead: we stopped it after 3 seconds. The optimiser turned the call into a loop (the tail-call optimisation from sheet §7.3), so there was no stack left to fill. The underlying bug is identical in both cases, it just shows up as an endless loop instead of a crash.

Debugging exercise 2

Off by one: arr[size]

Lab sheet §13.2 · Debugging Exercise 2 · the question, as set

The following program is designed to calculate the total sum of all elements in an integer array using recursion. Identify the error in this code and correct it.

#include <stdio.h>

/*
 * Function: sumArray
 * ------------------
 * Computes the sum of elements in an array recursively.
 *
 * Parameters:
 *   arr  - the array of integers
 *   size - the number of elements currently being considered
 *
 * Returns:
 *   The integer sum of the array elements.
 */
int sumArray(int arr[], int size) {
    if (size == 0) {
        return 0;
    }

    return arr[size] + sumArray(arr, size - 1);
}

int main(void) {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = 5;

    int totalSum = sumArray(numbers, size);

    printf("The sum of the array is: %d\n", totalSum);

    return 0;
}

What happens. On our run it printed:

% ./a.out
The sum of the array is: 141

The right answer is 150. With size elements, the last valid index is size − 1. So the first call reads arr[5], one box past the end, and the calls add up arr[5] + arr[4] + … + arr[1]. That misses arr[0] (10) and adds whatever happened to be in the box after the array (on this run, 1): 140 + 1 = 141. Another machine could print a different wrong number. Compiling with -fsanitize=address catches the read: stack-buffer-overflow … READ of size 4 … in sumArray d2_bug.c:20.

Fix: the last element of the first size elements is arr[size - 1].

#include <stdio.h>

/*
 * Function: sumArray
 * ------------------
 * Computes the sum of elements in an array recursively.
 *
 * Parameters:
 *   arr  - the array of integers
 *   size - the number of elements currently being considered
 *
 * Returns:
 *   The integer sum of the array elements.
 */
int sumArray(int arr[], int size) {
    if (size == 0) {
        return 0;
    }

    return arr[size - 1] + sumArray(arr, size - 1);   // FIX: last element is arr[size - 1]
}

int main(void) {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = 5;

    int totalSum = sumArray(numbers, size);

    printf("The sum of the array is: %d\n", totalSum);

    return 0;
}
% ./a.out
The sum of the array is: 150

Debugging exercise 3

A path with no return

Lab sheet §13.3 · Debugging Exercise 3 · the question, as set

The following program uses recursion to find the maximum integer in an array. Find the error in the code and correct it.

#include <stdio.h>

/*
 * Function: findMax
 * -----------------
 * Recursively finds the largest element in an array.
 */
int findMax(int arr[], int size) {
    if (size == 1) {
        return arr[0];
    }

    int maxOfRest = findMax(arr, size - 1);

    if (arr[size - 1] > maxOfRest) {
        return arr[size - 1];
    }
}

int main(void) {
    int numbersA[] = {3, 7, 2, 9, 5};
    int numbersB[] = {10, 8, 6, 4, 2};

    printf("Max of A: %d\n", findMax(numbersA, 5));
    printf("Max of B: %d\n", findMax(numbersB, 5));

    return 0;
}

What happens. clang warns at compile time:

src/d3_bug.c:18:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
   18 | }
      | ^
1 warning generated.

and the run printed nonsense:

% ./a.out
Max of A: 1
Max of B: 2

When the last element is not bigger than the maximum of the rest, the function reaches its closing } without returning anything. The caller then reads a "return value" that was never set, which is undefined behaviour. This is sheet §10.2's "missing return statement". Array A goes wrong at size 3 (2 is not > 7), and array B goes wrong at every level, because each new element is smaller.

Fix: cover the other path.

#include <stdio.h>

int findMax(int arr[], int size) {
    if (size == 1) {
        return arr[0];
    }
    int maxOfRest = findMax(arr, size - 1);
    if (arr[size - 1] > maxOfRest) {
        return arr[size - 1];
    }
    return maxOfRest;              /* the missing path: the rest had the bigger value */
}

int main(void) {
    int numbersA[] = {3, 7, 2, 9, 5};
    int numbersB[] = {10, 8, 6, 4, 2};
    printf("Max of A: %d\n", findMax(numbersA, 5));
    printf("Max of B: %d\n", findMax(numbersB, 5));
    return 0;
}
% ./a.out
Max of A: 9
Max of B: 10

Habit: for any non-void function, check that every path through it ends in a return. -Wall finds this bug for you, so compile with it.

Debugging exercise 4

Reading before checking the bounds

Lab sheet §13.4 · Debugging Exercise 4 · the question, as set

The following C program uses recursion to perform a linear search on an array for a specific target integer. Identify the error in the code and correct it.

#include <stdio.h>
#include <stdbool.h>

/*
 * Function: searchArray
 * ---------------------
 * Recursively searches for a target value in an integer array.
 */
bool searchArray(int arr[], int size, int index, int target) {
    if (arr[index] == target) {
        return true;
    }

    if (index >= size) {
        return false;
    }

    return searchArray(arr, size, index + 1, target);
}

int main(void) {
    int vault[] = {12, 45, 67, 89, 23};
    int size = 5;

    bool found = searchArray(vault, size, 0, 99);

    if (found) {
        printf("Target located in the vault.\n");
    } else {
        printf("Target is missing.\n");
    }

    return 0;
}

What happens. On our run it printed the right answer:

% ./a.out
Target is missing.

The bug is still there. With target 99, the calls walk to index = 5, and the first line reads arr[5] before the second line checks whether 5 is still inside the array. That box is outside the array. Whatever value was in memory there was not 99, so the check fell through to index >= size and returned false. If that stray value had happened to be 99, the program would have said "Target located". -fsanitize=address shows the illegal read: stack-buffer-overflow … READ of size 4 … in searchArray d4_bug.c:10.

Fix: swap the two base cases. Check the bounds first, then read the element. This is the same rule as flood fill (P4) and the maze (P6).

#include <stdio.h>
#include <stdbool.h>

bool searchArray(int arr[], int size, int index, int target) {
    if (index >= size) {           /* bounds check FIRST ... */
        return false;
    }
    if (arr[index] == target) {    /* ... only then read arr[index] */
        return true;
    }
    return searchArray(arr, size, index + 1, target);
}

int main(void) {
    int vault[] = {12, 45, 67, 89, 23};
    int size = 5;
    bool found = searchArray(vault, size, 0, 99);
    if (found) {
        printf("Target located in the vault.\n");
    } else {
        printf("Target is missing.\n");
    }
    printf("Searching for 23: %s\n", searchArray(vault, size, 0, 23) ? "found" : "missing");
    return 0;
}
% ./a.out
Target is missing.
Searching for 23: found

4 · The eight practice problems (sheet §12)

Every problem bans loops inside the recursive logic, so the only loops on this page are in main and in the grid-printing helpers, never inside the recursive functions. Each problem was run on all of the sheet's test cases.

Problem 1 · about 10 minutes

Sum of digits

Lab sheet §12.1 · Practice Problem 1 · the question, as set

Write a completely recursive C program that takes a non-negative integer and calculates the total sum of its individual digits. For example, if the input is 432, the program should calculate 4 + 3 + 2 and output 9.

  • Your solution must use the prototype int sumOfDigits(int n);
  • The algorithm must be entirely recursive. You are strictly forbidden from using any iterative loops (for, while, do-while).
  • You may not convert the integer into a string or an array of characters. You must process the number mathematically.

Test cases: 10485 → 18 · 7 → 7 · 0 → 0

How to start. Base case: a single digit (n < 10) is its own digit sum. That also covers 0. Smaller version: 10485 without its last digit is 1048, which is n / 10. One step: add the last digit back, n % 10. So 10485 → 5 + digitSum(1048). What shrinks: one digit fewer each call.
Unpack this step: % 10 and / 10 on 10485

10485 % 10 is the remainder after dividing by 10, which is 5, the last digit. 10485 / 10 is integer division, which gives 1048 and drops the last digit. Used together, they peel off one digit at a time from the right.

#include <stdio.h>

int sumOfDigits(int n);

int main(void) {
    int n;
    printf("Enter a non-negative integer: ");
    if (scanf("%d", &n) != 1 || n < 0) {
        printf("Please enter a non-negative integer.\n");
        return 1;
    }
    printf("%d\n", sumOfDigits(n));
    return 0;
}

int sumOfDigits(int n) {
    if (n < 10) {                       /* base case: one digit left */
        return n;
    }
    return n % 10 + sumOfDigits(n / 10);   /* last digit + sum of the rest */
}
% ./a.out
Enter a non-negative integer: 10485
18
% ./a.out
Enter a non-negative integer: 7
7
% ./a.out
Enter a non-negative integer: 0
0

This is digitSum from the Lecture 10 in-class activity. It is traced both ways on the recursion notes.

Problem 2 · about 10 minutes

Decimal to binary, printed

Lab sheet §12.2 · Practice Problem 2 · the question, as set

Write a completely recursive C program that takes a non-negative decimal integer (base 10) as input and prints its binary (base 2) equivalent directly to the screen.

  • Your solution must use the prototype void printBinary(unsigned int n);
  • You are strictly forbidden from using any iterative loops (for, while, do-while).
  • You may not use an array or a string to store the binary digits.

Test cases: 13 → 1101 · 256 → 100000000 · 0 → 0

How to start. The last binary digit of n is n % 2. Everything before it is the binary for n / 2. 13 = 1101: the last digit is 13 % 2 = 1, and the rest is 6 = 110. Base case: n < 2 is a single digit, so print it. That handles 0 correctly. One step: print the rest first, then this digit. What shrinks: n halves.
#include <stdio.h>

void printBinary(unsigned int n);

int main(void) {
    unsigned int n;
    printf("Enter a non-negative integer: ");
    if (scanf("%u", &n) != 1) {
        return 1;
    }
    printBinary(n);
    printf("\n");
    return 0;
}

void printBinary(unsigned int n) {
    if (n < 2) {                 /* base case: 0 or 1 is its own binary digit */
        printf("%u", n);
        return;
    }
    printBinary(n / 2);          /* print all the higher bits first ... */
    printf("%u", n % 2);         /* ... then this number's last bit */
}
% ./a.out
Enter a non-negative integer: 13
1101
% ./a.out
Enter a non-negative integer: 256
100000000
% ./a.out
Enter a non-negative integer: 0
0

Why no array is needed. Repeated division produces the digits last-first (1, 0, 1, 1 for 13). On paper you would write them down and read them backwards. Here the printf sits after the call, so it runs while the stack unwinds, which reverses the order for free. Dry run 3 used the same idea. If you move the printf above the call, 13 prints as 1011.

Unpack this step: binary by repeated division

13 ÷ 2 = 6 r 1; 6 ÷ 2 = 3 r 0; 3 ÷ 2 = 1 r 1; 1 is the last digit, 1. Reading the remainders bottom-up gives 1101. Check: 8 + 4 + 0 + 1 = 13. The number-systems drill has more practice.

Problem 3 · about 20 minutes

Phrase palindrome, recursively

Lab sheet §12.3 · Practice Problem 3 · the question, as set

In Lab 7, you wrote an iterative program to check if a phrase is a palindrome by ignoring spaces, punctuation, and case differences. Your task is to solve this exact same problem purely recursively. Write a C program that reads a string from the user using fgets and determines whether it is a palindrome. You must ignore all non-alphanumeric characters (using <ctype.h>) and treat uppercase and lowercase letters as equivalent.

  • You are strictly forbidden from using for, while, or do-while loops anywhere in your logic. This means you cannot use a loop to skip over punctuation or spaces; the skipping must be handled via recursive calls.
  • You must use the Wrapper/Helper function pattern to cleanly manage the boundary indices without forcing the user to pass them from main().

Test cases: A man, a plan, a canal: Panama! → Palindrome · Madam, I'm Adams. → Not a Palindrome · ... , !? → Palindrome

How to start. Take the two-pointer loop from the Lab 7 page and turn each kind of loop step into a recursive call. Base case: left >= right, meaning 0 or 1 characters remain, so the answer is true. Then there are three possible moves, and each makes the range one or two shorter: junk on the left → (left + 1, right); junk on the right → (left, right − 1); two letters that differ → false; two letters that match → (left + 1, right − 1). What shrinks: right − left, by at least 1 each call.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

/* Helper: is s[left..right] a palindrome, ignoring non-alphanumerics and case? */
bool isPalHelper(const char s[], int left, int right) {
    if (left >= right) {                              /* 0 or 1 characters left */
        return true;
    }
    if (!isalnum((unsigned char) s[left])) {          /* skip junk on the left */
        return isPalHelper(s, left + 1, right);
    }
    if (!isalnum((unsigned char) s[right])) {         /* skip junk on the right */
        return isPalHelper(s, left, right - 1);
    }
    if (tolower((unsigned char) s[left]) != tolower((unsigned char) s[right])) {
        return false;                                 /* a mismatch settles it */
    }
    return isPalHelper(s, left + 1, right - 1);       /* both ends matched: go inward */
}

/* Wrapper: the only function main needs to know about. */
bool isPalindrome(const char s[]) {
    return isPalHelper(s, 0, (int) strlen(s) - 1);
}

int main(void) {
    char line[200];
    printf("Enter a phrase: ");
    if (fgets(line, sizeof(line), stdin) == NULL) {
        return 1;
    }
    line[strcspn(line, "\n")] = '\0';
    if (isPalindrome(line)) {
        printf("Palindrome\n");
    } else {
        printf("Not a Palindrome\n");
    }
    return 0;
}
% ./a.out
Enter a phrase: A man, a plan, a canal: Panama!
Palindrome
% ./a.out
Enter a phrase: Madam, I'm Adams.
Not a Palindrome
% ./a.out
Enter a phrase: ... , !?
Palindrome

Tests beyond the sheet's. An empty line gives Palindrome: strlen is 0, so right is −1 and the base case fires at once. Was it a car or a cat I saw? gives Palindrome, and ab gives Not a Palindrome. Test 3 contains no letters at all. The skipping calls move the two ends together until they cross, and an empty phrase counts as a palindrome.

Classic trap

Trim the newline that fgets keeps, or treat it as junk. Here isalnum('\n') is false, so it would be skipped anyway, but trimming is still the habit from Lab 7. And cast to unsigned char before calling any ctype.h function (Lab 7 §8).

Problem 4 · about 20 minutes

The paint bucket (flood fill)

Lab sheet §12.4 · Practice Problem 4 · the question, as set

You are given a 2D array of characters representing a simple image, where each character represents a color. You are also given a starting coordinate (row, col) and a replacementColor. Your task is to write a recursive function that changes the starting pixel to the replacement color, and then recursively attempts to fill the adjacent pixels (Up, Down, Left, Right) only if they match the original color of the starting pixel.

  • Prototype (with #define MAX 10): void floodFill(char grid[MAX][MAX], int numRows, int numCols, int r, int c, char targetColor, char replacementColor);
  • You must explicitly handle out-of-bounds array indices before attempting to read grid[r][c]. Failing to do so will result in a Segmentation Fault.
  • The algorithm must be entirely recursive. You may not use iteration (loops) to traverse the adjacent pixels.

Test 1: the 5×5 grid below from (1, 2) with G. Test 2: AAB / ABB / BBB from (0, 0) with X → XXB / XBB / BBB. Test 3: all W, from (1, 1) with W → unchanged.

How to start. Ask the question from one pixel's point of view: "should I be painted?" Stop (base case) if the pixel is off the grid, or if it isn't the target colour. That second condition includes pixels you have already painted, so you never revisit one. Otherwise paint yourself and ask your four neighbours the same question. What shrinks: the number of target-coloured pixels. Each call that gets past the base case paints one of them, so there are never more such calls than pixels in the region.
before: start at (1, 2), colour B Y Y Y B B Y Y B B B Y B X X B Y Y B B B Y Y Y Y Y after: replacement G Y Y Y G G Y Y G G G Y B X X G Y Y G G G Y Y Y Y Y dashed: the B at (2, 1) touches the region only diagonally, so it stays B
Test 1, before and after, computed by the same algorithm. Only up, down, left and right count as neighbours.
#include <stdio.h>
#define MAX 10

void floodFill(char grid[MAX][MAX], int numRows, int numCols,
               int r, int c, char targetColor, char replacementColor) {
    /* 1. Off the grid? Check this BEFORE touching grid[r][c]. */
    if (r < 0 || r >= numRows || c < 0 || c >= numCols) {
        return;
    }
    /* 2. Not part of the region (wrong colour, or already repainted)? */
    if (grid[r][c] != targetColor) {
        return;
    }
    /* 3. Paint this pixel, then ask the four neighbours to do the same. */
    grid[r][c] = replacementColor;
    floodFill(grid, numRows, numCols, r - 1, c, targetColor, replacementColor); /* up    */
    floodFill(grid, numRows, numCols, r + 1, c, targetColor, replacementColor); /* down  */
    floodFill(grid, numRows, numCols, r, c - 1, targetColor, replacementColor); /* left  */
    floodFill(grid, numRows, numCols, r, c + 1, targetColor, replacementColor); /* right */
}

/* Wrapper: reads the starting colour itself and guards the same-colour case. */
void paintBucket(char grid[MAX][MAX], int numRows, int numCols,
                 int r, int c, char replacementColor) {
    char target = grid[r][c];
    if (target == replacementColor) {
        return;                     /* nothing to change, and avoids endless recursion */
    }
    floodFill(grid, numRows, numCols, r, c, target, replacementColor);
}

void printGrid(char grid[MAX][MAX], int numRows, int numCols) {
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            printf("%c%s", grid[i][j], j < numCols - 1 ? " " : "\n");
        }
    }
}

int main(void) {
    char g1[MAX][MAX] = {
        "YYYBB",
        "YYBBB",
        "YBXXB",
        "YYBBB",
        "YYYYY"
    };
    paintBucket(g1, 5, 5, 1, 2, 'G');
    printf("Test 1:\n");
    printGrid(g1, 5, 5);

    char g2[MAX][MAX] = { "AAB", "ABB", "BBB" };
    paintBucket(g2, 3, 3, 0, 0, 'X');
    printf("Test 2:\n");
    printGrid(g2, 3, 3);

    char g3[MAX][MAX] = { "WWW", "WWW", "WWW" };
    paintBucket(g3, 3, 3, 1, 1, 'W');
    printf("Test 3:\n");
    printGrid(g3, 3, 3);
    return 0;
}
% ./a.out
Test 1:
Y Y Y G G
Y Y G G G
Y B X X G
Y Y G G G
Y Y Y Y Y
Test 2:
X X B
X B B
B B B
Test 3:
W W W
W W W
W W W
Classic trap · Test 3 crashes a correct-looking flood fill

If the replacement colour is the same as the target colour, a painted pixel still "matches the target". So the neighbours paint it again, then it paints them, and the recursion never ends. We deleted the guard in paintBucket and ran Test 3: the program crashed with a segmentation fault (exit status 139). The sheet's test case is there to catch exactly this, but the sheet doesn't explain why it matters. Because the prototype takes targetColor as a parameter, a small wrapper is the natural place for the check. Alternatively, put if (targetColor == replacementColor) return; as the first line of floodFill.

The order of the two base-case checks matters for the same reason as in Debug 4: check the bounds first, and only then read grid[r][c]. || stops at the first true condition, so r < 0 || r >= numRows || … never evaluates an index that is out of range.

Problem 5 · about 25 minutes

Exact change

Lab sheet §12.5 · Practice Problem 5 · the question, as set

You are provided with an array of integers representing the values of available coins, and an integer representing a target price. Write a completely recursive C program to determine if it is possible to achieve exactly the target price using a subset of the provided coins. Each specific coin in the array can be used at most once (though the array may contain multiple coins of the same value).

  • Prototype: bool canMakeExactChange(int coins[], int numCoins, int target); (you may write a separate recursive helper function if necessary)
  • The algorithm must be entirely recursive.

Hint: For any single coin in the array, what do you think are the only two options you will have to satisfy your target value? Think of the base cases too.

Test cases: {1, 5, 10, 20}, 26 → True · {5, 5, 10, 25}, 17 → False · {10, 20, 30}, 0 → True

How to start. Answering the hint: for the last coin, either you use it or you don't. Use it: can the other n − 1 coins make target − coin? Don't use it: can the other n − 1 coins make target? If either answer is yes, the overall answer is yes. Base cases: target == 0 means you're done, so true. Check this first, so that "0 with no coins left" still counts as true. No coins left, or target below 0 (you overpaid), means false. What shrinks: the number of coins, by 1 on every call.
#include <stdio.h>
#include <stdbool.h>

/* Can some of coins[0..n-1] (each used at most once) add up to exactly target? */
bool changeHelper(int coins[], int n, int target) {
    if (target == 0) {                 /* nothing left to pay: done */
        return true;
    }
    if (n == 0 || target < 0) {        /* no coins left, or we overpaid */
        return false;
    }
    /* Look at the last coin, coins[n-1]. Either we use it ... */
    if (changeHelper(coins, n - 1, target - coins[n - 1])) {
        return true;
    }
    /* ... or we don't. */
    return changeHelper(coins, n - 1, target);
}

bool canMakeExactChange(int coins[], int numCoins, int target) {
    return changeHelper(coins, numCoins, target);
}

int main(void) {
    int c1[] = {1, 5, 10, 20};
    int c2[] = {5, 5, 10, 25};
    int c3[] = {10, 20, 30};
    printf("Test 1: %s\n", canMakeExactChange(c1, 4, 26) ? "True" : "False");
    printf("Test 2: %s\n", canMakeExactChange(c2, 4, 17) ? "True" : "False");
    printf("Test 3: %s\n", canMakeExactChange(c3, 3, 0)  ? "True" : "False");
    printf("Extra:  {5, 5, 10, 25}, target 20: %s\n",
           canMakeExactChange(c2, 4, 20) ? "True" : "False");
    printf("Extra:  {5, 5, 10, 25}, target 50: %s\n",
           canMakeExactChange(c2, 4, 50) ? "True" : "False");
    return 0;
}
% ./a.out
Test 1: True
Test 2: False
Test 3: True
Extra:  {5, 5, 10, 25}, target 20: True
Extra:  {5, 5, 10, 25}, target 50: False

26 = 1 + 5 + 20. For 17 with {5, 5, 10, 25}, every coin is a multiple of 5 and 17 isn't, so the answer is false. For target 0, the empty selection works, and the first base case returns true straight away. Our extra test, 50, is false, because the four coins add up to only 45. The function never reuses a coin: each call passes n − 1, so the coin it just decided on is out of the range from then on.

Each call can make two more calls, so the worst case is 2n calls. For a lab-sized array that is instant. With 30 coins it would be about a billion calls.

Problem 6 · about 15 minutes

Rat in a maze (right and down only)

Lab sheet §12.6 · Practice Problem 6 · the question, as set

You are given a 2D array of integers representing a maze. A rat starts at the top-left corner (0, 0) and must reach the cheese located at the bottom-right corner (numRows - 1, numCols - 1). The rat is only allowed to move in two directions: Right or Down. In the maze array, a 1 represents an open path that the rat can step on, and a 0 represents a blocked wall. Write a completely recursive C program to determine if a valid path exists from the start to the destination.

  • Prototype (with #define MAX 10): bool hasPath(int maze[MAX][MAX], int numRows, int numCols, int r, int c);
  • The algorithm must be entirely recursive.

Hint: Think of the boolean return value as the answer to a very localized question: "Can I eventually reach the end from my current cell?"

Test 1: 4×4 grid 1000 / 1101 / 0110 / 0011 → True · Test 2: 110 / 010 / 000 → False · Test 3: 1×1 grid 0 → False

How to start. Use the hint's question: "can I finish from here?" The answer is no if you are off the grid or standing on a wall. It is yes if you are on the cheese, and the cheese cell is open. Otherwise, the answer is yes if you can finish from the cell to your right or from the cell below you. What shrinks: the distance to the corner, (rows − 1 − r) + (cols − 1 − c). Every step goes right or down, so it drops by 1 each call and the rat can never walk in a circle.
1 0 0 0 1 1 0 1 0 1 1 0 0 0 1 1 start (0, 0)cheese(3, 3) c=0c=1c=2c=3r=0r=1r=2r=3
Test 1. The path shaded green is the one the program finds, since it tries right before down. It was marked by the same search (p6_path, below). The open cell at (1, 3) can't be reached: the walls at (0, 1) to (0, 3) and (1, 2) cut it off.
#include <stdio.h>
#include <stdbool.h>
#define MAX 10

/* "Can I reach the bottom-right corner from (r, c), moving only right or down?" */
bool hasPath(int maze[MAX][MAX], int numRows, int numCols, int r, int c) {
    if (r >= numRows || c >= numCols) {      /* walked off the grid */
        return false;
    }
    if (maze[r][c] == 0) {                   /* standing on a wall */
        return false;
    }
    if (r == numRows - 1 && c == numCols - 1) {   /* open AND the cheese */
        return true;
    }
    return hasPath(maze, numRows, numCols, r, c + 1)     /* try right */
        || hasPath(maze, numRows, numCols, r + 1, c);    /* else try down */
}

int main(void) {
    int m1[MAX][MAX] = {
        {1, 0, 0, 0},
        {1, 1, 0, 1},
        {0, 1, 1, 0},
        {0, 0, 1, 1}
    };
    int m2[MAX][MAX] = {
        {1, 1, 0},
        {0, 1, 0},
        {0, 0, 0}
    };
    int m3[MAX][MAX] = { {0} };
    printf("Test 1: %s\n", hasPath(m1, 4, 4, 0, 0) ? "True" : "False");
    printf("Test 2: %s\n", hasPath(m2, 3, 3, 0, 0) ? "True" : "False");
    printf("Test 3: %s\n", hasPath(m3, 1, 1, 0, 0) ? "True" : "False");
    return 0;
}
% ./a.out
Test 1: True
Test 2: False
Test 3: False

The same search, with each cell on the successful path marked as the calls unwind (the marking happens after a call returns true):

% ./a.out
* 0 0 0 
* * 0 1 
0 * * 0 
0 0 * * 
Classic trap · Test 3 is there for a reason

If you check "am I at the cheese?" before "is this a wall?", the 1×1 maze containing 0 answers True, because the rat "arrives" on a wall. We ran that ordering and it printed Test 3: True. Put the wall check before the destination check, as above.

Test 2 is False: from (1, 1), both "right" (1, 2) and "down" (2, 1) are walls, so every route is blocked.

Problem 7 · about 10 minutes

Pascal's triangle element

Lab sheet §12.7 · Practice Problem 7 · the question, as set

Write a purely recursive C program that takes a row index n and a column index k (both 0-indexed) and returns the value at that exact position in Pascal's Triangle. If you attempt to solve this iteratively using the mathematical combination formula n!/(k!(n − k)!), your factorials will rapidly cause an integer overflow (even for relatively small rows). The recursive approach elegantly avoids this by only using simple addition.

  • Prototype: int getPascalValue(int n, int k);
  • Entirely recursive; no multiplication, division, or separate factorial function.
  • You may assume that k will always be valid (0 ≤ k ≤ n).

Test cases: (4, 2) → 6 · (5, 5) → 1 · (7, 3) → 35

How to start. The problem statement gives you both pieces. Base case: the edges, where k == 0 or k == n, are 1. Recursive case: each inside number is the sum of the two above it, at row n − 1 and columns k − 1 and k. What shrinks: the row number. Both calls stay valid, with 0 ≤ k−1 and k ≤ n−1, because the base case has already handled the edges.
#include <stdio.h>

int getPascalValue(int n, int k) {
    if (k == 0 || k == n) {          /* the two edges of the triangle are 1 */
        return 1;
    }
    return getPascalValue(n - 1, k - 1) + getPascalValue(n - 1, k);  /* the two above */
}

int main(void) {
    printf("Test 1: n = 4, k = 2 -> %d\n", getPascalValue(4, 2));
    printf("Test 2: n = 5, k = 5 -> %d\n", getPascalValue(5, 5));
    printf("Test 3: n = 7, k = 3 -> %d\n", getPascalValue(7, 3));
    return 0;
}
% ./a.out
Test 1: n = 4, k = 2 -> 6
Test 2: n = 5, k = 5 -> 1
Test 3: n = 7, k = 3 -> 35
Classic trap · elegant, but slow, and it still overflows

Like Fibonacci, the two calls repeat each other's work. We counted the calls and timed them (p7_calls.c, default -O0):

C(4,2) = 6   calls = 11   time = 0.00 s
C(7,3) = 35   calls = 69   time = 0.00 s
C(20,10) = 184756   calls = 369511   time = 0.00 s
C(30,15) = 155117520   calls = 310235039   time = 0.50 s
C(34,17) = -1961361076   calls = 4667212439   time = 6.47 s

The function makes exactly 2 × answer − 1 calls, because every 1 it adds comes from its own base-case call. So the running time grows as fast as the answer itself. The last line also contradicts the sheet: C(34, 17) is 2,333,606,220, which is bigger than the largest int (2,147,483,647), so the additions overflow and the result prints as a negative number. Adding avoids the huge intermediate factorials, but it can't make a result fit that is too big for an int. For the test cases on the sheet, everything is fine.

Problem 8 · about 25 minutes

Minimum steps to one

Lab sheet §12.8 · Practice Problem 8 · the question, as set

You are given a positive integer N. Your goal is to reduce N to 1 using the absolute minimum number of operations. You are allowed to perform any of the following three operations: 1. Subtract 1 from N. 2. If N is divisible by 2, divide it by 2. 3. If N is divisible by 3, divide it by 3. Write a purely recursive C program that returns the minimum number of steps required to reduce N to 1.

Can you think of a greedy solution to solve this problem? Do you think it would work?

  • Prototype: int minStepsToOne(int n);
  • Entirely recursive.

Test cases: 10 → 3 · 15 → 4 · 1 → 0 · 28 → 4

How to start. You don't know which move is best, so try each one that's allowed and keep the cheapest. Base case: n == 1 needs 0 steps. Recursive case: 1 + the minimum of steps(n − 1), steps(n/2) if n is even, and steps(n/3) if n is divisible by 3. Subtracting 1 is always allowed, so start best with that option. What shrinks: n; every move makes it smaller.
#include <stdio.h>

int minStepsToOne(int n) {
    if (n == 1) {                                /* already there */
        return 0;
    }
    int best = 1 + minStepsToOne(n - 1);         /* option 1: subtract 1 (always allowed) */
    if (n % 2 == 0) {
        int viaHalf = 1 + minStepsToOne(n / 2);  /* option 2: halve */
        if (viaHalf < best) best = viaHalf;
    }
    if (n % 3 == 0) {
        int viaThird = 1 + minStepsToOne(n / 3); /* option 3: divide by 3 */
        if (viaThird < best) best = viaThird;
    }
    return best;
}

int main(void) {
    int tests[] = {10, 15, 1, 28};
    for (int i = 0; i < 4; i++) {
        printf("minStepsToOne(%d) = %d\n", tests[i], minStepsToOne(tests[i]));
    }
    return 0;
}
% ./a.out
minStepsToOne(10) = 3
minStepsToOne(15) = 4
minStepsToOne(1) = 0
minStepsToOne(28) = 4

The sheet's question: does greedy work? No. "Always take the biggest cut available" (÷3 if possible, else ÷2, else −1) fails on the very first test case. Greedy goes 10 → 5 → 4 → 2 → 1, which is 4 steps. The best route is 10 → 9 → 3 → 1, which is 3 steps: subtracting 1 first sets up two ÷3 moves. Test 4 shows the same thing: greedy goes 28 → 14 → 7 → 6 → 2 → 1 (5 steps), but the best is 28 → 27 → 9 → 3 → 1 (4 steps). We checked every n up to 100, and 10 is the first one where greedy loses.

Classic trap · the call count explodes

Every minStepsToOne(n) call starts a whole minStepsToOne(n − 1) search, and the halving and thirding branches repeat work that has already been done elsewhere. Our counts (p8_greedy.c):

n =    10: answer  3, greedy  4, memo  3, calls 47, 0.00 s
n =    15: answer  4, greedy  4, memo  4, calls 110, 0.00 s
n =    28: answer  4, greedy  5, memo  4, calls 643, 0.00 s
n =   100: answer  7, greedy  7, memo  7, calls 58140, 0.00 s
n =   200: answer  8, greedy  8, memo  8, calls 1343053, 0.00 s
n =   400: answer  9, greedy  9, memo  9, calls 52302124, 0.08 s
n =   800: answer 10, greedy 10, memo 10, calls 3478808521, 4.92 s
first greedy failure: n = 10 (greedy 4, best 3)

Doubling n from 400 to 800 multiplied the work by about 66. The "memo" column comes from a version that stores each answer in an array the first time it's computed, and it gives the same answers instantly. That technique (memoisation) is beyond this lab, but it's the standard fix you'll meet later. The sheet's test cases all run in well under a millisecond.

5 · The challenges (sheet §15)

Challenge 1 · the problem with an array of distinct integers

The Change Maker

Lab sheet §15.1 · Challenge · the question, as set

You are given an array of distinct integers representing available coin denominations (e.g., pennies, nickels, dimes) and an integer representing a target amount of money. You have an infinite supply of each coin denomination. Your task is to write a purely recursive C program that calculates the total number of distinct ways you can combine the coins to reach the exact target amount.

Note: The order of coins does not matter. Using a 1-cent coin and then a 2-cent coin is considered the exact same combination as using a 2-cent coin and then a 1-cent coin.

  • Prototype: int countWays(int coins[], int size, int target);
  • Entirely recursive.

Test cases: {1, 2, 3}, 4 → 4 (the ways are (1,1,1,1), (1,1,2), (2,2), (1,3)) · {2, 4}, 7 → 0 · {1, 5, 10, 25}, 10 → 4

How to start. This is Problem 5 with two changes: count instead of yes/no, and coins can be reused. Look at the last denomination, coins[size − 1], and split every possible way into two groups that don't overlap. Group 1 uses this coin at least once: pay one of it, and keep it available (same size, smaller target). Group 2 never uses it (size − 1, same target). The answer is the sum of the two group counts. Base cases: target == 0 is one complete way; target < 0 or no denominations left is zero ways. What shrinks: every call lowers target or size, and neither ever goes up.
#include <stdio.h>

/*
 * Number of ways to make target from coins[0..size-1], any coin any number
 * of times, order not mattering. We decide about the LAST denomination only.
 */
int countWays(int coins[], int size, int target) {
    if (target == 0) {               /* paid exactly: that is one complete way */
        return 1;
    }
    if (target < 0 || size == 0) {   /* overpaid, or no denominations left */
        return 0;
    }
    /* Either use coins[size-1] once more (and keep it available) ... */
    int useIt  = countWays(coins, size, target - coins[size - 1]);
    /* ... or decide never to use it again. */
    int skipIt = countWays(coins, size - 1, target);
    return useIt + skipIt;
}

int main(void) {
    int c1[] = {1, 2, 3};
    int c2[] = {2, 4};
    int c3[] = {1, 5, 10, 25};
    printf("Test 1: %d\n", countWays(c1, 3, 4));
    printf("Test 2: %d\n", countWays(c2, 2, 7));
    printf("Test 3: %d\n", countWays(c3, 4, 10));
    printf("Extra:  {1, 5, 10, 25}, target 100: %d\n", countWays(c3, 4, 100));
    return 0;
}
% ./a.out
Test 1: 4
Test 2: 0
Test 3: 4
Extra:  {1, 5, 10, 25}, target 100: 242

For {1, 5, 10, 25} and 10, the four ways are 10; 5 + 5; 5 + 1×5; and 1×10. Our extra test gives 242 ways to make 100 from these four coins, which matches the published answer for US coins without the 50-cent piece.

Classic trap · counting orders instead of combinations

The tempting version tries every coin at every step. It counts 1 + 1 + 2, 1 + 2 + 1 and 2 + 1 + 1 as three separate ways. We ran it on Test 1 and got orders: 7 instead of 4. The "use the last coin or retire it for good" split stops this: once a denomination is retired, no later call can use it, so every combination is built in exactly one order.

Challenge 2

Recursive prime factorisation

Lab sheet §15.2 · Challenge · the question, as set

The Fundamental Theorem of Arithmetic states that every integer greater than 1 can be uniquely expressed as a product of prime numbers. For example, the prime factorization of 60 is mathematically represented as 2 × 2 × 3 × 5. Your challenge is to write a purely recursive C program that prints the prime factors in ascending order.

  • Prototype: void printPrimeFactors(int n, int divisor); where n is the number to factorize and divisor is the current number checking for divisibility (starts at 2)
  • Entirely recursive.

Test cases: 60 → 2 2 3 5 · 31 → 31 · 64 → 2 2 2 2 2 2

How to start. This is school trial division, written as recursion. Base case: n == 1 means nothing is left to factor. Recursive case: if divisor divides n, print it and factor n / divisor with the same divisor, because 2 may divide again (64). If it doesn't divide, try divisor + 1. What shrinks: each call either makes n smaller or moves divisor one step closer to n. The printed factors come out in ascending order on their own, because the divisor only ever goes up.
#include <stdio.h>

void printPrimeFactors(int n, int divisor) {
    if (n <= 1) {                         /* nothing left to factor */
        return;
    }
    if (divisor * divisor > n) {          /* no divisor up to sqrt(n): n itself is prime */
        printf("%d ", n);
        return;
    }
    if (n % divisor == 0) {
        printf("%d ", divisor);           /* found a factor: print it ...            */
        printPrimeFactors(n / divisor, divisor);   /* ... and keep the SAME divisor */
    } else {
        printPrimeFactors(n, divisor + 1);         /* not a factor: try the next one */
    }
}

int main(void) {
    int tests[] = {60, 31, 64, 1, 97, 360, 1000003};
    for (int i = 0; i < 7; i++) {
        printf("%d: ", tests[i]);
        printPrimeFactors(tests[i], 2);
        printf("\n");
    }
    return 0;
}
% ./a.out
60: 2 2 3 5 
31: 31 
64: 2 2 2 2 2 2 
1: 
97: 97 
360: 2 2 2 3 3 5 
1000003: 1000003 

Why are only primes printed, when the divisor also passes 4, 6 and so on? By the time the divisor reaches 4, every factor of 2 has already been divided out, so 4 can't divide what's left.

Unpack this step: why stop at divisor × divisor > n

If n had a factor bigger than √n, it would have to be paired with a factor smaller than √n, and the search would already have found that one. So once divisor² > n, whatever is left is prime: print it and stop.

Classic trap · the simple version crashes on a big prime

Without the √n stop, a prime n makes the divisor climb all the way from 2 to n, one stack frame per step. We ran that version: 31 needed 31 frames, and 1,000,003 (a prime) crashed with a segmentation fault before printing anything. With the √n stop, 1,000,003 needs only about 1,000 frames and prints instantly (last line of the run above). The sheet's three test cases pass with either version.

6 · What we found when we ran the sheet

Note · sheet errata and claims to handle with care

All the sheet's code compiled and printed exactly what the sheet says (fast power 1024, the 7 Hanoi moves matching its tree, "Target 17 found at index 6"). Every test case's expected output was reproduced. The fast-power figure and the Hanoi recursion tree are both correct. These points need care: