CS U111 · Lab-eval ladder · Stage 1

Decisions and loops: twenty-one programs, four rungs

if/else, switch and one loop over N inputs: the two families that most of the instructor's real lab evals so far belong to. Every program reads silently and prints only the answer, the way Moodle VPL marks it, and every card has 5 test cases. Lab Sheet 4's own problems are worked on Lab 4 solutions.

Start here

What this stage covers. Lab Sheet 4 (Loops and iterative problem solving) plus the if/else and switch it builds on. Of the instructor's released evals, the if/else ones (2–5 numbers on one line, print one phrase) and the loop ones (N, then N values) match this stage directly.

What the rungs mean. A warms up one idea per program. A+ drills only the input shapes the evals use: flags on one line, N then N values, a header line then N values. B is calibrated against the instructor's real evals (lab-eval bank): same size (5–15 lines of logic), same input style, same edge cases in the tests, different problems. C is optional: longer lab-sheet-style programs with a twist.

Optional Rung 0. If loops still feel new, do the loops ladder first: 14 one-idea programs (print 1 to n, sum, factorial, digit count, read-until-zero, triangles). Teaching pages: operators & selection lesson and Lab 4 loops lesson; for revision, Lab 4 notes.

Time budget: about 2½–3 hours for A to B, the part that matters for evals. Rung A: 4 × 10 min. Rung A+: 3 × 10 min. Rung B: 5 × 15–20 min. Split it over two sittings (A and A+, then B). Rung C is extra: 9 × 20–40 min, about 4½ hours, only if time allows.

How to use it. Read the problem, then open a blank file and write the skeleton plus the scanf before anything else (Stage 0 drilled exactly that). Stuck for 5 minutes? Open "Stuck? First move" only. The plan comes next, and the solution only once you have a program that compiles, even a wrong one.

How these are marked

Every program here reads its input silently and prints only the answer, as VPL does: no prompt text such as Enter n, no debug prints. Each card has 5 tests; in the real evals each failed test costs 14%. Check one test with Copy input → run your program → paste its output → Check. Or press Download test script, save it next to your .c file and run sh s1-b1-tests.sh b1.c in Terminal to run all five at once (it compiles with cc -Wall -Wextra). Like VPL, the check ignores spacing and letter case, but every word and number must match. Full explanation: Stage 0 · how VPL marks you.

Syntax you need for this stage

FormMeaning
if (a) {…} else if (b) {…} else {…}Checked top to bottom; the first true branch runs, and the rest are skipped.
switch (op) { case '+': …; break; default: …; }Jump to the matching case. Without break it falls through into the next case.
for (int i = 1; i <= n; i++)Runs with i = 1, 2, …, n. Use when you know the count.
while (x != 0) { … }Repeat while the condition holds. It may run zero times.
do { … } while (choice != 0);Runs at least once (menus, validation). Note the ; at the end.
break; / continue;Leave the loop now / skip to the next iteration.
#include <stdbool.h>, bool ok = true;A flag: remembers "did this ever happen inside the loop?"
sum += x; count++; n /= 10;Shorthand for sum = sum + x, count = count + 1, n = n / 10.
d * d <= nSame as "d ≤ √n" for d ≥ 0, with no sqrt and no doubles.
k = (i <= n) ? i : 2 * n - i;Conditional expression: "if i ≤ n then i, else 2n − i", as one value.

Rung A · Warm-up

4 × 10 minutes. One idea each: an else-if ladder, a switch, a counting loop, a filtered range. These are the moves every eval contains somewhere, now written the VPL way: read silently, print only the answer.

A1 · Marks to grade

Rung A 10 min · Pattern: else-if ladder, validate first

Problem

Read a whole-number mark. Print the grade: 90–100 A, 80–89 B, 70–79 C, 60–69 D, 50–59 E, below 50 F. A mark outside 0–100 prints INVALID.

Input One integer: the mark.

Output One letter, or INVALID.

Test 1 · sample
85
B
Test 2
90
A
Test 3
49
F
Test 4
100
A
Test 5
101
INVALID
Stuck? First move

One int marks, one scanf and no printf before it. Then a single if / else if / else chain, with the invalid check as the first branch.

Plan in plain words
  1. Read the mark (silently).
  2. Below 0 or above 100 → INVALID.
  3. Otherwise ≥ 90 → A; otherwise ≥ 80 → B; … down to E; anything left → F.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int marks;
    scanf("%d", &marks);                /* no prompt: VPL types the input for you */

    if (marks < 0 || marks > 100)       /* reject bad input first */
        printf("INVALID\n");
    else if (marks >= 90)
        printf("A\n");
    else if (marks >= 80)               /* here we already know marks < 90 */
        printf("B\n");
    else if (marks >= 70)
        printf("C\n");
    else if (marks >= 60)
        printf("D\n");
    else if (marks >= 50)
        printf("E\n");
    else
        printf("F\n");
    return 0;
}
Classic trap

Putting the tests in the wrong order. If marks >= 50 comes first, 95 matches it and prints E, because only the first true branch runs. Tests 2–4 sit exactly on the boundaries, which is where hidden VPL tests always look.

A2 · A switch calculator

Rung A 10 min · Pattern: switch on a char · guard before dividing

Problem

Read an expression a op b: two integers with one of + - * / % between them, separated by spaces. For +, -, * and % print the result. For / print the quotient and the remainder, separated by a space. Division or % by zero prints DIVISION BY ZERO; any other operator prints UNKNOWN OPERATOR.

Input One line: a op b, e.g. 17 / 5.

Output One line: the result (two numbers for /), or one of the two messages.

Test 1 · sample
17 / 5
3 2
Test 2
12 * 4
48
Test 3
7 % 0
DIVISION BY ZERO
Test 4
3 ^ 2
UNKNOWN OPERATOR
Test 5
5 - 9
-4
Stuck? First move

int a, b; char op; and scanf("%d %c %d", &a, &op, &b); (the space before %c skips the space in the input). Then switch (op) with one case per symbol, in single quotes: case '+':.

Plan in plain words
  1. Read a, op, b.
  2. Switch on op: +, −, * print the result directly.
  3. / and %: if b is 0 print the division message, otherwise print the result.
  4. default: unknown operator.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a, b;
    char op;
    scanf("%d %c %d", &a, &op, &b);   /* space before %c skips the blank */

    switch (op) {
    case '+':
        printf("%d\n", a + b);
        break;
    case '-':
        printf("%d\n", a - b);
        break;
    case '*':
        printf("%d\n", a * b);
        break;
    case '/':
    case '%':                           /* both share the zero check */
        if (b == 0)
            printf("DIVISION BY ZERO\n");
        else if (op == '/')
            printf("%d %d\n", a / b, a % b);
        else
            printf("%d\n", a % b);
        break;
    default:
        printf("UNKNOWN OPERATOR\n");
    }
    return 0;
}
Classic trap

A missing break: case '+' then falls into case '-' and prints two numbers. On screen it looks like "the answer plus some junk"; to VPL it is a wrong output and the test fails. And scanf("%d%c%d", …) without the space reads the blank as the operator, so every test prints UNKNOWN OPERATOR.

A3 · Sum of squares, shown in full

Rung A 10 min · Pattern: counting loop + accumulator + separator

Problem

Read n. Print 1² + 2² + … + n² written out as a sum, then = and its total, with a space on each side of every + and = (for n = 4: 1 + 4 + 9 + 16 = 30). If n < 1 print NOTHING TO ADD.

Input One integer n.

Output One line: the written-out sum, or NOTHING TO ADD.

Test 1 · sample
4
1 + 4 + 9 + 16 = 30
Test 2
1
1 = 1
Test 3
0
NOTHING TO ADD
Test 4
2
1 + 4 = 5
Test 5
-3
NOTHING TO ADD
Stuck? First move

A for over i = 1..n and an int sum = 0. Ignore the plus signs at first: get 1 4 9 16 printing, then fix the separator.

Plan in plain words
  1. Read n; if below 1, print the message and stop.
  2. For i from 1 to n: if this isn't the first term, print " + "; print i × i; add it to sum.
  3. After the loop print " = " and sum.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n, sum = 0;
    scanf("%d", &n);

    if (n < 1) {
        printf("NOTHING TO ADD\n");
        return 0;
    }
    for (int i = 1; i <= n; i++) {
        if (i > 1)
            printf(" + ");              /* separator before every term but the first */
        printf("%d", i * i);
        sum += i * i;
    }
    printf(" = %d\n", sum);
    return 0;
}
Classic trap

Printing "%d + " every time gives 1 + 4 + 9 + 16 + = 30: one extra +, so the test fails. VPL ignores spaces but not symbols, so the spaces around + matter too: 1+4 is one word to VPL, 1 + 4 is three. "Separator before every item except the first" is a pattern you'll reuse for every list you print.

A4 · Multiples of k in a range

Rung A 10 min · Pattern: loop over a range + filter + count

Problem

Read a, b and k (a ≤ b, k > 0). On the first line print every multiple of k from a to b inclusive, separated by spaces, or NONE if there are none. On the second line print how many there are.

Input One line: a b k.

Output Line 1: the multiples, or NONE. Line 2: the count.

Test 1 · sample
10 50 7
14 21 28 35 42 49
6
Test 2
1 5 6
NONE
0
Test 3
7 7 7
7
1
Test 4
-6 6 3
-6 -3 0 3 6
5
Test 5
1 10 1
1 2 3 4 5 6 7 8 9 10
10
Stuck? First move

The loop runs over the numbers in the range: for (int i = a; i <= b; i++). Inside, a single if asks "does k divide i?", i.e. i % k == 0.

Plan in plain words
  1. For each i from a to b: if k divides i, print it followed by a space and add 1 to count.
  2. If count is still 0, print NONE.
  3. New line, then the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a, b, k, count = 0;
    scanf("%d %d %d", &a, &b, &k);

    for (int i = a; i <= b; i++) {
        if (i % k == 0) {
            printf("%d ", i);           /* a trailing space is fine: VPL compares words */
            count++;
        }
    }
    if (count == 0)
        printf("NONE");
    printf("\n%d\n", count);
    return 0;
}
Classic trap

Test 4 includes 0 and negatives: -6 % 3 and 0 % 3 are both 0, so they count. A version that starts the loop at 1 "because multiples are positive" fails it. And when a problem does not promise k > 0, guard it: i % 0 is undefined behaviour and crashes on a typical Linux grader.

Rung A+ · Input patterns

3 × 10 minutes. The logic here is deliberately tiny: the point is the three input shapes the real evals use. If you can read each of these correctly with no prompt, half of every eval is already done.

One fact all three rely on: scanf("%d", …) skips spaces and newlines before a number. So "N values on one line" and "N values one per line" are read by exactly the same loop.

A+1 · Rain check

Rung A+ 10 min · Pattern: flags + a number on one line, rules in priority order

Problem

Read three integers on one line: raining umbrella temp. raining and umbrella are flags (1 = yes, 0 = no); temp is in °C. Apply the rules in this order and print the first that fits:

  1. Raining and no umbrella: STAY IN (whatever the temperature).
  2. Otherwise, temperature below 10: TAKE A JACKET.
  3. Otherwise: GO OUT.

Input One line: raining umbrella temp.

Output One phrase from the list above.

Test 1 · sample
1 0 25
STAY IN
Test 2
1 1 25
GO OUT
Test 3
1 0 5
STAY IN
Test 4
0 0 10
GO OUT
Test 5
0 1 9
TAKE A JACKET
Stuck? First move

Three ints and one scanf("%d %d %d", …). Then copy the rule list straight into an if / else if / else, in the same order.

Plan in plain words
  1. Read the three numbers.
  2. If raining is 1 and umbrella is 0 → STAY IN.
  3. Else if temp < 10 → TAKE A JACKET.
  4. Else → GO OUT.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int raining, umbrella, temp;
    scanf("%d %d %d", &raining, &umbrella, &temp);

    if (raining == 1 && umbrella == 0)  /* rule 1 wins over everything */
        printf("STAY IN\n");
    else if (temp < 10)                 /* "below 10": 10 itself is not */
        printf("TAKE A JACKET\n");
    else
        printf("GO OUT\n");
    return 0;
}
Classic trap

Checking the temperature first. Test 3 (raining, no umbrella, 5 °C) then prints TAKE A JACKET, but rule 1 says STAY IN. When a problem says "in this order", the order of your ifs is the answer. Test 4 checks < 10 against <= 10.

A+2 · Positives only

Rung A+ 10 min · Pattern: N, then N values; count and total in one pass

Problem

Read N, then N integers. Print how many of them are positive (greater than 0) and the sum of those positive values.

Input First line: N (0 or more). Then N integers, separated by spaces or newlines.

Output Two integers on one line: count sum.

Test 1 · sample
5
3 -1 0 4 -7
2 7
Test 2
0
0 0
Test 3
1
-5
0 0
Test 4
1
8
1 8
Test 5
4
0 0 0 0
0 0
Stuck? First move

Read N first, on its own. Then for (int i = 0; i < n; i++) { scanf("%d", &x); … }: one value per pass, into one variable. No array needed: each value is used once and forgotten.

Plan in plain words
  1. count = 0, sum = 0.
  2. Read N.
  3. N times: read x; if x > 0, add 1 to count and x to sum.
  4. Print count and sum.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n, x, count = 0, sum = 0;
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {       /* exactly n passes; none when n is 0 */
        scanf("%d", &x);
        if (x > 0) {                    /* 0 is not positive */
            count++;
            sum += x;
        }
    }
    printf("%d %d\n", count, sum);
    return 0;
}
Classic trap

Looping i = 1; i < n (or i = 0; i <= n): one value too few, or one too many. With one too many, scanf finds no more input and leaves x holding the last value, which then counts twice (Test 4 would print 2 16). Test 2, N = 0, must print 0 0, not crash and not print nothing.

A+3 · Above the limit

Rung A+ 10 min · Pattern: header line limit N, then N values

Problem

The first line holds two integers: a limit L and a count N. Then come N integers. Print how many of them are strictly greater than L.

Input First line: L N. Then N integers (if N is 0 there are none).

Output One integer: the count.

Test 1 · sample
10 5
4 11 10 25 9
2
Test 2
10 0
0
Test 3
-1 3
-1 0 -5
1
Test 4
0 1
1
1
Test 5
5 4
5 5 5 5
0
Stuck? First move

scanf("%d %d", &limit, &n);, in the order the problem lists them. After that it is A+2's loop again.

Plan in plain words
  1. Read limit, then N.
  2. N times: read x; if x > limit, count it.
  3. Print the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int limit, n, x, above = 0;
    scanf("%d %d", &limit, &n);         /* header: same order as the problem */

    for (int i = 0; i < n; i++) {
        scanf("%d", &x);
        if (x > limit)                  /* strictly greater: equal does not count */
            above++;
    }
    printf("%d\n", above);
    return 0;
}
Classic trap

Swapping the header: scanf("%d %d", &n, &limit). For the sample it then tries to read 10 values with limit 5, runs out of input after 5 of them, and prints 9 (real run). Four of the five tests fail. The header's order is part of the problem; read it twice. Test 5 (all equal to the limit) checks > against >=.

Rung B · VPL level

5 × 15–20 minutes. Built like the instructor's real evals (lab-eval bank): 5–15 lines of logic, the same input shapes, the same kind of hidden tests (boundaries, rule order, N = 0, N = 1, all-equal values). Two are if/else problems, three are one loop over N inputs with no arrays. Set a timer, write from a blank file, and run the test script before opening anything.

B1 · Parcel routing

Rung B VPL format 15 min · Family: if/else · Pattern: rule priority, boundaries on both sides

Problem

A courier routes each parcel by its weight (a positive whole number of kg), a fragile flag (1 = fragile, 0 = not) and an express flag (1 = express, 0 = not). Rules, in priority order: a parcel gets the first rule that fits.

  1. Weight above 30: OVERWEIGHT, whatever the flags say.
  2. Otherwise, fragile: HAND CARRY, even if it is express.
  3. Otherwise, express and weight 5 or less: DRONE.
  4. Everything else: VAN.

Input Three space-separated integers: weight fragile express.

Output One of OVERWEIGHT, HAND CARRY, DRONE, VAN, exactly as worded.

Test 1 · sample
4 1 1
HAND CARRY
Test 2
31 1 1
OVERWEIGHT
Test 3
30 0 1
VAN
Test 4
5 0 1
DRONE
Test 5
5 0 0
VAN
Stuck? First move

The rule list is the else-if chain: four rules, four branches, in the same order. Write the branches with the printed words first, then fill in each condition.

Plan in plain words
  1. Read weight, fragile, express.
  2. weight > 30 → OVERWEIGHT.
  3. else fragile is 1 → HAND CARRY.
  4. else express is 1 and weight ≤ 5 → DRONE.
  5. else → VAN.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int weight, fragile, express;
    scanf("%d %d %d", &weight, &fragile, &express);

    if (weight > 30)                        /* "above 30": 30 itself is fine */
        printf("OVERWEIGHT\n");
    else if (fragile == 1)                  /* beats express */
        printf("HAND CARRY\n");
    else if (express == 1 && weight <= 5)   /* both must hold */
        printf("DRONE\n");
    else
        printf("VAN\n");
    return 0;
}
Classic trap

Writing the rules as separate ifs instead of one else-if chain. Then the sample (4 kg, fragile, express) prints HAND CARRY and DRONE: two answers, and VPL fails the test. Tests 3–5 are the boundaries: 30 is not "above 30", 5 is "5 or less", and DRONE needs express too.

B2 · Truck inspection

Rung B VPL format 15 min · Family: if/else · Pattern: print every reason that applies, in order

Problem

A checkpoint inspects a truck. Read its load (kg), the legal load limit (kg), its tyre pressure (psi) and a lights flag (1 = lights working, 0 = broken). The truck passes only if the load is at most the limit, the tyre pressure is from 30 to 40 inclusive, and the lights work.

If it passes, print PASS. Otherwise print FAIL followed by every reason that applies, space-separated, in this order: OVERLOAD (load above the limit), TYRES (pressure below 30 or above 40), LIGHTS (lights broken).

Input Four space-separated integers: load limit pressure lights.

Output PASS, or FAIL followed by the reasons, on one line.

Test 1 · sample
1200 1000 35 0
FAIL OVERLOAD LIGHTS
Test 2
1000 1000 30 1
PASS
Test 3
1001 1000 40 1
FAIL OVERLOAD
Test 4
500 1000 29 1
FAIL TYRES
Test 5
2000 1000 41 0
FAIL OVERLOAD TYRES LIGHTS
Stuck? First move

Two parts. First decide PASS or FAIL with one combined condition. Then, in the FAIL branch only, three separate ifs (not else-if), one per reason, each printing a space and its word.

Plan in plain words
  1. Read the four numbers.
  2. If load ≤ limit and 30 ≤ pressure ≤ 40 and lights is 1 → PASS.
  3. Otherwise print FAIL; then if load > limit print OVERLOAD; if pressure < 30 or > 40 print TYRES; if lights is 0 print LIGHTS.
  4. End the line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int load, limit, pressure, lights;
    scanf("%d %d %d %d", &load, &limit, &pressure, &lights);

    if (load <= limit && pressure >= 30 && pressure <= 40 && lights == 1) {
        printf("PASS\n");
    } else {
        printf("FAIL");
        if (load > limit)                   /* separate ifs: every reason is checked */
            printf(" OVERLOAD");
        if (pressure < 30 || pressure > 40)
            printf(" TYRES");
        if (lights == 0)
            printf(" LIGHTS");
        printf("\n");
    }
    return 0;
}
Classic trap

Using else-if for the reasons: only the first one prints, so Tests 1 and 5 fail. "Every reason that applies" always means independent ifs. Second trap: writing the range as 30 <= pressure <= 40. Clang on the Mac refuses it ("chained comparison" error); a compiler that accepts it reads (30 <= pressure) <= 40, which is 0 or 1, always ≤ 40, so always true, and Test 4 prints PASS. Use pressure >= 30 && pressure <= 40.

B3 · Record lows

Rung B VPL format 15 min · Family: one loop over N inputs · Pattern: running minimum + a counter of new records

Problem

Read N, then N daily temperatures (integers, may be negative). A day is a record low if its temperature is strictly lower than on every earlier day; the first day always counts as a record. Print the number of record lows and the lowest temperature. If N is 0, print NO DATA.

Input First line: N. Then N integers, separated by spaces or newlines.

Output Two integers on one line, records lowest, or NO DATA.

Test 1 · sample
6
30 28 28 31 25 26
3 25
Test 2
0
NO DATA
Test 3
1
-4
1 -4
Test 4
4
5 5 5 5
1 5
Test 5
5
-1 -2 -3 -4 -5
5 -5
Stuck? First move

"Lower than every earlier day" is the same as "lower than the lowest so far". So keep one variable low (the lowest so far) and one counter. The only question is what low starts as: the first day has no earlier days, so it sets low instead of being compared.

Plan in plain words
  1. Read N; if it is 0 print NO DATA and stop.
  2. N times: read t. If it is the first day, or t < low: it is a record, so low = t and count it.
  3. Print the count and low.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n, t, low = 0, records = 0;
    scanf("%d", &n);
    if (n == 0) {                       /* no days: nothing to report */
        printf("NO DATA\n");
        return 0;
    }
    for (int i = 0; i < n; i++) {
        scanf("%d", &t);
        if (i == 0 || t < low) {        /* first day, or strictly below the lowest so far */
            low = t;
            records++;
        }
    }
    printf("%d %d\n", records, low);
    return 0;
}
Classic trap

Starting low = 0 and skipping the "first day" case. For warm days nothing is ever below 0, so the sample prints 0 0. Starting low at a "very big number" like 9999 works only until a test has bigger values; taking the first value is always right. Test 4 (all equal) checks < against <=: an equal day is not a new record.

B4 · Longest repeat

Rung B VPL format 20 min · Family: one loop over N inputs · Pattern: current run vs best run, compare with the previous value

Problem

A die is rolled N times. Read N, then the N results (each 1–6). Find the longest run of the same face in a row. Print its length and the face. If two runs are equally long, report the one that came first. If N is 0, print NO ROLLS.

Input First line: N. Then N integers from 1 to 6.

Output Two integers on one line, length face, or NO ROLLS.

Test 1 · sample
8
3 3 5 5 5 2 2 6
3 5
Test 2
1
4
1 4
Test 3
0
NO ROLLS
Test 4
6
1 1 2 2 3 3
2 1
Test 5
5
6 6 6 6 6
5 6
Stuck? First move

Four variables: prev (last roll), run (length of the run that is still going), best and bestFace (the longest run seen so far). Each new roll either continues the run (same as prev) or starts a new run of length 1.

Plan in plain words
  1. Read N; if 0 print NO ROLLS and stop.
  2. N times: read x. If it is not the first roll and x equals prev, run goes up by 1; otherwise run = 1.
  3. Right away, if run > best: best = run and bestFace = x.
  4. prev = x.
  5. Print best and bestFace.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n, x, prev = 0, run = 0, best = 0, bestFace = 0;
    scanf("%d", &n);
    if (n == 0) {
        printf("NO ROLLS\n");
        return 0;
    }
    for (int i = 0; i < n; i++) {
        scanf("%d", &x);
        if (i > 0 && x == prev)         /* same face again: the run continues */
            run++;
        else
            run = 1;                    /* a new run starts with this roll */
        if (run > best) {               /* checked every roll, not only when a run ends */
            best = run;
            bestFace = x;               /* strict >: a tie keeps the earlier run */
        }
        prev = x;
    }
    printf("%d %d\n", best, bestFace);
    return 0;
}
Classic trap

Updating best only when a run breaks (inside the else). The last run never breaks, so Test 5 (all sixes) prints 0 0 instead of 5 6 (real run), and so does Test 2. Compare after every roll. Using >= instead of > reports the last of the tied runs: Test 4 then prints 2 3.

B5 · Lab latecomers

Rung B VPL format 20 min · Family: one loop over N inputs · Pattern: skip some values, count two things, average with a zero guard

Problem

For each of N students the lab records how many minutes late they arrived: 0 means on time, a positive number means late, and -1 means absent. Absent students are skipped entirely. Print the number of students present, the number who were late, and the average lateness of the late students to 2 decimal places. If nobody was late, print the average as 0.00.

Input First line: N. Then N integers, each -1 or 0 or more.

Output Three values on one line: present late average.

Test 1 · sample
6
0 5 -1 12 0 -1
4 2 8.50
Test 2
0
0 0 0.00
Test 3
3
-1 -1 -1
0 0 0.00
Test 4
3
0 0 0
3 0 0.00
Test 5
3
1 2 2
3 3 1.67
Stuck? First move

Three accumulators: present, late, and total (minutes of the late students only). Inside the loop, deal with -1 first and continue past it, so nothing below it in the loop ever sees an absent student.

Plan in plain words
  1. Read N. Then N times: read m.
  2. If m is −1, skip to the next student.
  3. Otherwise count them present; if m > 0, also count them late and add m to total.
  4. After the loop: if late is 0, the average is 0.00; otherwise it is total ÷ late, as a real number.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n, m, present = 0, late = 0, total = 0;
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        scanf("%d", &m);
        if (m == -1)
            continue;                   /* absent: skip entirely */
        present++;
        if (m > 0) {
            late++;
            total += m;
        }
    }
    if (late == 0)                      /* guard: never divide by zero */
        printf("%d %d 0.00\n", present, late);
    else
        printf("%d %d %.2f\n", present, late, (double)total / late);
    return 0;
}

(double)total turns the total into a real number before the division, so the division keeps its decimals: 5 ÷ 3 = 1.666…, which %.2f rounds to 1.67.

Classic trap

double avg = total / late; still divides two ints first (the decimals are gone before the result is stored), so Test 5 prints 1.00. Cast one side, as the solution does. And with no guard, Tests 2–4 divide by zero. With the (double) cast the real run printed nan for all three: three failed tests. Integer division by zero is worse: undefined behaviour, which crashes on a typical Linux grader. Counting absent students as present (forgetting the skip) fails Test 3.

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. 20–40 minutes each. C1–C5 are at Lab Sheet 4's practice-problem level, C6–C9 at its challenge and bonus level. They are in VPL format too: silent input, only the answer printed, 5 tests each.

C1 · Primes in a range

Rung C 20 min · Pattern: outer loop over candidates, inner loop with a flag

Problem

Read a and b (a ≤ b; a may be 0, 1 or negative). On the first line print every prime from a to b inclusive, separated by spaces, or NONE. On the second line print how many there are.

Input One line: a b.

Output Line 1: the primes, or NONE. Line 2: the count.

Same check as Lab Sheet 4's worked example §12 (prime check with a flag), wrapped in a loop over a range.

Test 1 · sample
10 30
11 13 17 19 23 29
6
Test 2
1 10
2 3 5 7
4
Test 3
24 28
NONE
0
Test 4
-5 2
2
1
Test 5
97 100
97
1
Stuck? First move

Write the single-number prime check first (it's on the sheet, §12) for a fixed n. Then put for (int n = a; n <= b; n++) { … } around it. The flag must be reset inside the outer loop, once per candidate.

Plan in plain words
  1. For each n from a to b:
  2. Assume prime if n ≥ 2, otherwise not.
  3. Try d = 2, 3, … while d × d ≤ n and it still looks prime; any d that divides n clears the flag.
  4. If still prime: print n and count it.
  5. After the outer loop: NONE if count is 0, then a new line and the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <stdbool.h>

int main(void) {
    int a, b, count = 0;
    scanf("%d %d", &a, &b);

    for (int n = a; n <= b; n++) {          /* outer loop: every candidate */
        bool isPrime = (n >= 2);            /* 0, 1 and negatives are not prime */
        for (int d = 2; d * d <= n && isPrime; d++) {   /* inner: try divisors */
            if (n % d == 0)
                isPrime = false;
        }
        if (isPrime) {
            printf("%d ", n);
            count++;
        }
    }
    if (count == 0)
        printf("NONE");
    printf("\n%d\n", count);
    return 0;
}
Classic trap

Starting the flag at true for every n: the inner loop never runs for n = 1 (or 0, or negatives), so they are reported as prime. Test 2 then prints 1 2 3 5 7 and count 5. Ranges starting at 1 or below are exactly the edge case a hidden test will try.

C2 · Digit report

Rung C 20 min · Pattern: digit peel · running max/min · flag

Problem

Read a non-negative integer. In one pass over its digits, find the number of digits, the largest digit, the smallest digit, and whether the digits are strictly increasing from left to right. Print these four on one line: three numbers, then YES or NO.

Input One non-negative integer.

Output One line: digits largest smallest YES|NO.

Same peel loop as Lab Sheet 4's Problem 1 (digits, sum, reverse in one loop), with different questions asked of each digit.

Test 1 · sample
1479
4 9 1 YES
Test 2
3053
4 5 0 NO
Test 3
0
1 0 0 YES
Test 4
7
1 7 7 YES
Test 5
1123
4 3 1 NO
Stuck? First move

The loop is the digit peel on a copy: d = t % 10; … t /= 10;. Digits arrive right to left (9, 7, 4, 1 for 1479). So "increasing left to right" means "each new digit must be smaller than the one before it". Keep the previous digit in a variable prev.

Plan in plain words
  1. Start: digits = 0, largest = 0, smallest = 9, prev = 10 (bigger than any digit), increasing = true.
  2. Repeat at least once: take the last digit d, count it, update largest and smallest; if d ≥ prev, increasing becomes false; prev = d; drop the digit.
  3. Stop when the copy reaches 0.
  4. Print the four results.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <stdbool.h>

int main(void) {
    int n, digits = 0, largest = 0, smallest = 9;
    int prev = 10;                  /* bigger than any digit */
    bool increasing = true;
    scanf("%d", &n);

    int t = n;
    do {                            /* do-while: 0 still has one digit */
        int d = t % 10;             /* digits arrive right to left */
        digits++;
        if (d > largest) largest = d;
        if (d < smallest) smallest = d;
        if (d >= prev) increasing = false;  /* right-to-left must keep falling */
        prev = d;
        t /= 10;
    } while (t != 0);

    printf("%d %d %d %s\n", digits, largest, smallest, increasing ? "YES" : "NO");
    return 0;
}
Classic trap

A while (t != 0) loop never runs for input 0, so it reports 0 digits and Test 3 fails. This is the sheet's own "zero iterations" test case (§19). do … while runs the body once first, which is exactly right here. Test 5 (a repeated 1) checks that "strictly" uses >= in the right-to-left test.

C3 · Number pyramid

Rung C 20 min · Pattern: nested loops, three inner loops per row

Problem

Read the number of rows n (1–9; otherwise print INVALID). Print a centred pyramid where row i climbs 1…i and comes back down. For n = 4:

   1
  121
 12321
1234321

Input One integer n.

Output n rows, or INVALID.

Lab Sheet 4's §17 triangle and Problem 7 patterns, with centring and a second inner loop running downwards.

Test 1 · sample
4
   1
  121
 12321
1234321
Test 2
1
1
Test 3
0
INVALID
Test 4
10
INVALID
Test 5
9
        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321

One honest limit: VPL ignores spacing, so these tests check the digits on each row but cannot see the centring. Check the shape by eye.

Stuck? First move

Outer loop: one pass per row, i = 1..n. Then make a table for n = 4 with columns row · spaces · climbing digits · falling digits: (1, 3, "1", ""), (2, 2, "12", "1"), (3, 1, "123", "21"), (4, 0, "1234", "321"). Each column becomes one inner loop.

Plan in plain words
  1. Validate n.
  2. For each row i: print n − i spaces; print 1 up to i; print i − 1 down to 1; end the line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);
    if (n < 1 || n > 9) {
        printf("INVALID\n");
        return 0;
    }

    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= n - i; s++)    /* leading spaces */
            printf(" ");
        for (int j = 1; j <= i; j++)        /* climb: 1 2 ... i */
            printf("%d", j);
        for (int j = i - 1; j >= 1; j--)    /* descend: i-1 ... 1 */
            printf("%d", j);
        printf("\n");
    }
    return 0;
}
Classic trap

Forgetting the printf("\n") after the inner loops (everything comes out as one long number, which fails), or putting it inside an inner loop (one digit per line, which also fails). The newline belongs to the row, so it goes in the outer loop.

C4 · Wallet menu with validation

Rung C 25 min · Pattern: do-while menu + switch + guarded updates

Problem

A wallet starts at 0. The program reads menu choices until it reads 0: 1 = deposit, 2 = withdraw (each followed by an amount), 3 = show balance. No menu is printed; the choices simply arrive on the input. Print only these results:

  • A successful deposit or withdrawal prints nothing.
  • An amount of 0 or less (for 1 or 2) prints INVALID AMOUNT.
  • A withdrawal larger than the balance prints INSUFFICIENT and the current balance.
  • Choice 3 prints the balance.
  • Any other choice prints INVALID CHOICE.
  • Choice 0 prints FINAL and the balance, and ends the program.

Input A sequence of integers: choices, each 1 or 2 followed by its amount, ending with 0.

Output One line per result above.

Lab Sheet 4's Problem 4 (PIN, do-while) and Problem 7 (switch menu) combined, with state that survives across iterations.

Test 1 · sample
1 500 2 800 2 200 3 7 0
INSUFFICIENT 500
300
INVALID CHOICE
FINAL 300
Test 2
0
FINAL 0
Test 3
1 -50 1 0 3 0
INVALID AMOUNT
INVALID AMOUNT
0
FINAL 0
Test 4
1 100 2 100 3 0
0
FINAL 0
Test 5
2 1 9 1 30 2 31 0
INSUFFICIENT 0
INVALID CHOICE
INSUFFICIENT 30
FINAL 30
Stuck? First move

int choice, amount, balance = 0; Then the shape: do { read choice; switch (choice) { … } } while (choice != 0);. Write that shell with empty cases, compile it, and check that input 0 prints FINAL 0. Then fill one case at a time.

Plan in plain words
  1. Repeat: read the choice.
  2. 1: read amount; if ≤ 0 reject, else add.
  3. 2: read amount; if ≤ 0 reject; else if more than balance print INSUFFICIENT and the balance; else subtract.
  4. 3: print the balance. 0: print FINAL and the balance. Anything else: INVALID CHOICE.
  5. Until the choice is 0.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int choice, amount, balance = 0;    /* before the loop, or it resets every pass */

    do {
        scanf("%d", &choice);           /* no menu text: VPL only wants results */
        switch (choice) {
        case 1:
            scanf("%d", &amount);
            if (amount <= 0)
                printf("INVALID AMOUNT\n");
            else
                balance += amount;
            break;
        case 2:
            scanf("%d", &amount);
            if (amount <= 0)
                printf("INVALID AMOUNT\n");
            else if (amount > balance)
                printf("INSUFFICIENT %d\n", balance);
            else
                balance -= amount;
            break;
        case 3:
            printf("%d\n", balance);
            break;
        case 0:
            printf("FINAL %d\n", balance);
            break;
        default:
            printf("INVALID CHOICE\n");
        }
    } while (choice != 0);
    return 0;
}
Classic trap

Keeping the interactive habits: printing the menu or "Amount: " each time. Every one of those words is extra output, so all five tests fail even though the arithmetic is right. Also: writing it with while (choice != 0) at the top, where choice hasn't been read yet and holds garbage. do-while exists for "do it at least once".

C5 · Statistics until zero

Rung C 20 min · Pattern: sentinel loop · running max/min · average with a cast

Problem

Read integers until a 0 arrives (0 itself is not data). Print, on one line, the count, the sum, the average to 2 decimal places, the maximum and the minimum. If the very first number is 0, print NO NUMBERS.

Input Integers separated by spaces or newlines, ending with 0.

Output One line: count sum average max min, or NO NUMBERS.

Lab Sheet 4's "use a while loop when the number of iterations is unknown" (§7), with a running max like Problem 5's bounds.

Test 1 · sample
5 -2 9 3 0
4 15 3.75 9 -2
Test 2
-4 -7 0
2 -11 -5.50 -4 -7
Test 3
0
NO NUMBERS
Test 4
8 0
1 8 8.00 8 8
Test 5
1 2 0
2 3 1.50 2 1
Stuck? First move

The sentinel shape is: read once before the loop; while (x != 0); at the end of the body, read again. Variables: count, sum, max, min.

Plan in plain words
  1. Read x.
  2. While x isn't 0: if it's the first number, set max and min to it; update max/min; add to sum; count it; read the next x.
  3. After: if count is 0 print NO NUMBERS, else print count, sum, sum ÷ count as a real number, max, min.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int x, count = 0, sum = 0, max = 0, min = 0;

    scanf("%d", &x);
    while (x != 0) {
        if (count == 0) {           /* first number: it is both max and min */
            max = x;
            min = x;
        }
        if (x > max) max = x;
        if (x < min) min = x;
        sum += x;
        count++;
        scanf("%d", &x);            /* read the next one, or the loop never ends */
    }

    if (count == 0)
        printf("NO NUMBERS\n");
    else
        printf("%d %d %.2f %d %d\n", count, sum, (double)sum / count, max, min);
    return 0;
}
Classic trap

Starting max = 0 and never resetting it from the first number. For all-negative input (Test 2) the max comes out as 0, a value that was never even data. Start max and min at the first value. Also, sum / count without the cast is integer division: Test 5 would print 1.00 instead of 1.50.

C6 · Hollow diamond

Rung C 30 min · Pattern: rows that grow then shrink · edge characters vs gap

Problem

Read a size n. If n ≥ 1, print a hollow diamond of stars whose middle row is 2n − 1 characters wide; otherwise print INVALID. For n = 4:

   *
  * *
 *   *
*     *
 *   *
  * *
   *

Input One integer n.

Output 2n − 1 rows of the diamond, or INVALID.

Test 1 · sample
4
   *
  * *
 *   *
*     *
 *   *
  * *
   *
Test 2
2
 *
* *
 *
Test 3
1
*
Test 4
0
INVALID
Test 5
3
  *
 * *
*   *
 * *
  *

As with C3, VPL-style checking ignores spacing: these tests count the stars on each row, not where they sit. Check the shape by eye.

Stuck? First move

Number the rows 1 to 2n − 1 and write, for n = 4, the row's level k (1 2 3 4 3 2 1), its outside spaces (3 2 1 0 1 2 3) and its inside gap (–, 1, 3, 5, …). Find each one as a formula in k. The only special row is k = 1, which has a single star.

Plan in plain words
  1. Validate n.
  2. For each row i from 1 to 2n − 1: k = i on the way down to the middle, 2n − i after it.
  3. Print n − k spaces, then a star.
  4. If k > 1: print 2k − 3 spaces and a second star.
  5. End the line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n;
    if (scanf("%d", &n) != 1 || n < 1) {
        printf("INVALID\n");
        return 0;
    }

    for (int i = 1; i <= 2 * n - 1; i++) {
        int k = (i <= n) ? i : 2 * n - i;   /* k = 1, 2, ..., n, ..., 2, 1 */

        for (int s = 1; s <= n - k; s++)    /* outside spaces */
            printf(" ");
        printf("*");                        /* left edge */
        if (k > 1) {
            for (int s = 1; s <= 2 * k - 3; s++)   /* inside gap */
                printf(" ");
            printf("*");                    /* right edge */
        }
        printf("\n");
    }
    return 0;
}
Unpack: where does 2k − 3 come from?

Row k spans 2k − 1 characters from edge to edge (1, 3, 5, 7 for k = 1..4). Take away the two edge stars and 2k − 3 spaces are left between them. For k = 1 that would be −1, which is why that row is handled separately.

Classic trap

Printing two stars on the top and bottom rows. Tests 2 and 3 (n = 2 and n = 1) catch it: the smallest sizes are where pattern formulas break.

C7 · Perfect and strong numbers in a range

Rung C 40 min · Pattern: range loop × two different inner computations · √n speed-up

Problem

Read a range a, b. If it is not 1 ≤ a ≤ b, print INVALID. Otherwise list the perfect numbers in it (the sum of the proper divisors, i.e. those less than the number, equals the number: 6 = 1 + 2 + 3) and the strong numbers (the sum of the factorials of the digits equals the number: 145 = 1! + 4! + 5!). It must handle b = 100000 within a second.

Input One line: a b.

Output Line 1: PERFECT then the perfect numbers, or PERFECT NONE. Line 2: STRONG then the strong numbers, or STRONG NONE. Or just INVALID.

Lab Sheet 4's Bonus 3 asks for perfect numbers; this adds a second, digit-based property and a speed requirement.

Test 1 · sample
1 10000
PERFECT 6 28 496 8128
STRONG 1 2 145
Test 2
1 100000
PERFECT 6 28 496 8128
STRONG 1 2 145 40585
Test 3
50 10
INVALID
Test 4
30 100
PERFECT NONE
STRONG NONE
Test 5
1 30
PERFECT 6 28
STRONG 1 2
Stuck? First move

Do it as two separate passes over the range, one per property, each with its own inner loop. Perfect: an inner loop over divisors d. Strong: Stage 1's digit peel, with a tiny factorial loop inside it for each digit. Get the slow version right first (divisors d = 1 to n − 1), then speed it up.

Plan in plain words
  1. Validate the range.
  2. Perfect pass: for each n, add up its divisors below n. Speed-up: divisors come in pairs (d, n ÷ d), so only try d while d × d ≤ n and add both, but not n itself, and not the same divisor twice when d × d = n. Print n if the sum equals n and n > 1.
  3. Strong pass: for each n, peel digits; for each digit compute its factorial and add it. Print n if the total equals n.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a, b, found;
    if (scanf("%d %d", &a, &b) != 2 || a < 1 || a > b) {
        printf("INVALID\n");
        return 0;
    }

    printf("PERFECT");
    found = 0;
    for (int n = a; n <= b; n++) {
        int sum = 0;                        /* sum of proper divisors */
        for (int d = 1; d * d <= n; d++) {
            if (n % d == 0) {
                sum += d;                   /* d divides n ... */
                int pair = n / d;           /* ... and so does n / d */
                if (pair != d && pair != n)
                    sum += pair;
            }
        }
        if (n > 1 && sum == n) {            /* 1 has no proper divisors but 1 */
            printf(" %d", n);
            found++;
        }
    }
    if (found == 0)
        printf(" NONE");
    printf("\n");

    printf("STRONG");
    found = 0;
    for (int n = a; n <= b; n++) {
        int sum = 0, t = n;
        while (t > 0) {
            int d = t % 10, fact = 1;
            for (int i = 2; i <= d; i++)    /* d! */
                fact *= i;
            sum += fact;
            t /= 10;
        }
        if (sum == n) {
            printf(" %d", n);
            found++;
        }
    }
    if (found == 0)
        printf(" NONE");
    printf("\n");
    return 0;
}

The speed-up matters. Measured on the Mac for a = 1, b = 100000: the simple d < n divisor loop took about 3 seconds; the d * d <= n version took 0.03 s. VPL stops a program that runs too long, which counts as a failed test.

Classic trap

Reporting 1 as perfect. 1 has no proper divisors (nothing smaller than 1 divides it), but the paired loop adds d = 1 anyway. Without the n > 1 test, Test 5 prints PERFECT 1 6 28.

C8 · Number to Roman numerals

Rung C 30 min · Pattern: greedy loop: take the biggest piece that fits

Problem

Read an integer and print it in Roman numerals. Only 1–3999 can be written; anything else prints INVALID. Symbols: M 1000, D 500, C 100, L 50, X 10, V 5, I 1, with the subtractive pairs CM 900, CD 400, XC 90, XL 40, IX 9, IV 4.

Input One integer.

Output The numeral, or INVALID.

Test 1 · sample
1994
MCMXCIV
Test 2
3999
MMMCMXCIX
Test 3
4
IV
Test 4
4000
INVALID
Test 5
1
I
Stuck? First move

Do 1994 by hand and watch what you do: "the biggest thing that fits is 1000 → M, 994 left; biggest that fits is 900 → CM, 94 left; 90 → XC, 4 left; 4 → IV." That's one loop, while (n > 0), with an else-if ladder from 1000 down to 1 inside it.

Plan in plain words
  1. Validate.
  2. While n > 0: find the largest of the 13 values (1000, 900, 500, …, 4, 1) that is ≤ n; print its symbol; subtract it.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int n;
    if (scanf("%d", &n) != 1 || n < 1 || n > 3999) {
        printf("INVALID\n");
        return 0;
    }

    while (n > 0) {                 /* each pass: print the biggest piece that fits */
        if (n >= 1000)      { printf("M");  n -= 1000; }
        else if (n >= 900)  { printf("CM"); n -= 900; }
        else if (n >= 500)  { printf("D");  n -= 500; }
        else if (n >= 400)  { printf("CD"); n -= 400; }
        else if (n >= 100)  { printf("C");  n -= 100; }
        else if (n >= 90)   { printf("XC"); n -= 90; }
        else if (n >= 50)   { printf("L");  n -= 50; }
        else if (n >= 40)   { printf("XL"); n -= 40; }
        else if (n >= 10)   { printf("X");  n -= 10; }
        else if (n >= 9)    { printf("IX"); n -= 9; }
        else if (n >= 5)    { printf("V");  n -= 5; }
        else if (n >= 4)    { printf("IV"); n -= 4; }
        else                { printf("I");  n -= 1; }
    }
    printf("\n");
    return 0;
}
Classic trap

Leaving out the subtractive pairs (or testing 500 before 900). Then 1994 comes out as MDCCCCLXXXXIIII. The ladder must list all 13 values strictly from largest to smallest. Note the output is one word: printing a space after each symbol would split it into several words and fail every test.

C9 · Loan payoff simulation

Rung C 40 min · Pattern: while-until simulation · detect "never ends" before looping

Problem

Read a loan amount, an annual interest rate in %, and a fixed monthly payment. Each month, interest of (rate ÷ 12)% is added to the balance, then the payment is made (in the last month, only what's left). Print how many months it takes, then the total paid and the interest part of it. If the payment doesn't even cover the first month's interest, print NEVER. If the amount or payment is 0 or less, or the rate is negative, print INVALID (a rate of 0 is allowed).

Input One line: amount rate payment (real numbers).

Output Line 1: the number of months. Line 2: total interest, both to 2 decimal places. Or NEVER, or INVALID.

The same "loop until a condition, not a count" as Lab Sheet 4's Problem 5 (smart guesser), with the infinite-loop case caught in advance.

Test 1 · sample
100000 12 10000
11
105898.49 5898.49
Test 2
500 12 1000
1
505.00 5.00
Test 3
5000 12 50
NEVER
Test 4
1000 0 300
4
1000.00 0.00
Test 5
0 5 100
INVALID
Stuck? First move

The state that changes each month is balance, months and totalPaid, all double except months. Ask the sheet's three loop questions (the Debugging Habit box in §10): starting state? stop when? how does each pass move towards stopping? The last answer tells you when the loop would never stop.

Plan in plain words
  1. Read and validate.
  2. If payment ≤ balance × rate ÷ 1200 (the first month's interest), print NEVER and stop.
  3. Remember the original loan.
  4. While the balance is more than half a paisa: add the interest; pay the smaller of payment and balance; add that to totalPaid; count the month.
  5. Print months, then totalPaid and totalPaid − loan.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    double balance, rate, payment, interest, pay, loan, totalPaid = 0;
    int months = 0;

    if (scanf("%lf %lf %lf", &balance, &rate, &payment) != 3 ||
        balance <= 0 || rate < 0 || payment <= 0) {
        printf("INVALID\n");
        return 0;
    }
    if (payment <= balance * rate / 1200) {     /* first month's interest */
        printf("NEVER\n");
        return 0;
    }

    loan = balance;                             /* remember the original amount */
    while (balance > 0.005) {                   /* until less than half a paisa */
        interest = balance * rate / 1200;       /* rate% per year = rate/12 % per month */
        balance += interest;
        pay = (payment < balance) ? payment : balance;   /* last month: pay what's left */
        balance -= pay;
        totalPaid += pay;
        months++;
    }

    printf("%d\n", months);
    printf("%.2f %.2f\n", totalPaid, totalPaid - loan);
    return 0;
}

The sample was cross-checked with an independent Python simulation: 11 months, 105898.49 total.

Classic trap

Testing payment < interest instead of <=. In Test 3 the interest is exactly 50 a month, so a payment of 50 leaves the balance at 5000 forever. With < the program hangs, and VPL kills it: a failed test. Always try the boundary input where "never" and "eventually" meet. The loop itself tests balance > 0.005 rather than > 0 as a habit: doubles are inexact (the sheet's Debugging Exercise 5, 0.1 + 0.2 ≠ 0.3), so never rely on a double hitting a value exactly.

Practising with an AI? Ask it well

"Here is a C lab-eval problem, auto-graded by VPL with no prompts allowed: [paste problem]. I've written this: [paste]. Don't solve it. Tell me which of these my code would fail: N = 0, N = 1, all values equal, a value exactly on a boundary, or two rules that both apply."

"Give me two new problems in the style of a VPL lab eval: read N, then N integers, one loop, no arrays, output one or two numbers. For each give 5 test cases with exact expected output, including N = 0, but no code."

Self-test before moving on

All four → Stage 2. If a B problem still needs the plan, redo it tomorrow from blank before moving on. Rung C is optional; C1 and C5 are the best two if you have time for only a couple. Functions in Stage 2 wrap exactly these loops, so they need to be solid.