CS U111 · Lab-eval ladder · Stage 6
Mock lab evaluations
Six timed mocks in the Moodle VPL format: silent input, exact output, five tests per problem. Mocks 1–3 are real instructor evaluations held back from the bank. Mocks 4–6 are ours, for arrays, strings and an end-semester-style program, where no real evaluation has been seen yet.
What the real thing is. From the handout: lab evaluations are unannounced, held in lab sessions, open book, best k of n, 10% in total; the end-semester lab exam is 25%, also open book. From the instructor's 28 released problems: they run on Moodle VPL. Your program reads from the keyboard with no prompts and prints only the answer. Each problem has 5 test cases, and each failed one takes 14% off. Letter case is ignored, but the words must match exactly.
What each mock maps to. Mock 1 → if/else evals (Stage 1) · Mock 2 → loop evals (Stage 1) · Mock 3 → function evals (Stage 2) · Mock 4 → arrays (Stage 3) · Mock 5 → strings (Stage 4) · Mock 6 → everything at end-semester lab-exam level. The six problems in Mocks 1–3 are the instructor's own, quoted word for word. The other 22 are on the lab-eval bank.
What is an estimate. The files don't say how many problems one evaluation has or how long it lasts. Mocks 1–3 assume 2 problems in 45 minutes. Mocks 4–6 are our own problems: the format copies the real evals, but the difficulty is our estimate.
Time budget: 45 + 45 + 45 + 60 + 75 + 90 minutes on the clock, plus about 10 minutes to run the tests after each. That is about 7 hours, so do one mock per sitting.
How to use: start the timer, keep only your open-book tabs open, and don't open any box on this page until time is up. Then run the 5 tests for each problem, count how many passed, and only then read the hints and solution for whatever failed.
Every program here reads silently and prints only the answer, as VPL does. Each problem has 5 tests. To check one, press Copy input, run your program, paste the input, then paste your output into the box and press Check. Or press Download test script, save it next to your .c file and run sh s6-m1q1-tests.sh m1q1.c in Terminal: it compiles with cc -Wall -Wextra and runs all five at once. The full explanation is on Stage 0.
- Lab-eval routine
- Mock 1 · if/else (real)
- Mock 2 · Loops (real)
- Mock 3 · Functions (real)
- Mock 4 · Arrays
- Mock 5 · Strings
- Mock 6 · Integrated
- What your score means
The lab-eval routine
Because an evaluation can start in any lab session, the routine has to be automatic. VPL marks only what your program prints, so the routine is built around getting the input and output exactly right first.
- First five minutes: format, skeleton, sampleRead the Input format and Output format before the story. Write the skeleton:
#include,int main(void), the variables, and thescanflines with noprintfbefore them. Add oneprintfwith the exact output words and a dummy value. Compile, run, paste the sample input. Now you have a file that compiles and prints the right shape. - Build the logicFill in the logic a few lines at a time and compile after each step with
gcc -Wall -Wextra -std=c11 -o q1 q1.c && ./q1. Fix only the first error, then recompile. If the statement lists rules "in this order", copy them as anif / else ifchain in that same order. - Run every edge case you can think ofThe sample passing proves very little; the 5 tests are mostly edge cases. Try N = 0 and N = 1, an input of 0, negative values, all-equal values, and every exact boundary (75 when the rule says "75 or above"). Work out the expected answer by hand before you run each one.
- Before you press EvaluateDelete every prompt and every debug
printf(for example one that printed an intermediate value). Recompile with-Wall -Wextraand treat any warning as a bug. Run the sample one last time. Then Evaluate. - Two problems: one file eachDo the problem with the shorter statement first. Keep
q1.candq2.cseparate so a broken Q2 can't break Q1.
Using the open book quickly
Open these tabs before any lab session, since an evaluation is unannounced. Search with Cmd-F instead of scrolling. The book is for checking syntax you already know. If you would have to learn a whole pattern from it during an evaluation, you are better off getting the sample and the easy edge cases right.
| Tab | Open it for |
|---|---|
| Lab-eval bank | the real problems: the closest model for input reading and output wording |
| Loops notes → "The pattern cookbook" | digit loops, running max/min, counting, totals |
| Functions notes → "The standard file layout" | where prototypes go, passing arrays, return values |
| Arrays notes → "The pattern cookbook" | read n then n values, bubble sort, frequency array |
| Strings notes → "Rule cards" | fgets + strip the newline, strcmp, strcpy, <ctype.h> |
Your own lab .c files | the fastest source of all: copy a read loop you have already debugged |
Unpack: re-running a test without retyping it
Save the test's input in a file such as t1.txt, then run ./q1 < t1.txt. The program reads from the file instead of the keyboard, which is exactly what VPL does. The downloaded test script does this for all five tests.
How to mark yourself
Mark the way VPL does. For each problem, run its 5 tests and count how many pass. A test passes only if your output has the same words and numbers in the same order. Spaces, line breaks and letter case don't matter; a missing or extra word does. Each failed test takes 14% off that problem: 5 passed = 100%, 4 = 86%, 3 = 72%, 2 = 58%, 1 = 44%. The problem files don't say what VPL gives a program that fails every test or doesn't compile, so count that as 0. Your mock score is the number of tests passed out of 10 (Mocks 1–3), 15 (Mocks 4–5) or 5 (Mock 6).
These six were held back from the bank so you meet them cold. Do one mock only after Rung B of the matching stage (Mocks 1 and 2: Stage 1; Mock 3: Stage 2). The statements below are the instructor's, word for word. The test cases are the instructor's 5 listed tests; the sample is shown inside the statement.
Mock 1 · if/else evals 45 min · 2 problems · 10 tests
Both problems read one line of integers and print one phrase. The difficulty is the order of the rules and the exact boundaries.
Q1 · Exam Result Classifier
Write a program that reads three subject marks — Math, Science, and English (each 0 to 100) — and prints the overall result:
DISTINCTIONif all three marks are 75 or above.- Otherwise,
PASSif all three marks are 40 or above. - Otherwise,
FAIL, followed by the name(s) of every subject that scored below 40, in the order Math, Science, English, space-separated on the same line.
Input format Three space-separated integers: math science english.
Output format Either DISTINCTION, PASS, or FAIL followed by the failing subject name(s).
Your output must match the wording shown above exactly — don't paraphrase or substitute a similar word (for example, don't write DISTINCTION as "HONORS", or misspell a subject name). Letter case doesn't need to match, but the actual words do.
Important: Remove any debug/testing printf statements (e.g., ones you added to check intermediate variable values) before you Evaluate. Your output is compared automatically against the expected result, and that comparison includes everything your program prints — not just the line you consider your "real" answer. Even one extra printed number or word will cause an otherwise-correct solution to fail a case it should have passed.
Sample
39 80 90
FAIL Math
Another example, with multiple failures
15 25 30
FAIL Math Science English
The 5 test cases (VPL hides these: open when you would press Evaluate)
80 85 90
DISTINCTION
75 75 75
DISTINCTION
40 40 40
PASS
39 80 90
FAIL Math
20 30 90
FAIL Math Science
Stuck? First move
Three ints and one scanf. Test DISTINCTION first: a student with 80 85 90 also satisfies the PASS rule, so the stricter rule has to come first. The FAIL branch is the only one with work in it.
Plan in plain words
- Read the three marks.
- All three ≥ 75 →
DISTINCTION. - Otherwise all three ≥ 40 →
PASS. - Otherwise print
FAIL. Then check each subject separately and print its name, with a space before it, if it is below 40. Finish with a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int math, science, english;
scanf("%d %d %d", &math, &science, &english); /* no prompt */
if (math >= 75 && science >= 75 && english >= 75) {
printf("DISTINCTION\n");
} else if (math >= 40 && science >= 40 && english >= 40) {
printf("PASS\n");
} else {
printf("FAIL"); /* the names follow on the same line */
if (math < 40) /* three separate ifs, not else-if: */
printf(" Math"); /* every failing subject is printed */
if (science < 40)
printf(" Science");
if (english < 40)
printf(" English");
printf("\n");
}
return 0;
}
Classic trap (read after marking)
Using else if for the subject names. Only the first true branch of a chain runs, so 20 30 90 prints FAIL Math and loses Science: test 5 fails. "Print every subject that…" always means separate ifs. Note also that "75 or above" is >= 75; test 2 (75 75 75) and test 3 (40 40 40) sit exactly on the boundaries.
Q2 · Driving Licence Checker
A transport authority decides a person's driving licence status from their age, their exam results, how long they have held the permit, and their accident record.
A licence can only be issued to a person who is 18 years of age or older and who has passed both the theory exam and the practical exam.
For the first 6 months the licence is provisional — the holder carries a Learner's permit. A new holder starts with 6 penalty points. Every accident during the learner period costs 3 points, so 2 accidents bring the holder to 0 points and the licence is cancelled. After a cancellation the person must wait 12 months before being allowed to retake the exams.
Write a program that reads a person's age, exam results, months elapsed since the permit was issued, and number of accidents, and prints the licence decision.
Rules, in this order:
- If the number of accidents is 2 or more (0 points or fewer remaining) and 12 or more months have elapsed: print
RETEST ELIGIBLE. - Otherwise, if the number of accidents is 2 or more: print
LICENCE CANCELLED. - Otherwise, if age is under 18, or the theory exam was not passed, or the practical exam was not passed: print
NOT ELIGIBLE. - Otherwise, if fewer than 6 months have elapsed: print
LEARNER PERMIT. - Otherwise: print
FULL LICENCE.
For this problem the 12-month waiting period is measured from the same starting point as the permit itself, i.e. from months = 0.
Input format Five space-separated integers: age theory practical months accidents
- age: the person's age in whole years.
- Theory: 1 if the theory exam was passed, 0 if not.
- Practical: 1 if the practical exam was passed, 0 if not.
- Months: whole months elapsed since the permit was issued.
- Accidents: number of accidents recorded against the holder.
All five values are non-negative integers, and that accidents is greater than 0 only for a person who held a permit.
Output format One of RETEST ELIGIBLE, LICENCE CANCELLED, NOT ELIGIBLE, LEARNER PERMIT, or FULL LICENCE.
Your output must match the wording shown above exactly and don't paraphrase or substitute a similar phrase (for example, don't write CANCELLED LICENCE instead of LICENCE CANCELLED, or PROVISIONAL PERMIT instead of LEARNER PERMIT). Letter case doesn't need to match, but the actual words and their order do.
Important: Remove any debug/testing printf statements (e.g., ones you added to check intermediate variable values such as the remaining points) before you Evaluate. Your output is compared automatically against the expected result, and that comparison includes everything your program prints — not just the line you consider your "real" answer. Even one extra printed number or word will cause an otherwise-correct solution to fail a case it should have passed.
Sample
19 1 1 3 0
LEARNER PERMIT
The 5 test cases (VPL hides these: open when you would press Evaluate)
19 1 1 3 0
LEARNER PERMIT
18 1 1 6 0
FULL LICENCE
17 1 1 2 0
NOT ELIGIBLE
20 1 1 5 2
LICENCE CANCELLED
17 1 1 13 3
RETEST ELIGIBLE
Stuck? First move
Five ints, one scanf. The story about penalty points is background: "2 accidents bring the holder to 0 points", so accidents >= 2 is all you need, and the points never have to be computed. Then copy the five rules as one if / else if / else chain, in the order given.
Plan in plain words
- Read age, theory, practical, months, accidents.
- accidents ≥ 2 and months ≥ 12 → RETEST ELIGIBLE.
- Otherwise accidents ≥ 2 → LICENCE CANCELLED.
- Otherwise age < 18, or theory is 0, or practical is 0 → NOT ELIGIBLE.
- Otherwise months < 6 → LEARNER PERMIT; anything left → FULL LICENCE.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int age, theory, practical, months, accidents;
scanf("%d %d %d %d %d", &age, &theory, &practical, &months, &accidents);
/* rules exactly in the order given: the first true one wins */
if (accidents >= 2 && months >= 12)
printf("RETEST ELIGIBLE\n");
else if (accidents >= 2)
printf("LICENCE CANCELLED\n");
else if (age < 18 || theory == 0 || practical == 0)
printf("NOT ELIGIBLE\n");
else if (months < 6)
printf("LEARNER PERMIT\n");
else
printf("FULL LICENCE\n");
return 0;
}
Classic trap (read after marking)
Checking eligibility first because it "feels" like the first question to ask. Test 5 is a 17-year-old with 3 accidents after 13 months: the rules say RETEST ELIGIBLE, but an age-first chain prints NOT ELIGIBLE. When a statement says "rules, in this order", the order is the specification. Also: "fewer than 6 months" is months < 6, so test 2 (exactly 6 months) is FULL LICENCE. And don't leave a debug printf of the points in.
Mock 2 · Loop evals 45 min · 2 problems · 10 tests
Both problems read a count, then that many values, with one loop and no array. The tests aim at N = 1, values that only go down, and negative numbers.
Q1 · Best Buy-Sell Day
You're given the price of a stock on N consecutive days. You may buy on one day and sell on a later day (never the same day, and never sell before you buy). Write a program that finds the maximum possible profit from exactly one such buy-then-sell transaction — if no profitable transaction is possible, the answer is 0.
Input format First line: N. Second line onward: N space- or newline-separated integers, the price on each day in order.
Output format A single integer: the maximum achievable profit (0 if none is possible).
Important: Remove any debug/testing printf statements (e.g., ones you added to check intermediate variable values) before you Evaluate. Your output is compared automatically against the expected result, and that comparison includes everything your program prints — not just the line you consider your "real" answer. Even one extra printed number or word will cause an otherwise-correct solution to fail a case it should have passed.
Sample
5 7 1 5 3 6
5
(Buy at 1, sell at 6, for a profit of 5 — the best possible.)
The 5 test cases (VPL hides these: open when you would press Evaluate)
3 1 5 3
4
1 10
0
4 9 7 5 3
0
4 5 1 8 2
7
4 -3 -8 -1 -5
7
Stuck? First move
You don't need to store the prices. Walk through the days once and keep two numbers: the cheapest price seen so far, and the best profit so far. On each day, ask: "if I sold today, having bought at the cheapest earlier day, what would I make?"
Plan in plain words
- Read N. Set best = 0.
- For each day: read the price. On the first day, it simply becomes the cheapest so far.
- On every later day: if price − cheapest is bigger than best, store it. Then, if the price is below the cheapest, it becomes the new cheapest.
- Print best. If prices only fall, no difference is ever positive, so best stays 0.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int n, price;
scanf("%d", &n);
int minSoFar = 0, best = 0; /* best stays 0 if no profit exists */
for (int i = 0; i < n; i++) {
scanf("%d", &price);
if (i == 0) { /* day 1: nothing to sell yet */
minSoFar = price;
continue;
}
if (price - minSoFar > best) /* sell today, bought at the cheapest earlier day */
best = price - minSoFar;
if (price < minSoFar) /* update AFTER using it: no same-day trade */
minSoFar = price;
}
printf("%d\n", best);
return 0;
}
Classic trap (read after marking)
Starting the cheapest price at 0 instead of at the first day's price. That pretends you could buy for 0 before day 1. Test 2 (one day at 10) then prints 10 instead of 0, and test 3 (9 7 5 3) prints 9 instead of 0. Checked: that version fails tests 1–4. Another one: printing the largest price minus the smallest. In 9 7 5 3 the largest comes before the smallest, and you can't sell before you buy.
Q2 · ATM Transaction Processor with Declines
Write a program that reads a starting account balance, then N transactions (positive integers are deposits, negative integers are withdrawals). Apply each transaction in order — but if a withdrawal would take the balance below zero, decline it (skip it entirely, leaving the balance unchanged) and keep processing the rest. Deposits always succeed.
Input format First line: balance N. Second line onward: N space- or newline-separated integers (the transactions).
Output format Two space-separated integers: <final balance> <number of declined transactions>.
Important: Remove any debug/testing printf statements (e.g., ones you added to check intermediate variable values) before you Evaluate. Your output is compared automatically against the expected result, and that comparison includes everything your program prints — not just the line you consider your "real" answer. Even one extra printed number or word will cause an otherwise-correct solution to fail a case it should have passed.
Sample
100 3 -50 30 -100
80 1
(−50 succeeds → 50; +30 → 80; −100 would go negative, so it's declined.)
The 5 test cases (VPL hides these: open when you would press Evaluate)
0 3 10 20 30
60 0
50 1 -50
0 0
50 1 -51
50 1
20 4 -30 10 -25 5
10 1
0 2 -5 5
5 1
Stuck? First move
One scanf("%d %d", …) for the first line, then a for loop that runs N times and reads one transaction per pass. Inside it there is exactly one decision: apply it, or count it as declined.
Plan in plain words
- Read balance and N. Set declined = 0.
- N times: read the amount. If it is a withdrawal and balance + amount would be below 0, add 1 to declined and leave the balance alone.
- Otherwise add the amount to the balance (adding a negative number subtracts it).
- Print the balance, a space, and declined.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int balance, n, amount;
scanf("%d %d", &balance, &n);
int declined = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &amount);
if (amount < 0 && balance + amount < 0) /* withdrawal would go below 0 */
declined++; /* skip it: balance unchanged */
else
balance += amount;
}
printf("%d %d\n", balance, declined);
return 0;
}
Classic trap (read after marking)
Writing balance + amount <= 0. "Below zero" means < 0: a withdrawal that leaves exactly 0 is allowed. Test 2 (balance 50, withdraw 50) must print 0 0; the <= version prints 50 1. Test 5 checks the other half: a withdrawal from 0 is declined, but the deposit after it still goes through.
Mock 3 · Function evals 45 min · 2 problems · 10 tests
Both problems give you a prototype. You write the function body and a main that reads T, then T cases, and calls the function once per case. The calculation must happen in the function.
Q1 · Round to Nearest Multiple
Write a function
int roundToNearest(int n, int m);
that rounds the non-negative integer n to the nearest multiple of m and returns it. If n is exactly halfway between two multiples of m, round up (to the larger multiple).
Then write a complete C program that reads an integer T, followed by T lines each containing two integers n m. For each line, call roundToNearest and print the value it returns on its own line.
Constraints: 0 <= n <= 1000000, 1 <= m <= 1000.
How this evaluation is different
This is a function evaluation. In earlier evaluations you wrote everything inside main. Here, the starter file only gives you:
- the prototype of
roundToNearest, and - an empty
main(it does nothing yet) and an emptyroundToNearestbody.
You must write both parts yourself:
- the body of
roundToNearest, and - the code in
mainthat reads the input, callsroundToNearest, and prints the value it returns.
The calculation must be done inside roundToNearest, not inside main. If your program never calls roundToNearest, you will see a warning when you evaluate.
Input format The first line contains T. Each of the next T lines has two integers: n m.
Output format T lines, the rounded value for each line, in order.
Sample
3 23 10 27 5 12 4
20 25 12
Important:
- Do not print any prompts such as
Enter a number:. Print only the required output. - Remove all debugging
printfstatements before you submit. Any extra output will make test cases fail.
Starter (our reconstruction of what the description above says VPL gives you)
#include <stdio.h>
int roundToNearest(int n, int m);
int main(void) {
return 0;
}
int roundToNearest(int n, int m) {
}
The 5 test cases (VPL hides these: open when you would press Evaluate)
2 14 10 16 10
10 20
3 15 10 25 10 5 10
20 30 10
3 0 10 10 10 4 10
0 10 0
4 7 3 8 3 10 4 9 4
6 9 12 8
6 3 1 1 100 50 100 49 100 149 100 150 100
3 0 100 0 100 200
Stuck? First move
Get main working first with a dummy body (return n;): read T, loop T times, read two numbers, print the call's result. Then the function: (n / m) * m is the multiple at or below n, because integer division throws the remainder away (23 / 10 = 2, times 10 = 20). The remainder n % m (here 3) decides whether to go up to the next multiple.
Plan in plain words
- main: read T; T times, read n and m and print
roundToNearest(n, m)on its own line. - Function: down = (n / m) × m, and r = n − down (how far above it n is).
- If r is at least half of m, return down + m. Otherwise return down.
- "At least half" without fractions: 2 × r ≥ m.
Unpack: why 2 × r ≥ m and not r ≥ m / 2
With ints, m / 2 drops the fraction: for m = 3 it is 1, so r = 1 would round 7 up to 9 (the answer is 6). Doubling both sides, 2r ≥ m, keeps everything whole: 2 ≥ 3 is false, so 7 stays at 6. For m = 10 and r = 5 (halfway) it gives 10 ≥ 10, true, so it rounds up as required.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int roundToNearest(int n, int m);
int main(void) {
int t, n, m;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &n, &m);
printf("%d\n", roundToNearest(n, m)); /* main reads, calls, prints */
}
return 0;
}
int roundToNearest(int n, int m) {
int down = (n / m) * m; /* multiple at or below n: 23, 10 gives 20 */
int r = n - down; /* how far above it n is (same as n % m) */
if (2 * r >= m) /* halfway or more: round up */
return down + m;
return down;
}
Classic trap (read after marking)
Comparing the remainder with m / 2. r > m / 2 rounds the halfway case down, so 15 10 gives 10 instead of 20 (test 2 fails). r >= m / 2 fixes that but breaks odd m, so 7 3 gives 9 instead of 6 (test 4 fails). Both were checked. Test 5 also has m = 1, where every number is already a multiple.
Q2 · Power Modulo
Write a function
int powerMod(int base, int exp, int m);
that returns (base raised to the power exp) % m, i.e. the remainder when base^exp is divided by m. Note that base^0 = 1, so for exp = 0 the answer is 1 % m.
Do not use pow() or any function from <math.h>: base^exp can be far too large to store, so keep your running result reduced modulo m as you go.
Then write a complete C program that reads an integer T, followed by T lines each containing three integers base exp m. For each line, call powerMod and print the value it returns on its own line.
Constraints: 0 <= base <= 1000, 0 <= exp <= 100, 1 <= m <= 1000.
How this evaluation is different
This is a function evaluation. In earlier evaluations you wrote everything inside main. Here, the starter file only gives you:
- the prototype of
powerMod, and - an empty
main(it does nothing yet) and an emptypowerModbody.
You must write both parts yourself:
- the body of
powerMod, and - the code in
mainthat reads the input, callspowerMod, and prints the value it returns.
The calculation must be done inside powerMod, not inside main. If your program never calls powerMod, you will see a warning when you evaluate.
Input format The first line contains T. Each of the next T lines has three integers: base exp m.
Output format T lines, the result for each line, in order.
Sample
2 3 4 5 2 5 100
1 32
Important:
- Do not print any prompts such as
Enter a number:. Print only the required output. - Remove all debugging
printfstatements before you submit. Any extra output will make test cases fail.
Starter (our reconstruction of what the description above says VPL gives you)
#include <stdio.h>
int powerMod(int base, int exp, int m);
int main(void) {
return 0;
}
int powerMod(int base, int exp, int m) {
}
The 5 test cases (VPL hides these: open when you would press Evaluate)
1 2 10 1000
24
3 5 0 7 7 0 1 0 5 3
1 0 0
1 2 31 1000
648
3 3 40 1000 10 9 7 999 50 1000
801 6 1
3 7 13 11 2 62 97 5 100 13
2 88 1
Stuck? First move
The main is the same T-loop as Q1, with three numbers per line. In the function, start a result and multiply it by the base exp times, taking % m after every multiplication. Only the remainder matters at each step, and keeping it below m stops the number from growing.
Plan in plain words
- main: read T; T times, read base, exp, m and print
powerMod(base, exp, m). - Function: result = 1 % m (this is the answer when exp is 0, and it is 0 when m is 1).
- Repeat exp times: result = (result × base) % m.
- Return result.
Unpack: why reducing every step gives the same answer
The remainder of a product depends only on the remainders of its factors: (a × b) % m = ((a % m) × (b % m)) % m. For example 34 % 5: 3, 9 % 5 = 4, 12 % 5 = 2, 6 % 5 = 1, and 81 % 5 is also 1. Each step multiplies two numbers below 1000, so it never goes past 1,000,000.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int powerMod(int base, int exp, int m);
int main(void) {
int t, base, exp, m;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d %d", &base, &exp, &m);
printf("%d\n", powerMod(base, exp, m));
}
return 0;
}
int powerMod(int base, int exp, int m) {
int result = 1 % m; /* base^0 = 1, and 1 % 1 is 0 */
for (int i = 0; i < exp; i++)
result = (result * (base % m)) % m; /* reduce every step: stays below m */
return result;
}
Classic trap (read after marking)
Starting with result = 1 and returning it when exp is 0. The statement warns that the answer is 1 % m: test 2 includes 7 0 1, whose answer is 0, but that version prints 1. The other trap is computing the power first and taking % m at the end. 231 (test 3) already overflows an int, 340 (test 4) doesn't fit even in a long long, and 99950 has 150 digits.
Modelled on the real format; no real eval for these topics yet. No arrays, strings or recursion evaluation has been released, so these use the VPL rules (silent input, exact words, 5 tests) with our own problems, and the difficulty is our estimate. They are longer than any real eval seen so far: three problems per mock, or one three-part program in Mock 6.
Mock 4 · Arrays + functions 60 min · 3 problems · 15 tests
Calibrated against Lab Sheet 6 Problems 1–8 (read n then n values, one or two passes over the array) and Lab 5a (arrays passed to functions). Suggested split: 15 / 25 / 20 min.
Q1 · Above the average
Write double average(int a[], int n). Read n. If n is not between 1 and 100, print Invalid n and stop. Otherwise read n integers, each between −100000 and 100000.
Print Average: X with 2 decimals. On the next line print Above average (k): followed by the values that are strictly greater than the average, in input order, each preceded by a space. If there are none, print none after the colon.
Input n, then n integers.
Output Invalid n, or the two lines Average: X and Above average (k): ….
The 5 test cases (open when time is up)
5 10 25 7 18 14
Average: 14.80 Above average (2): 25 18
4 6 6 6 6
Average: 6.00 Above average (0): none
3 -5 -1 -2
Average: -2.67 Above average (2): -1 -2
1 -3
Average: -3.00 Above average (0): none
0
Invalid n
Stuck? First move
You need two passes over the same array. The first, inside average(), adds everything up. The second, in main, compares each value with the result. This is why you need an array at all: you can't know which values are above the average until you've seen every value.
Plan in plain words
- Read n and validate it, then read the n values into
a[]. - Call average and print it with
%.2f. - Count the values above the average and print the
(k):part. - If the count is 0, print
none. Then go through the array again, printing each value above the average with a space before it. End with a newline.
Unpack: why (double) sum / n
If both sides of / are int, C throws the fraction away: 74 / 5 is 14. Casting sum to double first makes the division keep the decimals, giving 14.8. Writing (double)(sum / n) is too late, because the fraction has already been lost. See the arrays prerequisite kit.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
double average(int a[], int n) {
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
return (double) sum / n; /* cast first, or 74 / 5 gives 14 */
}
int main(void) {
int a[100];
int n;
scanf("%d", &n);
if (n < 1 || n > 100) {
printf("Invalid n\n");
return 0;
}
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
double avg = average(a, n);
printf("Average: %.2f\n", avg);
int count = 0;
for (int i = 0; i < n; i++)
if (a[i] > avg)
count++;
/* cond ? x : y picks x when cond is true, else y */
printf("Above average (%d):%s", count, count == 0 ? " none" : "");
for (int i = 0; i < n; i++)
if (a[i] > avg)
printf(" %d", a[i]);
printf("\n");
return 0;
}
Classic trap (read after marking)
Integer division in the average: return sum / n; with two ints. Test 1 then prints Average: 14.00 instead of 14.80. On test 3 (-5 -1 -2) the average becomes −2 instead of −2.67, so −2 no longer counts as above it and the list prints only -1. One missing cast fails tests 1 and 3.
Q2 · Leaders
A value is a leader if it is strictly greater than every value that comes after it. The last value is always a leader, since nothing comes after it. Write int is_leader(int a[], int n, int i), which returns 1 if a[i] is a leader and 0 otherwise.
Read n. If n is not between 1 and 100, print Invalid n and stop. Otherwise read n integers. Print the number of leaders on the first line, then the leaders in input order on the second line, separated by spaces.
Input n, then n integers.
Output Invalid n, or two lines: the count, then the leaders.
The 5 test cases (open when time is up)
6 16 17 4 3 5 2
3 17 5 2
1 7
1 7
4 5 5 5 5
1 5
4 -1 -2 -3 -4
4 -1 -2 -3 -4
0
Invalid n
Stuck? First move
This one needs the array: whether a value is a leader depends on values you haven't read yet. Read all n values first. Then write is_leader as a loop over j from i + 1 to the end that gives up (return 0) as soon as it finds a value at least as big.
Plan in plain words
- Read and validate n, then read the values into
a[]. - In the function: for every later index j, if
a[j] >= a[i], return 0. After the loop, return 1. - In main: count the indexes where
is_leaderis 1, and print the count. - Go through again and print each leader, with a space before every one except the first. End with a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* 1 if a[i] is bigger than every value after it, else 0 */
int is_leader(int a[], int n, int i) {
for (int j = i + 1; j < n; j++)
if (a[j] >= a[i]) /* a later value is as big: not a leader */
return 0;
return 1; /* the last value has nothing after it */
}
int main(void) {
int a[100];
int n;
scanf("%d", &n);
if (n < 1 || n > 100) {
printf("Invalid n\n");
return 0;
}
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
int count = 0;
for (int i = 0; i < n; i++)
if (is_leader(a, n, i))
count++;
printf("%d\n", count);
int first = 1; /* no space before the first leader */
for (int i = 0; i < n; i++) {
if (is_leader(a, n, i)) {
if (!first)
printf(" ");
printf("%d", a[i]);
first = 0;
}
}
printf("\n");
return 0;
}
Classic trap (read after marking)
Getting the comparison wrong. "Strictly greater than every later value" means a later value that is equal already disqualifies it, so the test inside the loop is a[j] >= a[i]. With a[j] > a[i], test 3 (5 5 5 5) prints 4 leaders instead of 1 (checked). A second trap: comparing only with the next neighbour (a[i] > a[i+1]). In the sample that makes 4 a leader, because it beats 3, even though 5 comes later.
Q3 · Merge without repeats
Read n1, then n1 integers (list 1), then n2, then n2 integers (list 2). Each list should be in non-decreasing order, and repeats are allowed.
- If a size is not between 1 and 100, print
Invalid sizestraight after reading it, and stop. - If list 1 is not sorted, print
List 1 is not sorted. Otherwise, if list 2 is not sorted, printList 2 is not sorted. - Otherwise print
Merged (k):and then every distinct value from both lists in increasing order, each preceded by a space.
Don't join the lists and sort the result. Walk both lists once, with one index for each.
Input n1, list 1, n2, list 2.
Output One line: one of the two error messages, Invalid size, or Merged (k): and the values.
The 5 test cases (open when time is up)
4 1 3 5 7 5 2 3 4 7 9
Merged (7): 1 2 3 4 5 7 9
3 1 1 2 2 2 2
Merged (2): 1 2
3 4 5 6 3 1 2 3
Merged (6): 1 2 3 4 5 6
2 1 2 3 3 2 1
List 2 is not sorted
0
Invalid size
Stuck? First move
Use two "fingers": i on list 1 and j on list 2. At each step, take the smaller of the two front values and move that finger on. Because values come out in increasing order, a repeat can only equal the last value you wrote, so compare with out[k-1].
Plan in plain words
- Read and validate both sizes and lists. Then check list 1 is sorted, then list 2 (each value ≥ the one before it).
- Set i = j = k = 0. While either list still has values: if list 2 is used up, or list 1's front is ≤ list 2's front, take from list 1. Otherwise take from list 2.
- Write the taken value to
out[k]only ifk == 0or it differs fromout[k-1]. - Print
Merged (k):and the k values.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* 1 if a[0..n-1] never goes down, else 0 */
int is_sorted(int a[], int n) {
for (int i = 1; i < n; i++)
if (a[i] < a[i - 1])
return 0;
return 1;
}
void read_list(int a[], int n) {
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
}
int main(void) {
int a[100], b[100], out[200];
int n1, n2;
scanf("%d", &n1);
if (n1 < 1 || n1 > 100) {
printf("Invalid size\n");
return 0;
}
read_list(a, n1);
scanf("%d", &n2);
if (n2 < 1 || n2 > 100) {
printf("Invalid size\n");
return 0;
}
read_list(b, n2);
if (!is_sorted(a, n1)) {
printf("List 1 is not sorted\n");
return 0;
}
if (!is_sorted(b, n2)) {
printf("List 2 is not sorted\n");
return 0;
}
int i = 0, j = 0, k = 0; /* i walks a, j walks b, k counts out */
while (i < n1 || j < n2) {
int next;
/* take from a if b is used up, or if a's front is smaller */
if (j == n2 || (i < n1 && a[i] <= b[j])) {
next = a[i];
i++;
} else {
next = b[j];
j++;
}
if (k == 0 || out[k - 1] != next) { /* skip a repeat */
out[k] = next;
k++;
}
}
printf("Merged (%d): %d", k, out[0]); /* k >= 1: both lists are non-empty */
for (int t = 1; t < k; t++)
printf(" %d", out[t]);
printf("\n");
return 0;
}
Classic trap (read after marking)
Writing while (i < n1 && j < n2). This stops as soon as one list runs out and silently drops the rest of the other, so test 3 (4 5 6 with 1 2 3) prints only 1 2 3. Either use || with the "used up" check, as in the solution, or add two leftover loops after it.
Mock 5 · Strings + arrays 75 min · 3 problems · 15 tests
Calibrated against Lab Sheet 7 Problems 1, 2 and 9 and the frequency array of Lab Sheet 6 §13. Suggested split: 15 / 30 / 30 min.
Q1 · Letter census
Read one word (no spaces, at most 49 characters). Count each letter, treating upper and lower case as the same letter and ignoring anything that isn't a letter. For each letter that appears, in order from a to z, print x: count with the letter in lowercase. Then print Distinct letters: d. If the word contains no letters at all, print only No letters.
Input One word.
Output One x: count line per letter present, then Distinct letters: d; or No letters.
The 5 test cases (open when time is up)
banana
a: 3 b: 1 n: 2 Distinct letters: 3
R2D2-C3PO
c: 1 d: 1 o: 1 p: 1 r: 1 Distinct letters: 5
AbBa
a: 2 b: 2 Distinct letters: 2
1234
No letters
x
x: 1 Distinct letters: 1
Stuck? First move
Declare int freq[26] = {0};. You need one loop over the word until '\0' to do the counting, and a second loop over 0…25 to do the printing. Letter c goes into box c - 'a', so 'a' lands in box 0 and 'z' in box 25.
Plan in plain words
- Read the word with
%49s. - For each character: if it is a letter, make it lowercase and add 1 to its box.
- For each box from 0 to 25 with a count above 0, print the letter (
'a' + k) and its count, and add 1 to distinct. - If distinct is 0, print
No letters. Otherwise print the distinct line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <ctype.h>
int main(void) {
char word[50];
int freq[26] = {0}; /* freq[0] counts 'a', freq[25] counts 'z' */
scanf("%49s", word);
for (int i = 0; word[i] != '\0'; i++) {
if (isalpha(word[i])) {
char c = tolower(word[i]);
freq[c - 'a']++;
}
}
int distinct = 0;
for (int k = 0; k < 26; k++) {
if (freq[k] > 0) {
printf("%c: %d\n", 'a' + k, freq[k]);
distinct++;
}
}
if (distinct == 0)
printf("No letters\n");
else
printf("Distinct letters: %d\n", distinct);
return 0;
}
Classic trap (read after marking)
Writing freq[word[i] - 'a']++ without the letter check. For '2' the index is 50 − 97 = −47, and for 'R' it is 82 − 97 = −15. Both write outside the array with no error message, which can change other variables; test 2 (R2D2-C3PO) is there for this. Always check isalpha and convert with tolower before indexing.
Q2 · Password checker
Read a password (no spaces, at most 39 characters). Check six rules, in this order:
- at least 8 characters
- an uppercase letter
- a lowercase letter
- a digit
- a special character (anything that is not a letter or digit)
- no character three times in a row
Print Passed p of 6 rules. If p = 6, print Strong. Otherwise print one line for each failed rule, in rule order, using exactly these forms:
- needs at least 8 characters (has L)
- needs an uppercase letter
- needs a lowercase letter
- needs a digit
- needs a special character
- 'c' appears 3 times in a row at position i
For rule 6, report the first such place, with positions counted from 0. Write rules 2–5 as functions that return 1 or 0, and rule 6 as a function that returns the position, or −1 if there is none.
Input One password.
Output The Passed line, then Strong or one line per failed rule.
The 5 test cases (open when time is up)
Tr0ub4dor&3
Passed 6 of 6 rules Strong
hello
Passed 2 of 6 rules - needs at least 8 characters (has 5) - needs an uppercase letter - needs a digit - needs a special character
aaa
Passed 1 of 6 rules - needs at least 8 characters (has 3) - needs an uppercase letter - needs a digit - needs a special character - 'a' appears 3 times in a row at position 0
aaBBB1!x
Passed 5 of 6 rules - 'B' appears 3 times in a row at position 2
xY9#
Passed 5 of 6 rules - needs at least 8 characters (has 4)
Stuck? First move
Write int has_upper(char s[]) first. Loop until '\0', return 1 at the first uppercase character, and return 0 after the loop. The other three yes/no rules are copies of it with one word changed (islower, isdigit, !isalnum).
Plan in plain words
- Read the password and get its length with
strlen. - Count the passed rules with six
ifs, then print the "Passed" line. - If all 6 passed, print
Strongand stop. - Otherwise go through the same six checks again, and print the message for each one that failed.
- Rule 6: for each i where characters i, i+1 and i+2 all exist, return i if all three are equal. Return −1 after the loop.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int has_upper(char s[]) {
for (int i = 0; s[i] != '\0'; i++)
if (isupper(s[i]))
return 1;
return 0;
}
int has_lower(char s[]) {
for (int i = 0; s[i] != '\0'; i++)
if (islower(s[i]))
return 1;
return 0;
}
int has_digit(char s[]) {
for (int i = 0; s[i] != '\0'; i++)
if (isdigit(s[i]))
return 1;
return 0;
}
int has_special(char s[]) {
for (int i = 0; s[i] != '\0'; i++)
if (!isalnum(s[i])) /* not a letter and not a digit */
return 1;
return 0;
}
/* index where some character appears 3 times in a row, or -1 */
int triple_at(char s[]) {
for (int i = 0; s[i] != '\0' && s[i + 1] != '\0' && s[i + 2] != '\0'; i++)
if (s[i] == s[i + 1] && s[i + 1] == s[i + 2])
return i;
return -1;
}
int main(void) {
char pw[40];
scanf("%39s", pw);
int len = strlen(pw);
int t = triple_at(pw);
int passed = 0;
if (len >= 8) passed++;
if (has_upper(pw)) passed++;
if (has_lower(pw)) passed++;
if (has_digit(pw)) passed++;
if (has_special(pw)) passed++;
if (t == -1) passed++;
printf("Passed %d of 6 rules\n", passed);
if (passed == 6) {
printf("Strong\n");
return 0;
}
if (len < 8)
printf("- needs at least 8 characters (has %d)\n", len);
if (!has_upper(pw))
printf("- needs an uppercase letter\n");
if (!has_lower(pw))
printf("- needs a lowercase letter\n");
if (!has_digit(pw))
printf("- needs a digit\n");
if (!has_special(pw))
printf("- needs a special character\n");
if (t != -1)
printf("- '%c' appears 3 times in a row at position %d\n", pw[t], t);
return 0;
}
Classic trap (read after marking)
Putting else return 0; inside the loop. The function then returns after looking at only the first character, so xY9# (test 5) "has no uppercase letter" because it gave up at the x. "Not found" can only be decided after the loop has seen every character.
Q3 · Sentence tidy-up
Read one line with fgets (at most 200 characters; it may be all spaces). Write void tidy(char in[], char out[]), which builds a tidy copy:
- no spaces at the start or end, and every run of spaces replaced by one space;
- the first letter of each sentence in uppercase, where a sentence starts at the beginning of the text and after every
.,!or?; - every other letter in lowercase, and all other characters unchanged.
Print Tidy: [result] (the brackets make spaces visible), then Length: before -> after, where before does not count the newline.
Input One line of text.
Output The Tidy: line and the Length: line.
The 5 test cases (open when time is up)
hello WORLD. this is C! ok
Tidy: [Hello world. This is c! Ok] Length: 34 -> 26
Tidy: [] Length: 3 -> 0
wait... what?! REALLY
Tidy: [Wait... What?! Really] Length: 22 -> 21
3 cats sat.it RAINED
Tidy: [3 Cats sat.It rained] Length: 20 -> 20
is it? yes.
Tidy: [Is it? Yes.] Length: 17 -> 11
Stuck? First move
Use two indexes: i reads in[] and k writes out[]. When you see a space, don't write it. Just remember it (pending_space = 1). Write one space only when the next non-space character arrives and k > 0. That one idea handles leading, repeated and trailing spaces.
Plan in plain words
- Set k = 0, cap_next = 1 and pending_space = 0.
- For each character: if it's a space, set pending_space and move on.
- Otherwise, if pending_space is set and k > 0, write one space. Clear pending_space.
- If it's a letter, make it uppercase if cap_next is set (then clear cap_next), otherwise lowercase. If it's
.,!or?, set cap_next. Write it. - After the loop, write
'\0'atout[k].
Unpack: line[strcspn(line, "\n")] = '\0';
fgets keeps the newline at the end of the line as '\n'. strcspn returns the index of the first '\n', or the length if there is none, and writing '\0' there cuts it off. This is rule card 4 in the strings notes.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* builds the tidy version of in[] into out[] */
void tidy(char in[], char out[]) {
int k = 0; /* next free slot in out */
int cap_next = 1; /* 1 = the next letter starts a sentence */
int pending_space = 0; /* saw spaces since the last kept character */
for (int i = 0; in[i] != '\0'; i++) {
char c = in[i];
if (c == ' ') {
pending_space = 1; /* don't write it yet */
continue;
}
if (pending_space && k > 0) { /* one space, never at the start */
out[k] = ' ';
k++;
}
pending_space = 0;
if (isalpha(c)) {
if (cap_next) {
c = toupper(c);
cap_next = 0;
} else {
c = tolower(c);
}
} else if (c == '.' || c == '!' || c == '?') {
cap_next = 1;
}
out[k] = c;
k++;
}
out[k] = '\0'; /* trailing spaces were never written */
}
int main(void) {
char line[201], result[201];
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0'; /* drop the newline fgets keeps */
tidy(line, result);
printf("Tidy: [%s]\n", result);
printf("Length: %d -> %d\n", (int) strlen(line), (int) strlen(result));
return 0;
}
Classic trap (read after marking)
Forgetting out[k] = '\0'; at the end. out is a fresh array, so printf("%s") then keeps printing whatever bytes follow the text. This often passes one run and fails the next, which makes it look random. A VPL-specific point: the token comparison ignores spaces, so a double space inside Tidy: […] would not fail by itself. The Length: line is what catches it.
Mock 6 · Quiz scoreboard (integrated) 90 min · 1 program · 5 tests
This is pitched at the end-semester lab exam: one program built in three parts, using loops, functions, arrays, strings and one recursive function. What each part draws on:
- Part A: validating and scoring strings (Lab 7) plus a running max (Lab 4).
- Part B: the bubble sort from Lab 6 Problem 8, done on parallel arrays with
strcmp/strcpyas in Lab 7 Problem 5. - Part C: the include/exclude recursion of Lab 8 Practice Problem 5 (Exact Change), but with three branches instead of two, and returning a count instead of true/false.
Suggested split: 35 / 35 / 20 min. Build and test Part A completely before starting Part B. VPL compares the whole output, so an unfinished program fails every test except possibly test 5, which stops after Part A. For practice, also count how many tests your Part A lines alone get right (the lines from Scores: to Top:).
The task
A quiz has m questions, each answered A, B, C or D, or skipped with -. A correct answer scores +4, a wrong answer −1 and a skip 0.
Input The answer key (1 to 10 characters, each A–D, so m = its length). Then n. Then n lines, each with an ID (at most 9 characters, no spaces), a space, and an answer string (at most 19 characters).
If n is not between 1 and 30, print Invalid n and stop. An answer string is valid if its length is m and every character is A, B, C, D or -. Read all the lines before printing anything.
Part A. Print Scores:, then one line per student in input order: ID score, or ID invalid. If no sheet is valid, print No valid sheets and stop. Otherwise print Average: X (2 decimals, valid sheets only) and Top: ID (score). If several students share the top score, use the first in input order. Write int valid_sheet(char ans[], int m) and int score_sheet(char ans[], char key[]).
Part B. Print Hardest question: q (w wrong), where q is the question (numbered from 1) with the most wrong answers among valid sheets. Skips are not wrong. If several questions tie, use the lowest number. If no answer is wrong at all, print Hardest question: none.
Then print Leaderboard: and one line per valid student: rank ID score. Sort by score from high to low, and sort equal scores by ID in strcmp order. Equal scores share a rank and the next rank skips (1, 1, 3). Write the sort as void sort_board(char ids[][10], int scores[], int n) using bubble sort.
Part C (recursion). Write a recursive int patterns(int q, int target), with no loops inside it. It returns the number of ways q questions can each be right (+4), wrong (−1) or skipped (0) so that the total is exactly target. Print Patterns giving S over m questions: N for the top score S.
Output The Part A lines, then the Part B lines, then the Part C line, as described.
The 5 test cases (open when time is up)
ABCDABCD 5 P101 ABCAABCD P102 ABCA-BCD P103 ABC P104 DBCDAB-A P105 ABCDABCB
Scores: P101 27 P102 23 P103 invalid P104 18 P105 27 Average: 23.75 Top: P101 (27) Hardest question: 4 (2 wrong) Leaderboard: 1 P101 27 1 P105 27 3 P102 23 4 P104 18 Patterns giving 27 over 8 questions: 8
ABCD 3 X1 ---- X2 ---- X3 ABCE
Scores: X1 0 X2 0 X3 invalid Average: 0.00 Top: X1 (0) Hardest question: none Leaderboard: 1 X1 0 1 X2 0 Patterns giving 0 over 4 questions: 1
ABCDA 4 zed ABCDA amy ABCDA bob BBCDA cat -----
Scores: zed 20 amy 20 bob 15 cat 0 Average: 13.75 Top: zed (20) Hardest question: 1 (1 wrong) Leaderboard: 1 amy 20 1 zed 20 3 bob 15 4 cat 0 Patterns giving 20 over 5 questions: 1
ABCDABCD 2 K1 AA------ K2 DD------
Scores: K1 3 K2 -2 Average: 0.50 Top: K1 (3) Hardest question: 2 (2 wrong) Leaderboard: 1 K1 3 2 K2 -2 Patterns giving 3 over 8 questions: 224
AB 2 Q abc R A
Scores: Q invalid R invalid No valid sheets
Test 4 checks Part C properly. A top score of 3 over 8 questions can come from 1 right + 1 wrong (8 × 7 = 56 orders) or from 2 right + 5 wrong (8!/(2!·5!·1!) = 168 orders), so 224 in all. This was also checked by listing all 38 = 6561 patterns.
Stuck? First move (Part A)
Declare parallel arrays: char all_ids[30][10] and char all_sheets[30][20] for everything read, and ids, sheets, scores for the valid sheets only. Read all n lines with scanf("%9s %19s", all_ids[s], all_sheets[s]). Then make one pass that validates, scores, prints, and copies each valid sheet into the "valid only" arrays.
Stuck? First move (Part B)
Hardest question: int wrong[10] = {0};. Loop over every valid sheet and, inside that, every question, adding 1 to wrong[q] when the answer isn't '-' and isn't the key's letter. Leaderboard: copy the Lab 6 bubble sort, and change the swap condition to "lower score, or the same score and strcmp(...) > 0".
Stuck? First move (Part C)
Think about the first question only. It is right, wrong or skipped, and each choice leaves q − 1 questions to make up the rest of the total. So patterns(q, t) = patterns(q-1, t-4) + patterns(q-1, t+1) + patterns(q-1, t). For the base case, with 0 questions left, there is exactly 1 way if t is 0 and 0 ways otherwise.
Plan in plain words
- Read the key (m =
strlen), then n (validate it), then all n lines. - A: Print
Scores:. For each line: if it is invalid, printID invalid. Otherwise score it, print it, and copy the ID, sheet and score into the valid arrays (count = valid). If valid is 0, print the message and stop. - A: Sum and find the top score in one loop, using
>so the first student is kept on a tie. Print the average and the top. - B: Count wrong answers per question. Find the maximum, using
>so the lowest number is kept on a tie. Print it, ornone. - B: Sort. Print the leaderboard with
rank = s + 1whenever the score differs from the one above. - C: Print
patterns(m, top_score). Save the top score before sorting, because sorting moves the array entries.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#define MAXN 30
/* ---------- Part A ---------- */
/* 1 if every character of ans is A, B, C, D or '-' and the length matches */
int valid_sheet(char ans[], int m) {
if ((int) strlen(ans) != m)
return 0;
for (int i = 0; i < m; i++) {
char c = ans[i];
if (!(c == '-' || (c >= 'A' && c <= 'D')))
return 0;
}
return 1;
}
/* +4 right, -1 wrong, 0 skipped */
int score_sheet(char ans[], char key[]) {
int score = 0;
for (int i = 0; key[i] != '\0'; i++) {
if (ans[i] == '-')
continue;
if (ans[i] == key[i])
score += 4;
else
score -= 1;
}
return score;
}
/* ---------- Part B ---------- */
/* sort by score high to low; equal scores by ID A to Z */
void sort_board(char ids[][10], int scores[], int n) {
for (int pass = 0; pass < n - 1; pass++) {
for (int j = 0; j < n - 1 - pass; j++) {
int out_of_order = scores[j] < scores[j + 1] ||
(scores[j] == scores[j + 1] && strcmp(ids[j], ids[j + 1]) > 0);
if (out_of_order) {
int t = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = t;
char tmp[10];
strcpy(tmp, ids[j]);
strcpy(ids[j], ids[j + 1]);
strcpy(ids[j + 1], tmp);
}
}
}
}
/* ---------- Part C ---------- */
/* ways to fill q questions (right +4, wrong -1, skip 0) totalling target */
int patterns(int q, int target) {
if (q == 0)
return target == 0; /* all questions decided: did we hit it? */
return patterns(q - 1, target - 4) /* this one right */
+ patterns(q - 1, target + 1) /* this one wrong */
+ patterns(q - 1, target); /* this one skipped */
}
int main(void) {
char key[11];
char all_ids[MAXN][10], all_sheets[MAXN][20]; /* everything typed */
char ids[MAXN][10], sheets[MAXN][20]; /* valid sheets only */
int scores[MAXN];
int n, valid = 0;
scanf("%10s", key);
int m = strlen(key);
scanf("%d", &n);
if (n < 1 || n > MAXN) {
printf("Invalid n\n");
return 0;
}
for (int s = 0; s < n; s++)
scanf("%9s %19s", all_ids[s], all_sheets[s]);
/* Part A: score every valid sheet, in input order */
printf("Scores:\n");
for (int s = 0; s < n; s++) {
if (!valid_sheet(all_sheets[s], m)) {
printf("%s invalid\n", all_ids[s]);
continue;
}
strcpy(ids[valid], all_ids[s]);
strcpy(sheets[valid], all_sheets[s]);
scores[valid] = score_sheet(sheets[valid], key);
printf("%s %d\n", ids[valid], scores[valid]);
valid++;
}
if (valid == 0) {
printf("No valid sheets\n");
return 0;
}
/* Part A: average and top (first in input order on a tie) */
int sum = 0, top = 0;
for (int s = 0; s < valid; s++) {
sum += scores[s];
if (scores[s] > scores[top])
top = s;
}
int top_score = scores[top];
printf("Average: %.2f\n", (double) sum / valid);
printf("Top: %s (%d)\n", ids[top], top_score);
/* Part B: hardest question = most WRONG answers (skips don't count) */
int wrong[10] = {0};
for (int s = 0; s < valid; s++)
for (int q = 0; q < m; q++)
if (sheets[s][q] != '-' && sheets[s][q] != key[q])
wrong[q]++;
int hardest = 0;
for (int q = 1; q < m; q++)
if (wrong[q] > wrong[hardest]) /* strictly more: ties keep the lower number */
hardest = q;
if (wrong[hardest] == 0)
printf("Hardest question: none\n");
else
printf("Hardest question: %d (%d wrong)\n", hardest + 1, wrong[hardest]);
/* Part B: leaderboard with shared ranks 1 2 2 4 */
sort_board(ids, scores, valid);
printf("Leaderboard:\n");
int rank = 1;
for (int s = 0; s < valid; s++) {
if (s > 0 && scores[s] != scores[s - 1])
rank = s + 1;
printf("%d %s %d\n", rank, ids[s], scores[s]);
}
/* Part C */
printf("Patterns giving %d over %d questions: %d\n",
top_score, m, patterns(m, top_score));
return 0;
}
Classic traps (read after marking)
- Swapping the scores but not the IDs in the sort. The scores come out in order, but every name is now next to someone else's score. Tests 1 and 3 catch this (checked).
- Reading the top student from
ids[top]after sorting. The sort has moved the entries, so whatevertoppointed to has changed. Print Part A first, or save the values before sorting. - Counting skips as wrong in the hardest-question count. Test 2 would then print
Hardest question: 1 (2 wrong)instead ofnone.
What your score means
Count tests passed, per problem, the way VPL does. The table reads one problem at a time; the second table gives the matching stage.
| Tests passed | What it usually means | Do next |
|---|---|---|
| 5 / 5 | You can handle an evaluation like this one. | Go to the next mock. A week later, redo your weakest one from a blank file. |
| 3–4 / 5 | The main logic works, but an edge case doesn't: N = 0 or 1, an exact boundary, a tie, a negative value, or rule order. | Look at which tests failed and name the edge case each one targets. Then do Rung B of the matching stage, writing 3 edge-case inputs and their answers before you run anything. |
| 0 / 5, but the output looks right | Almost always output hygiene: a prompt, a debug printf, or a word that differs from the statement. | Reread step 4 of the routine. Compare your output with the expected output word by word. |
| 0–2 / 5 | The pattern for this family isn't automatic yet, or the program didn't compile. | Do Rung A+ and Rung B of the matching stage, then retake this mock in 3–4 days. Check the compile loop on the setup page too. |
| Ran out of time | You can solve these, but not yet from a blank file at speed. | Do Rung B of the matching stage against the clock (about 15 min each), and start every problem with the five-minute skeleton. |
| Lost tests on | Matching stage |
|---|---|
| Mock 1 (if/else) | Stage 1 · Decisions and loops, the if/else problems of Rungs A+ and B |
| Mock 2 (loops) | Stage 1, the loop problems of Rungs A+ and B (counters, totals, running min/max) |
| Mock 3 (functions) | Stage 2 · Functions (prototype + T-loop in main) |
| Mock 4 (any) | Stage 3 · Arrays, and Stage 2 if passing the array to the function was the problem |
| Mock 5 Q1 | Stage 3 (frequency array) and Stage 4 · Strings |
| Mock 5 Q2, Q3 | Stage 4 · Strings |
| Mock 6 Part A | Stage 4 (validating a string) and Stage 1 (running max) |
| Mock 6 Part B | Stage 3 (bubble sort) and Stage 4 (strcmp/strcpy) |
| Mock 6 Part C | Stage 5 · Recursion (branching recursion) |
For more real-format practice, the lab-eval bank has the other 22 instructor problems with their tests.
← Stage 5 · RecursionBack to the ladder hub
Once you've marked a mock yourself, an AI is useful for one narrow job: finding the line that failed a test.
- "Here is my C program for [paste the problem statement]. For input
[paste the failed test]it prints[paste], but the expected output is[paste]. Don't rewrite it: point to the line that causes the difference and explain why, using only first-semester C (no pointers beyond arrays, no structs)." - "Write one new lab-evaluation problem in Moodle VPL style (no prompts, exact output words, an Input format and Output format) in the same family as [e.g. ATM declines: one loop over N values]. Give 5 test cases that target edge cases such as N = 0, N = 1 and exact boundaries. Don't give the solution."
Compile and run whatever it claims. AI-written expected outputs can be wrong too.