CS U111 · Lab-eval ladder · Stage 5
Recursion: from countdown to every subset
Twenty problems in four rungs, plus three trace-by-hand drills with call-stack tables. Every program reads silently and prints only the answer, the way Moodle VPL marks it, and every card carries 5 test cases. Each solution was compiled with clang -Wall -Wextra -std=c11 (zero warnings), and every expected output was produced by running it.
What this stage covers: Lab Sheet 8 (recursion): base case plus smaller call, printing before or after the call, helper (wrapper) functions, recursion over arrays and strings, and branching recursion (two calls per call). None of these problems is on the sheet; the sheet's own problems are solved on Lab 8 solutions.
What the rungs mean: A is one-line-base-case warm-ups. A+ drills the input shape a recursion eval will most likely use. B is five problems built like real lab evaluations. C is optional: the longer lab-sheet-plus-twist problems.
An honest note on Rung B: no real recursion evaluation has been seen yet. B is calibrated against the instructor's real evals (see the lab-eval bank): it copies the function-eval format exactly (a given prototype, an empty main, read T then T cases) and adds the one rule a recursion eval would most likely add, the function must be recursive, no loops inside it. The difficulty is our estimate.
A fact about the gap: recursion is new to almost everyone in the batch, JEE background or not. School maths and school programming don't drill it. What it needs is one habit, and every First move box below states it out loud: name the base case, name the smaller subproblem, and trust the smaller call.
Time budget: about 3 hours for the core: Rung A 30 min, A+ 15 min, the traces 30 min, Rung B about 1½ h (15–20 min each). Rung C is optional and takes another 3–4 hours. Split it over evenings: A + A+ + traces, then B, then C if time allows.
How to use it: before any code, write two lines on paper: Base case: … and Smaller subproblem: …. Then write the function. Open First move only if those two lines won't come after 3–4 minutes.
Every program here reads silently and prints only the answer, as VPL does: no printf before a scanf, no debug prints left in. Each card has 5 tests, and in VPL each failed test costs 14 %. Check one test with Copy input → run your program → paste your output → Check. Or press Download test script, save it next to your .c file and run sh s5-b1-tests.sh b1.c in Terminal to run all five at once (it compiles with cc -Wall -Wextra). The full explanation is on Stage 0.
Syntax you need for this stage
Recursion adds no new syntax. It is ordinary functions calling themselves. These are the shapes you'll write. For teaching, see the recursion lesson (especially §3 trust the smaller call and §5 code before vs after the call) and the notes kit.
| Write this | It means |
|---|---|
scanf("%d", &t); for (…; i < t; …) { scanf(…); printf("%d\n", f(n)); } | the function-eval main: read T, then per case read, call, print. No loop goes inside f. |
int f(int n) { if (n == 0) return …; return … f(n - 1) …; } | the standard shape: base case first, then one smaller call |
if (n < 10) return …; · f(n / 10) · n % 10 | digit recursion: one digit left · the number without its last digit · that last digit |
printf(…); f(n - 1); vs f(n - 1); printf(…); | print on the way down (first call prints first) vs on the way back up (reversed order) |
int helper(int n, int acc) + int f(int n) { return helper(n, 0); } | wrapper pattern: the helper carries an extra parameter; the wrapper fills in its start value |
f(a, n, i + 1) with base if (i == n) | array recursion: deal with a[i], let the call handle a[i+1..n-1] |
f(s, i + 1) with base if (s[i] == '\0') | string recursion: same idea, the terminator is the base case |
return f(…, choice 1) || f(…, choice 2); | branching: try one choice; if it fails, try the other |
long long, %lld | 64-bit integer for counts that overflow int |
Rung A · Warm-up
Time box: 30 minutes for all four, 5–10 minutes each. Each is one line of base case plus one line of recursive case; A1–A3 already sit inside the function-eval main (read T, then call once per case). If you can write all four from a blank file in 20 minutes, go straight to Rung A+.
A1 · Factorial
Write int factorial(int n); recursively (no loops inside it), returning n! for 0 ≤ n ≤ 12. Then write main: read T, then T integers; for each, call factorial and print the result on its own line.
Starter (given)
#include <stdio.h>
int factorial(int n);
int main(void) {
return 0;
}
int factorial(int n) {
}
Input T, then T integers n (0 ≤ n ≤ 12).
Output T lines, one factorial each.
3 5 0 3
120 1 6
1 0
1
1 12
479001600
2 1 2
1 2
4 4 6 7 10
24 720 5040 3628800
Stuck? First move
Base case: n == 0 → return 1 (0! = 1). Smaller subproblem: factorial(n - 1). Then n! = n × (n − 1)!, so return n * factorial(n - 1). main only reads, calls and prints.
Plan in plain words
- If n is 0, the answer is 1.
- Otherwise, the answer is n times the factorial of n − 1.
- main: read T; T times: read n, print factorial(n).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int factorial(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) { /* one pass per test value */
scanf("%d", &n);
printf("%d\n", factorial(n));
}
return 0;
}
int factorial(int n) {
if (n == 0) return 1; /* base case: 0! = 1 */
return n * factorial(n - 1); /* n! = n x (n-1)! */
}
Using base case n == 1 only. Then factorial(0) calls factorial(-1), factorial(-2), … and never stops, and the program crashes when the stack runs out (a segmentation fault). Test 2 is exactly that input: always test the smallest legal value. The 12 limit is there because 13! is too big for an int.
A2 · Power
Write int power(int x, int n); recursively, returning xn for n ≥ 0 (with x0 = 1 for every x, 0 included). Then write main: read T, then T lines x n; print each power on its own line. (The sheet's §11.1 shows a faster version; this one is the plain one.)
Starter (given)
#include <stdio.h>
int power(int x, int n);
int main(void) {
return 0;
}
int power(int x, int n) {
}
Input T, then T lines of two integers x n (n ≥ 0; every answer fits in an int).
Output T lines, one power each.
3 2 10 7 0 -3 3
1024 1 -27
1 0 0
1
2 -2 4 -2 5
16 -32
2 0 5 1 30
0 1
1 10 9
1000000000
Stuck? First move
Base case: n == 0 → return 1. Smaller subproblem: power(x, n - 1). Only n shrinks; x is passed along unchanged. Then return x * power(x, n - 1).
Plan in plain words
- If n is 0, the answer is 1.
- Otherwise, it is x times x to the power n − 1.
- main: read T; T times: read x and n, print power(x, n).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int power(int x, int n);
int main(void) {
int t, x, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &x, &n); /* two numbers per case */
printf("%d\n", power(x, n));
}
return 0;
}
int power(int x, int n) {
if (n == 0) return 1; /* base case: x^0 = 1 */
return x * power(x, n - 1); /* x^n = x * x^(n-1) */
}
Shrinking the wrong argument: power(x - 1, n) never reaches n == 0, so it recurses until it crashes. Ask "which argument gets closer to the base case?" and shrink that one.
A3 · Sum 1 to n
Write int sumTo(int n); recursively, returning 1 + 2 + … + n (and 0 for n = 0). Then write main: read T, then T integers; print each sum on its own line.
Starter (given)
#include <stdio.h>
int sumTo(int n);
int main(void) {
return 0;
}
int sumTo(int n) {
}
Input T, then T integers n (0 ≤ n ≤ 10000).
Output T lines, one sum each.
3 100 1 0
5050 1 0
1 0
0
2 2 3
3 6
1 10000
50005000
3 5 6 7
15 21 28
Stuck? First move
Base case: n == 0 → return 0 (nothing to add). Smaller subproblem: sumTo(n - 1), which is 1 + … + (n − 1). Add n to it.
Plan in plain words
- If n is 0, return 0.
- Otherwise return n plus the sum up to n − 1.
- main: the same T-loop as A1.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int sumTo(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", sumTo(n));
}
return 0;
}
int sumTo(int n) {
if (n == 0) return 0; /* base case: nothing to add */
return n + sumTo(n - 1); /* 1+...+n = n + (1+...+(n-1)) */
}
A4 · Count down, count up
Write two recursive void functions with no loops: countDown(n) prints n n-1 … 1 and countUp(n) prints 1 2 … n, each number with a space in front. main reads one integer n ≥ 0 and prints two lines: DOWN followed by the countdown, then UP followed by the count up.
Input One integer n (0 ≤ n ≤ 100).
Output Two lines: DOWN and the numbers from n to 1, then UP and the numbers from 1 to n. For n = 0 both lines have only the word.
5
DOWN 5 4 3 2 1 UP 1 2 3 4 5
1
DOWN 1 UP 1
0
DOWN UP
2
DOWN 2 1 UP 1 2
10
DOWN 10 9 8 7 6 5 4 3 2 1 UP 1 2 3 4 5 6 7 8 9 10
Stuck? First move
Both functions have the same base case, n == 0 → print nothing and return;, and the same smaller subproblem, the call on n - 1. The only difference is whether the printf of n comes before the call or after it.
Plan in plain words
- countDown: if n is 0 stop; print n; count down from n − 1.
- countUp: if n is 0 stop; count up to n − 1; print n.
- main: read n; print the word, call, newline; twice.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
void countDown(int n) {
if (n == 0) return; /* base case: nothing to print */
printf(" %d", n); /* print FIRST ... */
countDown(n - 1); /* ... then handle the rest */
}
void countUp(int n) {
if (n == 0) return;
countUp(n - 1); /* handle the rest FIRST ... */
printf(" %d", n); /* ... print on the way back */
}
int main(void) {
int n;
scanf("%d", &n);
printf("DOWN");
countDown(n);
printf("\nUP");
countUp(n);
printf("\n");
return 0;
}
Thinking countUp needs a second parameter that counts upward. It doesn't. Code placed after the call runs as the calls return, and the deepest call (n = 1) returns first. Trace T2 below tests exactly this.
Rung A+ · Input patterns
Time box: 15 minutes for both. These train only the shape a recursion eval will most likely have: you are given the prototype and an empty main; you fill in a recursive body, and main reads T, then calls the function once per case and prints each result on its own line. A+1 has one number per case, A+2 has two. The calculation must happen inside the function, as the real function evals require.
A+1 · Double factorial
The double factorial n!! multiplies every second number down from n: 7!! = 7 × 5 × 3 × 1 = 105 and 8!! = 8 × 6 × 4 × 2 = 384. By definition 0!! = 1 and 1!! = 1. Write int doubleFactorial(int n); and a main that reads T, then T integers, calls the function for each and prints the result on its own line.
Your function must be recursive: no for, while or do inside it. (The loop in main over the T cases is fine.)
Starter (given)
#include <stdio.h>
int doubleFactorial(int n);
int main(void) {
return 0;
}
int doubleFactorial(int n) {
}
Input T, then T integers n (0 ≤ n ≤ 19), one per line or space-separated.
Output T lines, one double factorial each.
3 5 6 0
15 48 1
1 1
1
2 2 3
2 3
1 19
654729075
2 10 11
3840 10395
Stuck? First move
Smaller subproblem: doubleFactorial(n - 2), because the next factor is two below. Base case: the steps of 2 land on 0 (even n) or on 1 (odd n), so the base must catch both: if (n <= 1) return 1;.
Plan in plain words
- n is 0 or 1 → 1.
- Otherwise → n times doubleFactorial(n − 2).
- main: read T; T times: read, call, print.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int doubleFactorial(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", doubleFactorial(n));
}
return 0;
}
int doubleFactorial(int n) {
if (n <= 1) return 1; /* base: catches 0 (even n) AND 1 (odd n) */
return n * doubleFactorial(n - 2); /* step down by 2, not 1 */
}
Copying factorial's base case n == 0. Odd numbers step 5, 3, 1, −1, −3, … and skip 0 forever, so every odd value crashes the program, and every one of the five tests contains an odd value. When the argument jumps by more than 1, check that every starting value lands on a base case.
A+2 · Multiply by adding
Write int multiply(int a, int b); that returns a × b for b ≥ 0 without using the * operator, using a × b = a + a × (b − 1). Then write main: read T, then T lines a b; call multiply for each and print the result on its own line.
Your function must be recursive: no for, while or do inside it. (The loop in main over the T cases is fine.)
Starter (given)
#include <stdio.h>
int multiply(int a, int b);
int main(void) {
return 0;
}
int multiply(int a, int b) {
}
Input T, then T lines of two integers a b (−1000 ≤ a ≤ 1000, 0 ≤ b ≤ 1000).
Output T lines, one product each.
3 4 5 7 0 -3 4
20 0 -12
1 0 9
0
1 9 1
9
2 -6 0 123 1000
0 123000
1 -1000 1000
-1000000
Stuck? First move
Two numbers arrive per case, so scanf("%d %d", &a, &b) inside the T-loop. In the function, base case: b == 0 → 0 (anything times 0). Smaller subproblem: multiply(a, b - 1); add one more a to it.
Plan in plain words
- b is 0 → 0.
- Otherwise → a + multiply(a, b − 1).
- main: read T; T times: read a and b, print multiply(a, b).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int multiply(int a, int b);
int main(void) {
int t, a, b;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &a, &b);
printf("%d\n", multiply(a, b));
}
return 0;
}
int multiply(int a, int b) {
if (b == 0) return 0; /* base: a x 0 = 0 */
return a + multiply(a, b - 1); /* a x b = a + a x (b-1); only b shrinks */
}
Recursing on a instead of b. a can be negative or 0, so a - 1 heads away from any base case (Tests 1, 4 and 5 have negative a). Shrink the argument whose range has a floor: here b ≥ 0.
Trace by hand · three call-stack tables
Lab evaluations and the end-sem include "what does this print?" questions on recursion. Draw the table before opening the answer: one row per call (frame), with what it is waiting for and what it returns. Each answer was checked by running the code, and the instrumented program is shown, so you can use the same trick on any recursion you are unsure about. For more practice, the recursion dry-run drill generates endless ones.
T1 · What does sumTo(4) wait for?
Using A3's sumTo, fill in this table for the call sumTo(4): one row per frame, with columns call, base case?, waits for, returns.
Stuck? First move
Write the rows top-down: each call makes exactly one smaller call until n == 0. Then fill the returns column bottom-up, because each frame can only finish once the frame below it has returned.
Answer, checked with clang
| Frame | Call | Base case? | Waits for | Returns |
|---|---|---|---|---|
| 1 | sumTo(4) | no | 4 + sumTo(3) | 4 + 6 = 10 |
| 2 | sumTo(3) | no | 3 + sumTo(2) | 3 + 3 = 6 |
| 3 | sumTo(2) | no | 2 + sumTo(1) | 2 + 1 = 3 |
| 4 | sumTo(1) | no | 1 + sumTo(0) | 1 + 0 = 1 |
| 5 | sumTo(0) | yes | nothing | 0 |
Read the Call column downwards and the Returns column upwards. At the deepest point, five frames are open at once. This instrumented copy prints every call and return, indented by depth:
#include <stdio.h>
int depth = 0; /* how many calls are open right now */
int sumTo(int n) {
printf("%*scall sumTo(%d)\n", depth * 2, "", n);
depth++;
int r;
if (n == 0) r = 0;
else r = n + sumTo(n - 1);
depth--;
printf("%*ssumTo(%d) returns %d\n", depth * 2, "", n, r);
return r;
}
int main(void) {
printf("Answer: %d\n", sumTo(4));
return 0;
}
call sumTo(4)
call sumTo(3)
call sumTo(2)
call sumTo(1)
call sumTo(0)
sumTo(0) returns 0
sumTo(1) returns 1
sumTo(2) returns 3
sumTo(3) returns 6
sumTo(4) returns 10
Answer: 10
T2 · What does mirror(3) print?
Write the exact output of this program, spaces included.
#include <stdio.h>
void mirror(int n) {
if (n == 0) {
printf("| ");
return;
}
printf("%d ", n);
mirror(n - 1);
printf("%d ", n);
}
int main(void) {
mirror(3);
printf("\n");
return 0;
}
Stuck? First move
Each frame does three things in order: print n, make the smaller call, print n again. Write one row per frame, with columns prints before the call and prints after the call. The base frame prints | and nothing else.
Answer, checked with clang
| Frame | Before the call | Then | After the call |
|---|---|---|---|
| mirror(3) | 3 | calls mirror(2) | 3 |
| mirror(2) | 2 | calls mirror(1) | 2 |
| mirror(1) | 1 | calls mirror(0) | 1 |
| mirror(0) | base case: prints | and returns | ||
Read the "before" column downwards, then the base case, then the "after" column upwards:
3 2 1 | 1 2 3
T3 · gcd(105, 252): how many calls?
For the function below, list every call made by gcd(105, 252) and the final answer. What happens in the first call, where a < b?
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}Stuck? First move
Use a table with columns a, b, a % b, next call. Each next call is gcd(b, a % b), so the old b moves left and the remainder becomes the new b. Stop at the row where b is 0.
Answer, checked with clang
| a | b | a % b | Next |
|---|---|---|---|
| 105 | 252 | 105 | gcd(252, 105) |
| 252 | 105 | 42 | gcd(105, 42) |
| 105 | 42 | 21 | gcd(42, 21) |
| 42 | 21 | 0 | gcd(21, 0) |
| 21 | 0 | (not computed) | base case: return 21 |
That's five calls. When a < b, a % b is just a, so the first call simply swaps the two numbers, and you don't need an if for it. Nothing is waiting after each call (return gcd(…) passes the answer straight up), so 21 travels back up unchanged. The same program with a trace line added:
#include <stdio.h>
int gcd(int a, int b) {
printf("gcd(%d, %d)\n", a, b); /* trace line: shows every call */
if (b == 0) return a;
return gcd(b, a % b);
}
int main(void) {
printf("Answer: %d\n", gcd(105, 252));
return 0;
}
gcd(105, 252)
gcd(252, 105)
gcd(105, 42)
gcd(42, 21)
gcd(21, 0)
Answer: 21
Rung B · VPL level
Time box: 15–20 minutes each, about 1½ hours for all five. No real recursion evaluation has been seen yet, so these copy the real function evals' format (given prototype, empty main and body, T cases, 5 tests) and add the rule a recursion eval would most likely add: the function must be recursive, with no loops inside it. The difficulty is our estimate. What they train: picking the right base case first time, because the tests aim at the smallest inputs (0, 1, a number below the base), where a wrong base case either gives a wrong answer or never stops.
B1 · Product of the digits
Write int digitProduct(int n); that returns the product of the decimal digits of the non-negative integer n. For example 234 → 2 × 3 × 4 = 24 and 105 → 1 × 0 × 5 = 0. A single-digit number is its own product, so 0 → 0 and 7 → 7. Then write main: read T, then T integers; for each, call digitProduct and print the value it returns on its own line.
Your function must be recursive: no for, while or do inside it. (The loop in main over the T cases is fine.)
Starter (given)
#include <stdio.h>
int digitProduct(int n);
int main(void) {
return 0;
}
int digitProduct(int n) {
}
Input T, then T integers n (0 ≤ n ≤ 2147483647), one per line or space-separated.
Output T lines, one product each.
3 234 7 105
24 7 0
1 0
0
2 9 10
9 0
1 2147483647
903168
3 999 111 2222
729 1 16
Stuck? First move
Base case: n < 10, one digit left: return n itself (this also gives 0 → 0). Smaller subproblem: digitProduct(n / 10), the number without its last digit. Multiply it by the last digit, n % 10.
Plan in plain words
- One digit → that digit.
- Otherwise → (last digit) × product of the rest.
- main: read T; T times: read, call, print.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int digitProduct(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", digitProduct(n));
}
return 0;
}
int digitProduct(int n) {
if (n < 10) return n; /* base: one digit (0 gives 0) */
return (n % 10) * digitProduct(n / 10); /* last digit x product of the rest */
}
The "sum of digits" base case, if (n == 0) return 0;, turns every product into 0, because the last call multiplies by it. Switching to return 1 fixes most tests but makes digitProduct(0) return 1 instead of 0, so Test 2 fails. Stopping at n < 10 handles both.
B2 · Is it a power of 3?
Write int isPowerOf3(int n); that returns 1 if n is a power of 3 (1, 3, 9, 27, …; note 1 = 30) and 0 otherwise. 0 is not a power of 3. Then write main: read T, then T integers; for each, call isPowerOf3 and print YES if it returned 1, or NO.
Your function must be recursive: no for, while or do inside it. (The loop in main over the T cases is fine.)
Starter (given)
#include <stdio.h>
int isPowerOf3(int n);
int main(void) {
return 0;
}
int isPowerOf3(int n) {
}
Input T, then T integers n (0 ≤ n ≤ 2147483647).
Output T lines, each YES or NO.
3 9 10 81
YES NO YES
1 1
YES
2 0 3
NO YES
3 6 18 2
NO NO NO
2 1162261467 2147483647
YES NO
Stuck? First move
There are three stopping points, in this order: n == 0 → 0; n == 1 → 1 (reached 30); n % 3 != 0 → 0 (a factor other than 3 is left). Smaller subproblem: otherwise isPowerOf3(n / 3). The function returns a number; main turns it into the word.
Plan in plain words
- 0 → no.
- 1 → yes.
- Not divisible by 3 → no.
- Otherwise → same question for n / 3.
- main: print YES for 1, NO for 0.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int isPowerOf3(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
if (isPowerOf3(n)) printf("YES\n"); /* main prints the words */
else printf("NO\n");
}
return 0;
}
int isPowerOf3(int n) {
if (n == 0) return 0; /* base: 0 / 3 is 0 again, so stop here */
if (n == 1) return 1; /* base: reached 3^0 */
if (n % 3 != 0) return 0; /* base: some other factor is left */
return isPowerOf3(n / 3); /* divisible: ask about n / 3 */
}
Leaving out the n == 0 check. 0 % 3 is 0 and 0 / 3 is 0, so the call repeats with the same argument forever and the program crashes: Test 3 fails. A second mark-loser is checking divisibility only once (6 and 18 are divisible by 3 but are not powers of 3: Test 4).
B3 · Ways to climb the stairs
You climb a staircase of n steps, taking 1 or 2 steps at a time. Write int countWays(int n); that returns the number of different orders of moves that reach the top. For n = 3 there are 3: 1+1+1, 1+2, 2+1. For n = 0 there is exactly 1 way (do nothing). Then write main: read T, then T integers; print countWays of each on its own line.
Your function must be recursive: no for, while or do inside it. (The loop in main over the T cases is fine.)
Starter (given)
#include <stdio.h>
int countWays(int n);
int main(void) {
return 0;
}
int countWays(int n) {
}
Input T, then T integers n (0 ≤ n ≤ 30).
Output T lines, one count each.
3 3 4 5
3 5 8
1 0
1
2 1 2
1 2
1 10
89
1 30
1346269
Stuck? First move
Sort the ways by their first move. First move 1 step: countWays(n - 1) ways to finish. First move 2 steps: countWays(n - 2). Return the sum. Base case: n <= 1 → 1 (for n = 0 and n = 1 there is one way each). Without the 1 case, countWays(1) would call countWays(-1).
Plan in plain words
- n is 0 or 1 → 1 way.
- Otherwise → ways after a 1-step start + ways after a 2-step start.
- main: read T; T times: read, call, print.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int countWays(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", countWays(n));
}
return 0;
}
int countWays(int n) {
if (n <= 1) return 1; /* base: 0 or 1 step left, one way */
return countWays(n - 1) + countWays(n - 2); /* first move 1 step, or 2 steps */
}
The answers 1, 1, 2, 3, 5, 8, … are the Fibonacci numbers shifted by one. n = 30 makes about 2.7 million calls and still finishes well inside a second; C9 shows why the call count grows so fast and how to cut it.
Writing the base cases as n == 1 → 1 and n == 2 → 2. That is correct for every n ≥ 1 but countWays(0) falls through to countWays(-1) and never stops: Test 2 crashes. The spec named n = 0 on purpose; base-case tests are where the hidden tests look first.
B4 · Collatz steps
Start from a positive integer n. If it is even, halve it; if it is odd, replace it with 3n + 1. Repeat until you reach 1. For example 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 takes 8 steps, and 1 takes 0 steps. Write int collatzSteps(int n); that returns the number of steps, and a main that reads T, then T integers, and prints collatzSteps of each on its own line.
Your function must be recursive: no for, while or do inside it. (The loop in main over the T cases is fine.)
Starter (given)
#include <stdio.h>
int collatzSteps(int n);
int main(void) {
return 0;
}
int collatzSteps(int n) {
}
Input T, then T integers n (1 ≤ n ≤ 10000).
Output T lines, one step count each.
3 6 1 7
8 0 16
1 1
0
2 2 3
1 7
1 27
111
2 9999 8192
91 13
Stuck? First move
Base case: n == 1 → 0 steps left. Smaller subproblem: the count from the next number, which is n / 2 or 3 * n + 1. This step plus the rest: return 1 + collatzSteps(next);. "Smaller" here means "closer to the end", not a smaller number.
Plan in plain words
- n is 1 → 0.
- n even → 1 + steps from n / 2.
- n odd → 1 + steps from 3n + 1.
- main: read T; T times: read, call, print.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int collatzSteps(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", collatzSteps(n));
}
return 0;
}
int collatzSteps(int n) {
if (n == 1) return 0; /* base: already at 1, no steps */
if (n % 2 == 0) return 1 + collatzSteps(n / 2); /* this step + the rest */
return 1 + collatzSteps(3 * n + 1);
}
Some values climb a long way before falling: 27 goes up to 9232 and takes 111 steps. Within 1 ≤ n ≤ 10000 every value stays far below the int limit.
Off by one: if (n == 1) return 1; counts the numbers in the sequence instead of the steps between them, so every answer is 1 too big (Test 2 expects 0 for n = 1). Check your base case against the smallest example in the statement before writing anything else.
B5 · Whole-number logarithm
Write int logFloor(int n, int b); that returns the largest whole number e with be ≤ n. For example logFloor(100, 10) = 2, logFloor(99, 10) = 1 and logFloor(5, 7) = 0 (since 70 = 1 ≤ 5 but 71 > 5). Then write main: read T, then T lines n b; call logFloor for each and print the value it returns on its own line.
Your function must be recursive: no for, while or do inside it. (The loop in main over the T cases is fine.)
Starter (given)
#include <stdio.h>
int logFloor(int n, int b);
int main(void) {
return 0;
}
int logFloor(int n, int b) {
}
Input T, then T lines of two integers n b (1 ≤ n ≤ 2147483647, 2 ≤ b ≤ 10).
Output T lines, one exponent each.
3 100 10 99 10 1 2
2 1 0
2 5 7 7 7
0 1
2 1024 2 1023 2
10 9
1 2147483647 2
30
3 1000000000 10 80 3 81 3
9 3 4
Stuck? First move
Each whole division by b uses up one factor of b. Base case: n < b → 0 (not even b1 fits). Smaller subproblem: logFloor(n / b, b); add 1 for the division just done. Only n shrinks; b is passed along unchanged.
Plan in plain words
- n smaller than b → 0.
- Otherwise → 1 + logFloor(n / b, b).
- main: read T; T times: read n and b, print logFloor(n, b).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int logFloor(int n, int b);
int main(void) {
int t, n, b;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &n, &b);
printf("%d\n", logFloor(n, b));
}
return 0;
}
int logFloor(int n, int b) {
if (n < b) return 0; /* base: b^1 is already too big */
return 1 + logFloor(n / b, b); /* one factor of b used up */
}
Unpack this step: why does dividing again and again give the exponent?
Whole division twice, (n / b) / b, gives the same result as n / b2 rounded down. So after e divisions you hold n / be, and it is still ≥ 1 exactly when be ≤ n. For 100 and 10: 100 → 10 → 1, two divisions, and 1 < 10 stops it.
Stopping at n == 1 or n == 0 instead of n < b. With n == 1, 99 → 9 → 0 → 0 → … misses 1 and never stops; with n == 0 every answer comes out 1 too big. The boundary tests (99 vs 100, 1023 vs 1024, 80 vs 81) are there to catch exactly this.
Rung C · Beyond the eval (optional)
These are the old lab-sheet-plus-twist problems: longer than any eval we've seen. Do them after B, if time allows; they build fluency for the end-semester lab exam. C1–C5 are at the level of Lab 8's Practice Problems 1–3 (digits, a helper function, array and string recursion; allow 15–20 minutes each). C6–C9 use branching recursion, where each call makes two calls: the idea behind the sheet's Exact Change, Rat in a Maze and Change Maker, used on new tasks (allow 25–40 minutes each). Use the same two lines every time: base case, then smaller subproblem(s).
C1 · How many digits, and how many of digit d?
Read a non-negative integer n and a digit d (0–9). With two recursive functions and no loops, print how many digits n has (0 has one digit) and how many times d appears in it.
Input One line: n d (0 ≤ n ≤ 2147483647, 0 ≤ d ≤ 9).
Output Two lines: Digits: k, then d appears c time(s) with the real values of k, d and c.
1020300 0
Digits: 7 0 appears 4 time(s)
0 0
Digits: 1 0 appears 1 time(s)
98765 3
Digits: 5 3 appears 0 time(s)
7 7
Digits: 1 7 appears 1 time(s)
2147483647 4
Digits: 10 4 appears 3 time(s)
Stuck? First move
Base case (for both): n < 10, meaning a single digit is left. countDigits returns 1; countDigit returns (n == d), which is 1 or 0. Smaller subproblem: the same function on n / 10 (the number without its last digit). Add 1, or add (n % 10 == d).
Plan in plain words
- countDigits(n): one digit → 1; else 1 + countDigits(n without its last digit).
- countDigit(n, d): one digit → 1 if it equals d, else 0; else (1 if the last digit equals d) + countDigit(rest, d).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int countDigits(int n) {
if (n < 10) return 1; /* base: one digit left (0 counts as 1 digit) */
return 1 + countDigits(n / 10); /* last digit + digits of the rest */
}
int countDigit(int n, int d) {
if (n < 10) return (n == d); /* base: 1 if this last digit matches */
return (n % 10 == d) + countDigit(n / 10, d);
}
int main(void) {
int n, d;
scanf("%d %d", &n, &d);
printf("Digits: %d\n", countDigits(n));
printf("%d appears %d time(s)\n", d, countDigit(n, d));
return 0;
}
Using n == 0 as the base case. Then countDigits(0) returns 0, which is wrong (0 has one digit), and for d = 0 the zero in 0 is never counted. Test 2 is exactly that input.
C2 · Reverse a number (and spot palindromes)
Write int reverseNumber(int n) for n ≥ 0 using a recursive helper and no loops. Print the reversed number (leading zeros vanish: 1200 → 21) and whether n is a palindrome.
Input One integer n (0 ≤ n ≤ 1000000000, and its reverse fits in an int).
Output Two lines: Reversed: r, then Palindrome: yes or Palindrome: no.
1234
Reversed: 4321 Palindrome: no
1200
Reversed: 21 Palindrome: no
12321
Reversed: 12321 Palindrome: yes
0
Reversed: 0 Palindrome: yes
10
Reversed: 1 Palindrome: no
Stuck? First move
The answer is built up digit by digit, so the helper needs a second parameter acc (the reversed part so far): revHelper(int n, int acc). Base case: n == 0 → return acc. Smaller subproblem: revHelper(n / 10, acc * 10 + n % 10), which moves the last digit of n onto the end of acc. The wrapper calls revHelper(n, 0).
Plan in plain words
- helper(n, acc): no digits left → acc is the answer.
- Otherwise: take n's last digit, append it to acc (acc × 10 + digit), drop it from n, recurse.
- reverseNumber(n) = helper(n, 0). Palindrome ⇔ reverse equals n.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* helper: move digits of n onto the end of acc, one per call */
int revHelper(int n, int acc) {
if (n == 0) return acc; /* base: no digits left */
return revHelper(n / 10, acc * 10 + n % 10); /* take the last digit of n */
}
int reverseNumber(int n) { /* wrapper: starts acc at 0 */
return revHelper(n, 0);
}
int main(void) {
int n;
scanf("%d", &n);
int r = reverseNumber(n);
printf("Reversed: %d\n", r);
printf("Palindrome: %s\n", (r == n) ? "yes" : "no");
return 0;
}
Unpack: one row at a time for revHelper(1234, 0)
(1234, 0) → (123, 4) → (12, 43) → (1, 432) → (0, 4321) → base case returns 4321. Each step: acc * 10 + n % 10 appends a digit and n / 10 removes it.
Printing the digits one by one instead of building a number. 1200 then prints 0021, but the spec (and Test 2) wants 21: as a number, leading zeros vanish.
C3 · GCD and LCM
Read two positive integers. Using a recursive gcd (Euclid's rule: gcd(a, b) = gcd(b, a mod b)), print the GCD and the LCM.
Input One line: a b (1 ≤ a, b ≤ 100000; the LCM fits in an int).
Output Two lines: GCD = g, then LCM = l.
84 36
GCD = 12 LCM = 252
17 5
GCD = 1 LCM = 85
21 21
GCD = 21 LCM = 21
1 1
GCD = 1 LCM = 1
60000 40000
GCD = 20000 LCM = 120000
Stuck? First move
Base case: b == 0 → return a (every number divides 0, so gcd(a, 0) = a). Smaller subproblem: gcd(b, a % b). The remainder is always smaller than b, so the second argument shrinks to 0. Then LCM = a / gcd × b.
Plan in plain words
- gcd(a, b): b is 0 → a; else gcd(b, remainder of a ÷ b).
- main: read, g = gcd, print g and a / g × b.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) return a; /* base: gcd(a, 0) = a */
return gcd(b, a % b); /* Euclid: same gcd, smaller numbers */
}
int main(void) {
int a, b;
scanf("%d %d", &a, &b);
int g = gcd(a, b);
printf("GCD = %d\n", g);
printf("LCM = %d\n", a / g * b); /* divide first: keeps numbers small */
return 0;
}
Computing LCM as a * b / g. The product overflows an int long before the LCM does: 60000 × 40000 = 2.4 billion is past the int limit of about 2.1 billion, so Test 5 prints garbage. Divide first.
C4 · Is the array sorted? Where does it break?
Read n (1 ≤ n ≤ 100) and n integers. With a recursive function (reading the input with a loop is fine), find the first index i where a[i] < a[i-1]. Print Sorted if there is none (equal neighbours are allowed). Otherwise print the pair in the form Not sorted: a[3]=5 is less than a[2]=7.
Input n, then n integers.
Output Sorted, or one line Not sorted: a[i]=x is less than a[j]=y with the real indices and values (j = i − 1).
5 1 3 3 8 9
Sorted
5 2 4 7 5 9
Not sorted: a[3]=5 is less than a[2]=7
1 42
Sorted
2 5 5
Sorted
4 9 1 2 3
Not sorted: a[1]=1 is less than a[0]=9
Stuck? First move
Use the signature int firstDrop(int a[], int n, int i), meaning "first drop at index i or later, or −1", and start it with i = 1. There are two base cases: i >= n (ran off the end: return −1) and a[i] < a[i - 1] (found it: return i). Smaller subproblem: firstDrop(a, n, i + 1), the same question on the rest of the array.
Plan in plain words
- firstDrop(i): past the end → −1. a[i] smaller than a[i−1] → i. Otherwise → firstDrop(i + 1).
- main: read; d = firstDrop starting at 1; −1 → Sorted, else print a[d] and a[d−1].
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* Index of the first element smaller than the one before it, looking from i on.
-1 means "no drop: sorted from here". */
int firstDrop(int a[], int n, int i) {
if (i >= n) return -1; /* base: ran off the end, no drop found */
if (a[i] < a[i - 1]) return i; /* base: found the drop */
return firstDrop(a, n, i + 1); /* check the rest */
}
int main(void) {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int d = firstDrop(a, n, 1); /* start comparing a[1] with a[0] */
if (d == -1) printf("Sorted\n");
else printf("Not sorted: a[%d]=%d is less than a[%d]=%d\n", d, a[d], d - 1, a[d - 1]);
return 0;
}
Putting the comparison before the i >= n check. The last call then reads a[n], one element past the end, and the answer depends on whatever garbage is there. Check the bounds first, as in the sheet's Debugging Exercise 4.
C5 · Print a line backwards, without loops
Read a line with fgets. Print REVERSED, a space, and the line backwards, using a recursive void printReverse(const char s[], int i). You may not use a loop or a second array.
Input One line of text (at most 198 characters; it may be empty).
Output One line: REVERSED, a space, then the line backwards (just REVERSED for an empty line).
stressed
REVERSED desserts
a b c
REVERSED c b a
REVERSED
x
REVERSED x
Hello, World!
REVERSED !dlroW ,olleH
Stuck? First move
Base case: s[i] == '\0' → nothing to print, return. Smaller subproblem: printReverse(s, i + 1), which prints everything after position i backwards. So: call first, then putchar(s[i]). That's A4's countUp idea applied to a string.
Plan in plain words
- printReverse(i): at the terminator → stop.
- Otherwise: print the rest backwards (recursive call), then print s[i].
- main: read, strip the newline, print the word, call with i = 0, newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
void printReverse(const char s[], int i) {
if (s[i] == '\0') return; /* base: past the last character */
printReverse(s, i + 1); /* first print everything after s[i] ... */
putchar(s[i]); /* ... then s[i] itself */
}
int main(void) {
char s[200];
if (fgets(s, sizeof(s), stdin) == NULL) s[0] = '\0'; /* no line at all: treat as empty */
s[strcspn(s, "\n")] = '\0';
printf("REVERSED ");
printReverse(s, 0);
printf("\n");
return 0;
}
Forgetting to strip the '\n'. The newline then becomes the first character printed, so the reversed text starts on a new line. VPL's token comparison happens to forgive that here, but the same leftover '\n' makes a length one too big or a palindrome check fail. Strip it every time: that's the Stage 4 input rule, still in force here.
C6 · Every subset of a few letters
Read a line of distinct letters (at most 10). Print every subset, one per line, in this order: for each letter, first every subset that includes it, then every one that excludes it. The order is fixed by "take, then leave", so match Test 1 exactly. Print the empty subset as {}, and finish with Total: n.
Input One line of distinct letters (it may be empty).
Output Every subset on its own line, in take-then-leave order, the empty one as {}; then Total: n.
abc
abc
ab
ac
a
bc
b
c
{}
Total: 8x
x
{}
Total: 2{}
Total: 1ab
ab
a
b
{}
Total: 4abcd
abcd
abc
abd
ab
acd
ac
ad
a
bcd
bc
bd
b
cd
c
d
{}
Total: 16Stuck? First move
Walk through the letters by index i, carrying an out[] array with the letters chosen so far and its length k: subsets(s, i, out, k). Base case: s[i] == '\0', meaning every letter has been decided, so terminate out at k and print it. Smaller subproblems (two): put s[i] into out[k] and call with (i + 1, k + 1) to take it, then call with (i + 1, k) to leave it.
Plan in plain words
- If all letters are decided: end out at length k; print it (or {}); add 1 to the total.
- Otherwise: write s[i] at out[k] and decide the rest with k + 1 letters chosen (take).
- Then decide the rest with k letters chosen (leave). Whatever was written at out[k] gets overwritten or cut off by the terminator.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int total = 0; /* global: counts subsets across all calls */
/* Decide about s[i]; out[0..k-1] holds the letters chosen so far. */
void subsets(const char s[], int i, char out[], int k) {
if (s[i] == '\0') { /* base: every letter decided */
out[k] = '\0';
if (k == 0) printf("{}\n");
else printf("%s\n", out);
total++;
return;
}
out[k] = s[i];
subsets(s, i + 1, out, k + 1); /* choice 1: take s[i] */
subsets(s, i + 1, out, k); /* choice 2: leave s[i] (out[k] is overwritten later) */
}
int main(void) {
char s[20], out[20];
if (fgets(s, sizeof(s), stdin) == NULL) s[0] = '\0';
s[strcspn(s, "\n")] = '\0';
subsets(s, 0, out, 0);
printf("Total: %d\n", total);
return 0;
}
Unpack: why are there 2n lines?
Each letter is a yes/no decision, and the decisions are independent: 2 × 2 × … × 2 (n times). For abc that's 2 × 2 × 2 = 8, matching Total: 8. The empty input makes no decisions, and its one subset is {}.
Writing only the "take" call. That prints a single line, abc. Every branching problem needs both choices as separate calls, which is the same shape as the sheet's Exact Change.
C7 · Counting paths in a grid
A robot starts in the top-left cell of an r × c grid (1 ≤ r, c ≤ 12) and may only move right or down, one cell at a time. Count the different routes to the bottom-right cell with a recursive function. Also print how many calls your function made, using a global counter.
Input One line: r c.
Output Two lines: Paths: p, then Calls made: k.
3 3
Paths: 6 Calls made: 11
2 4
Paths: 4 Calls made: 7
1 5
Paths: 1 Calls made: 1
10 10
Paths: 48620 Calls made: 97239
1 1
Paths: 1 Calls made: 1
Stuck? First move
Base case: r == 1 || c == 1: a single row or column has exactly one route (straight along it). Smaller subproblems (two): paths(r - 1, c) if the first move is down, and paths(r, c - 1) if it is right. Return their sum (see the figure).
Plan in plain words
- Add 1 to the call counter.
- One row or one column → 1 route.
- Otherwise → routes after moving down + routes after moving right.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
long long calls = 0; /* global: every call adds to the same counter */
/* Paths from the top-left to the bottom-right of an r x c grid, moving only right or down. */
long long paths(int r, int c) {
calls++;
if (r == 1 || c == 1) return 1; /* base: a single row or column, one straight path */
return paths(r - 1, c) /* first move down: an (r-1) x c grid is left */
+ paths(r, c - 1); /* first move right: an r x (c-1) grid is left */
}
int main(void) {
int r, c;
scanf("%d %d", &r, &c);
printf("Paths: %lld\n", paths(r, c));
printf("Calls made: %lld\n", calls);
return 0;
}
Look at Test 4: 97,239 calls to produce 48,620. The same small grids are counted again and again. C9 shows the cure on Fibonacci.
Using only r == 1 && c == 1 as the base case. A call like paths(1, 3) then calls paths(0, 3), and from there the arguments go negative and never reach (1, 1), so the program recurses until it crashes. Ask "can either argument reach 0?" before you finish the base case.
C8 · Plus or minus every number to hit a target
Read n (1 ≤ n ≤ 15), then n positive integers, then a target. Put + or - in front of every number (all must be used, in order) so the total equals the target. If possible, print the first solution found, trying + before - at each number, as YES +1-2-3+4 = 0. Otherwise print NOT REACHABLE.
Input n; then n positive integers; then the target.
Output One line: YES, a space, the signed numbers written together, = and the target; or NOT REACHABLE.
4 1 2 3 4 0
YES +1-2-3+4 = 0
4 1 2 3 4 3
NOT REACHABLE
3 5 3 2 -4
YES -5+3-2 = -4
1 5 -5
YES -5 = -5
2 3 3 0
YES +3-3 = 0
Stuck? First move
Use the signature bool reach(int a[], char sign[], int n, int i, int sum, int target), where sum is the total of the signs chosen so far. Base case: i == n, meaning every number has a sign, so return sum == target. Smaller subproblems (two): record sign[i] = '+' and try reach(…, i + 1, sum + a[i], …). If that fails, record '-' and try sum - a[i].
Plan in plain words
- All numbers signed → success exactly when the sum equals the target.
- Otherwise: mark + and try the rest with sum + a[i]; if that works, report success.
- Else mark − and try with sum − a[i]; report whatever that gives.
- main: on success, print sign[i] and a[i] for each i.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <stdbool.h>
/* Try a sign for a[i]; sum is the value of the signs chosen so far. */
bool reach(int a[], char sign[], int n, int i, int sum, int target) {
if (i == n) return sum == target; /* base: every number has a sign */
sign[i] = '+';
if (reach(a, sign, n, i + 1, sum + a[i], target)) return true;
sign[i] = '-';
if (reach(a, sign, n, i + 1, sum - a[i], target)) return true;
return false; /* neither sign works from here */
}
int main(void) {
int n, target, a[20];
char sign[20];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
scanf("%d", &target);
if (reach(a, sign, n, 0, 0, target)) {
printf("YES ");
for (int i = 0; i < n; i++) printf("%c%d", sign[i], a[i]);
printf(" = %d\n", target);
} else {
printf("NOT REACHABLE\n");
}
return 0;
}
Why is 3 unreachable from 1 2 3 4 (Test 2)? Changing a +x to -x changes the total by 2x, an even number. All plus signs give 10, which is even, so every reachable total is even and 3 can never appear.
Returning true as soon as sum == target partway through. The spec says every number must be used, so the check belongs only in the i == n base case. (The sheet's Exact Change is the opposite: there you may skip coins.)
C9 · Fibonacci, naive vs remembered, with call counts
fib(0) = 0, fib(1) = 1, fib(n) = fib(n−1) + fib(n−2). Read n (0 ≤ n ≤ 40). Compute fib(n) twice: once with the plain recursive definition, and once with a version that stores each answer in an array memo[] the first time it is computed and looks it up after that. Count the calls each version makes (global counters), and print both results and both counts.
Input One integer n.
Output Two lines: fib(n) = x (naive) = y (memo), then Calls: naive p, memo q, with the real values.
10
fib(10) = 55 (naive) = 55 (memo) Calls: naive 177, memo 19
30
fib(30) = 832040 (naive) = 832040 (memo) Calls: naive 2692537, memo 59
1
fib(1) = 1 (naive) = 1 (memo) Calls: naive 1, memo 1
0
fib(0) = 0 (naive) = 0 (memo) Calls: naive 1, memo 1
20
fib(20) = 6765 (naive) = 6765 (memo) Calls: naive 21891, memo 39
Stuck? First move
Base case (both versions): n <= 1 → return n. Smaller subproblems: fib(n - 1) and fib(n - 2), added. The memo version has one extra early exit after the base case: if (memo[n] != -1) return memo[n];. It also saves the sum in memo[n] before returning it. Fill memo with −1 in main first, since −1 means "not known yet".
Plan in plain words
- naive(n): add 1 to the naive count; n ≤ 1 → n; else naive(n−1) + naive(n−2).
- memo(n): add 1 to the memo count; n ≤ 1 → n; already stored → return it; else compute memo(n−1) + memo(n−2), store it, return it.
- main: fill memo with −1, read n, run both, print.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
long long naiveCalls = 0, memoCalls = 0;
long long memo[91]; /* memo[k] = fib(k), or -1 if not known yet */
long long fibNaive(int n) {
naiveCalls++;
if (n <= 1) return n; /* base: fib(0) = 0, fib(1) = 1 */
return fibNaive(n - 1) + fibNaive(n - 2);
}
long long fibMemo(int n) {
memoCalls++;
if (n <= 1) return n; /* same base case */
if (memo[n] != -1) return memo[n]; /* already worked out: just look it up */
memo[n] = fibMemo(n - 1) + fibMemo(n - 2);
return memo[n];
}
int main(void) {
int n;
scanf("%d", &n);
for (int i = 0; i <= 90; i++) memo[i] = -1;
long long a = fibNaive(n);
long long b = fibMemo(n);
printf("fib(%d) = %lld (naive) = %lld (memo)\n", n, a, b);
printf("Calls: naive %lld, memo %lld\n", naiveCalls, memoCalls);
return 0;
}
Try n = 40 yourself (it is left out of the tests because it takes about a second): fib(40) = 102334155, with 331,160,281 naive calls against 79 memo calls. 79 is 2n − 1: each fib(k) is computed once, and every later request for it is a single lookup. This is the cure C7 was hinting at.
Using 0 to mean "not computed yet". fib(0) really is 0, so 0 can't serve as "unknown" for every n. Pick a value no answer can take, such as −1. Also, forgetting the memo[n] = … store gives the correct answer with no speed-up at all, because nothing is ever remembered.
Self-test before moving on
- For any problem on this page you can write the two lines Base case: … and Smaller subproblem: … within 3 minutes, without opening a box, and you can predict T2's output without running it.
- You can do B2 and B5 from the starter in under 20 minutes each, passing all 5 tests on the first full run, with no prompt and no debug print in the file.
- Optional, for the end-sem lab exam: you can do C2 or C6 in under 40 minutes, opening at most the First move box.
If the two lines don't come quickly, reread lesson §3 and do ten rounds of the dry-run drill, then come back. For the sheet's own problems (sum of digits, binary, flood fill, maze and so on), work through Lab 8 solutions after attempting each one.
← Stage 4 · StringsStage 6 · Mock evals →
Ask about your recursion, not for a solution. For example:
- "Here is my recursive C function for [task]. My base case is ___ and my smaller subproblem is ___. For input ___ it returns ___ but I expected ___. Without rewriting it, draw the call-stack table for this input and show me the first row where it goes wrong."
- "Give me one tracing question like this one [paste T2] with a different print order, and hide the answer until I reply."