CS U111 · Lab-eval ladder · Instructor's problem bank
Real lab evals: the instructor's problem bank
22 lab-evaluation problems released by the instructor, quoted word for word with the instructor's own 5 test cases each, in three families: if/else only, one loop over N inputs, and function evals. New (13 Nov): the instructor's two sample practice programs, Q1 · Number X and Q1 · Shifted number grid (nested loops + a void function), each with a full explanation.
These are real. The instructor released 28 lab-evaluation problems; 22 are on this page, unchanged. The other 6 are held back as the timed Stage 6 mocks, so you can sit them cold. Family 4 at the end is different: two sample practice programs the instructor posted on 13 Nov (30-mark "Q1"s, each a grid with a required function), with their samples and our edge-case tests.
This is what an evaluation looks like. Moodle VPL marks your program automatically: it types the input into your program (stdin) and compares what you print (stdout). Each problem has 5 test cases, and each failed one costs 14 % of the marks. There are no prompts, ever: the input simply arrives. Words must match exactly; letter case is ignored.
The programs are short. Every solution here is 5–15 lines of logic, shorter than most of the old ladder's Rung B. The marks are lost on details (≥ against >, rule order, N = 0), not on length. If a problem takes you 40 lines, step back and reread the statement.
First the matching ladder stage. Families 1 and 2 (if/else, loops) follow Stage 1: do its Rung A → A+ → B first, ending at Stage 1 Rung B. Family 3 (function evals) follows Stage 2 Rung B. Then come here.
Then cold, with the clock. 15 minutes per problem, from a blank file, hints closed. When time is up, mark yourself with the 5 tests below the statement and write down the score out of 5. Only then open the hints, in order: first move, plan, solution. Each family runs from easiest to hardest (our judgement of the order, not the instructor's).
Finally the mocks. The six held-back problems are the Stage 6 mock evals. Keep them for last, as a dress rehearsal.
Every program reads silently and prints only the answer, as VPL does. Each card has the instructor's 5 tests. Check one 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 bank-if1-tests.sh if1.c in Terminal to run all five at once (it compiles with cc -Wall -Wextra). The comparison works like VPL's: spaces, newlines and letter case are ignored; words and numbers must match. Full explanation: Stage 0, how VPL marks.
Every statement carries the same few paragraphs. They are quoted once here and left off the cards below. Read them once; they apply to all 22.
Important: Remove any debug/testing
printfstatements (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.
Your output must match the wording shown above exactly — don't paraphrase or substitute a similar phrase […]. Letter case doesn't need to match, but the actual words do.
Print only the single required output value — nothing else. Do not print any prompts or labels, including things like
printf("Enter three integers: ");orprintf("The result is: ");. VPL runs your program without a person watching, so a prompt just becomes stray text mixed into your output. Your program should read the input silently and print exactly one value.
- 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.
And when a test fails, VPL's message gives no hint about which detail you missed:
This test case did not pass. Re-check your program's logic against the full problem statement — there may be an edge case your code doesn't handle correctly.
So the edge cases are yours to find before you press Evaluate. Each family intro below lists the ones its tests use.
- 1 · if/else only (9)
- 2 · One loop over N inputs (9)
- 3 · Function evals (4)
- 4 · Sample practice programs (2)
- After the bank
Family 1 · if/else only
Two or three integers on one line (often 0/1 flags or a code), one phrase or number out. No loops. These test whether you translate the rules in the right order with the right comparison. What the instructor's tests hit, again and again:
- Exact boundaries. 40 and 41, 60, 65 and 66, 1000, 2000, age 12, 18, 60. "More than" is
>, "or more" / "or above" is>=, "up to (but not including)" is<. Decide each one from the statement's words. - Rule priority. "Otherwise" means
else: the first rule that matches wins, so the narrowest rule goes first (IF4, IF5, IF8). - The opposite case: "every reason that applies". Independent
ifs, noelse(IF9). - Zero and invalid codes. The origin and the axes (IF3), a side of 0 or a flat triangle (IF6), signal code 4 (IF1).
- Percentages in whole numbers. Multiply before dividing:
amount * pct / 100, becausepct / 100on its own is 0.
- IF1 · Traffic Light Action Advisor
- IF2 · Discount Eligibility Checker
- IF3 · Quadrant / Axis Locator
- IF4 · Insurance Risk Tier Classifier
- IF5 · Flight Boarding Priority Classifier
- IF6 · Triangle Classifier
- IF7 · Ticket Price Calculator
- IF8 · Gym Membership Fee Calculator
- IF9 · Voting Eligibility Checker
IF1 · Traffic Light Action Advisor
Write a program that reads a signal code (1 = red, 2 = yellow, 3 = green) and a vehicle's current speed in km/h, and prints the recommended action using a switch on the signal code.
Rules:
- Red (1): if speed > 0, print
STOP IMMEDIATELY. Otherwise printSTAY STOPPED. - Yellow (2): if speed > 40, print
SLOW DOWN NOW. Otherwise printPROCEED WITH CAUTION. - Green (3): if speed > 60, print
REDUCE SPEED. Otherwise printGO. - Any other signal code: print
INVALID SIGNAL.
Input Two space-separated integers: signal speed.
Output A single line with the recommended action, exactly as worded above.
Wording "don't write "STOP NOW" instead of STOP IMMEDIATELY"
Sample
1 20
STOP IMMEDIATELY
1 20
STOP IMMEDIATELY
2 40
PROCEED WITH CAUTION
2 41
SLOW DOWN NOW
3 60
GO
4 10
INVALID SIGNAL
Stuck? First move
Read the two integers, then write the bare switch (signal) with case 1:, case 2:, case 3: and default:, each ending in break;. Only then fill each case with its own two-way if/else.
Plan in plain words
- Read
signalandspeed. - Switch on
signal. In each of cases 1–3: one comparison onspeed, two possible phrases. defaultcatches every other code:INVALID SIGNAL.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int signal, speed;
scanf("%d %d", &signal, &speed);
switch (signal) {
case 1: /* red */
if (speed > 0) printf("STOP IMMEDIATELY\n");
else printf("STAY STOPPED\n");
break; /* without break, red falls into yellow */
case 2: /* yellow */
if (speed > 40) printf("SLOW DOWN NOW\n");
else printf("PROCEED WITH CAUTION\n");
break;
case 3: /* green */
if (speed > 60) printf("REDUCE SPEED\n");
else printf("GO\n");
break;
default: /* 0, 4, -1, ... */
printf("INVALID SIGNAL\n");
}
return 0;
}
Tests 2 and 4 sit exactly on the limits (40 and 60): the rule says strictly more, so writing >= loses both. A missing break after case 1 makes Test 1 print STOP IMMEDIATELY and then a yellow phrase too: two lines, so the test fails even though the first line is right.
IF2 · Discount Eligibility Checker
A store gives discounts based on purchase amount and membership status. Write a program that reads a purchase amount and a membership flag (1 = member, 0 = not a member), and prints the discount percentage applied and the final price.
Rules:
- Members: 15% discount if the purchase amount is 1000 or more, otherwise 5%.
- Non-members: 10% discount, but only if the purchase amount is strictly more than 2000. Otherwise, no discount at all.
Input Two space-separated integers: amount isMember.
Output Two space-separated integers: <discountPercent> <finalPrice>.
Sample
1500 1
15 1275
1500 1
15 1275
1000 1
15 850
3000 0
10 2700
2000 0
0 2000
100 0
0 100
Stuck? First move
Decide the percentage first, in its own variable pct; work out the price only after the if/else is finished. The outer test is membership, the inner test is the amount.
Plan in plain words
- Read
amountandisMember. - Member:
pct= 15 if amount ≥ 1000, else 5. Non-member:pct= 10 if amount > 2000, else 0. - Final price = amount − amount × pct / 100. Print
pct, a space, the price.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int amount, isMember, pct;
scanf("%d %d", &amount, &isMember);
if (isMember == 1) {
if (amount >= 1000) pct = 15; /* "1000 or more" */
else pct = 5;
} else {
if (amount > 2000) pct = 10; /* "strictly more than 2000" */
else pct = 0;
}
/* multiply before dividing: pct / 100 alone is 0 in whole-number division */
printf("%d %d\n", pct, amount - amount * pct / 100);
return 0;
}
The two boundary tests: Test 2 (exactly 1000, member: "or more", so 15 %) and Test 4 (exactly 2000, non-member: "strictly more", so nothing). One rule uses ≥ and the other >; read each one separately. Also, amount * (pct / 100) is always 0, because 15 / 100 is 0 in integer arithmetic: multiply first.
IF3 · Quadrant / Axis Locator
Write a C program that reads two integers x and y, representing the coordinates of a point on a 2D plane, and prints a single integer code describing its location:
| Code | Meaning |
|---|---|
0 | The origin (x = 0 and y = 0) |
1 | Quadrant I (x > 0, y > 0) |
2 | Quadrant II (x < 0, y > 0) |
3 | Quadrant III (x < 0, y < 0) |
4 | Quadrant IV (x > 0, y < 0) |
5 | On the x-axis, not the origin (y = 0, x ≠ 0) |
6 | On the y-axis, not the origin (x = 0, y ≠ 0) |
Input Two space-separated integers on a single line: x y.
Output A single integer: 0 through 6.
Constraints All inputs are integers. (Plus the no-prompts rule quoted in the rules box above.)
Examples
| Input | Output | Explanation |
|---|---|---|
0 0 | 0 | origin |
3 4 | 1 | Quadrant I |
0 0
0
5 0
5
0 5
6
3 4
1
-3 -4
3
Stuck? First move
Write the three "zero" branches first: both zero, then y zero, then x zero. Once those are out of the way, x and y are both non-zero and the four quadrants need only the signs.
Plan in plain words
- Read
x y. - x = 0 and y = 0 → 0. Otherwise y = 0 → 5. Otherwise x = 0 → 6.
- Now neither is zero: x > 0, y > 0 → 1; x < 0, y > 0 → 2; x < 0 (so y < 0) → 3; anything left → 4.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int x, y;
scanf("%d %d", &x, &y);
if (x == 0 && y == 0) printf("0\n"); /* origin first */
else if (y == 0) printf("5\n"); /* x-axis (x is not 0 here) */
else if (x == 0) printf("6\n"); /* y-axis (y is not 0 here) */
else if (x > 0 && y > 0) printf("1\n");
else if (x < 0 && y > 0) printf("2\n");
else if (x < 0) printf("3\n"); /* y < 0 is the only option left */
else printf("4\n");
return 0;
}
Three of the five tests (1–3) are points with a zero coordinate. Writing quadrant I as x >= 0 && y >= 0 and putting it first sends the origin and both axis points to code 1. Zero is neither positive nor negative: it gets its own branches, and they come first.
IF4 · Insurance Risk Tier Classifier
Write a program that reads a person's age, a smoker flag (1 = smoker, 0 = non-smoker), and a pre-existing condition flag (1 = has one, 0 = doesn't), and prints their insurance risk tier.
Rules:
HIGH RISKif the person is both a smoker and has a pre-existing condition.- Otherwise,
MEDIUM RISKif the person is a smoker, or has a pre-existing condition, or is older than 65. - Otherwise,
LOW RISK.
Input Three space-separated integers: age isSmoker hasCondition.
Output One of HIGH RISK, MEDIUM RISK, or LOW RISK.
Wording "don't write "HIGH-RISK" or "SEVERE RISK" instead of HIGH RISK"
Sample
30 1 1
HIGH RISK
30 0 0
LOW RISK
30 1 1
HIGH RISK
65 0 0
LOW RISK
66 0 0
MEDIUM RISK
70 1 1
HIGH RISK
Stuck? First move
The rules already come in priority order with "Otherwise" between them. That word is else: one if / else if / else chain, written in the order the statement gives.
Plan in plain words
- Read the three integers.
- Smoker and condition → HIGH RISK.
- Else smoker or condition or age > 65 → MEDIUM RISK.
- Else LOW RISK.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int age, isSmoker, hasCondition;
scanf("%d %d %d", &age, &isSmoker, &hasCondition);
if (isSmoker == 1 && hasCondition == 1) /* both: highest tier */
printf("HIGH RISK\n");
else if (isSmoker == 1 || hasCondition == 1 || age > 65) /* any one of three */
printf("MEDIUM RISK\n");
else
printf("LOW RISK\n");
return 0;
}
Testing MEDIUM first: a smoker with a condition also satisfies the MEDIUM test, so Tests 2 and 5 print MEDIUM RISK. Put the narrower rule (the && one) above the wider one (the || one). Tests 3 and 4 (age 65, 66) check "older than 65" means > 65, not >= 65.
IF5 · Flight Boarding Priority Classifier
Write a program that reads a ticket class (1 = economy, 2 = business, 3 = first), a frequent-flyer flag (1 = yes, 0 = no), and a special-needs flag (1 = yes, 0 = no), and prints the boarding group.
Rules, in priority order:
- If the passenger has special needs, they board in
GROUP 1, regardless of ticket class. - Otherwise, first class passengers board in
GROUP 2. - Otherwise, business class passengers board in
GROUP 3, and so do economy passengers who are frequent flyers. - Everyone else boards in
GROUP 4.
Input Three space-separated integers: ticketClass isFrequentFlyer hasSpecialNeeds.
Output One of GROUP 1, GROUP 2, GROUP 3, or GROUP 4.
Wording "don't write "Group1" without the space, or "PRIORITY 1" instead of GROUP 1"
Sample
3 0 0
GROUP 2
3 0 0
GROUP 2
2 0 0
GROUP 3
1 0 1
GROUP 1
1 1 0
GROUP 3
1 0 0
GROUP 4
Stuck? First move
Same shape as IF4: the statement lists the rules in priority order, so write one if / else if chain in that order. Special needs is the very first test, before the ticket class is even looked at.
Plan in plain words
- Read the three integers.
- Special needs → GROUP 1.
- Else first class (3) → GROUP 2.
- Else business (2), or economy (1) and frequent flyer → GROUP 3.
- Else GROUP 4.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int ticketClass, isFrequentFlyer, hasSpecialNeeds;
scanf("%d %d %d", &ticketClass, &isFrequentFlyer, &hasSpecialNeeds);
if (hasSpecialNeeds == 1) /* beats every ticket class */
printf("GROUP 1\n");
else if (ticketClass == 3)
printf("GROUP 2\n");
else if (ticketClass == 2 || (ticketClass == 1 && isFrequentFlyer == 1))
printf("GROUP 3\n");
else
printf("GROUP 4\n");
return 0;
}
Test 3 is an economy passenger with special needs. A program that sorts by ticket class first sends them to GROUP 4: "regardless of ticket class" means the special-needs check goes above all the class checks. Test 4 checks the second half of the GROUP 3 rule (economy plus frequent flyer), which is easy to leave out.
IF6 · Triangle Classifier
Write a C program that reads three integers a, b, and c, representing the side lengths of a triangle, and prints a single integer code describing the triangle:
| Code | Meaning |
|---|---|
0 | Not a valid triangle (a side is not positive, or the triangle inequality fails) |
1 | Equilateral (all three sides equal) |
2 | Isosceles (exactly two sides equal) |
3 | Scalene (all three sides different) |
A valid triangle must have all sides greater than 0, and the sum of any two sides must be strictly greater than the third side.
Input Three space-separated integers on a single line: a b c.
Output A single integer: 0, 1, 2, or 3.
Constraints All inputs are integers. (Plus the no-prompts rule quoted in the rules box above.)
Examples
| Input | Output | Explanation |
|---|---|---|
3 3 3 | 1 | all sides equal |
1 2 10 | 0 | 1 + 2 is not greater than 10 |
3 3 3
1
3 4 5
3
5 5 8
2
1 2 10
0
5 5 10
0
Stuck? First move
Write the "not a valid triangle" test as the first branch: six conditions joined with || (three "side ≤ 0", three "two sides add up to no more than the third"). Classifying only starts in the else.
Plan in plain words
- Read
a b c. - Any side ≤ 0, or a + b ≤ c, or a + c ≤ b, or b + c ≤ a → 0.
- Else all three equal → 1.
- Else any two equal → 2 (we already know not all three are).
- Else → 3.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
if (a <= 0 || b <= 0 || c <= 0 ||
a + b <= c || a + c <= b || b + c <= a) /* "strictly greater" fails */
printf("0\n");
else if (a == b && b == c)
printf("1\n");
else if (a == b || b == c || a == c) /* exactly two: three-equal is gone */
printf("2\n");
else
printf("3\n");
return 0;
}
Test 5 is 5 5 10: 5 + 5 is equal to 10, a flat "triangle". The rule says strictly greater, so the invalid test must use <=; with < the program calls it isosceles (2). Validity also has to come before the equal-sides tests, or 5 5 10 matches "two sides equal" first. (The listed tests always put the longest side last, so checking only a + b would slip through them; write all three pairs anyway, it is what the statement says.)
IF7 · Ticket Price Calculator
Write a C program that reads a visitor's age, a flag isWeekend, and a flag isMember, and computes their final ticket price.
Pricing rules, applied in this order:
- Base price by age:
- Under 12 →
5.0 - 12 up to (but not including) 60 →
10.0 - 60 and above →
6.0
- Under 12 →
- Weekend surcharge: if
isWeekendis1, add2.0to the price. - Member discount: if
isMemberis1, reduce the price so far by 10%.
Print the final price with exactly 2 digits after the decimal point.
Input Three space-separated integers on a single line: age isWeekend isMember. isWeekend and isMember are each either 0 or 1.
Output A single decimal number, printed to 2 decimal places.
Constraints All inputs are integers. Do not use loops, functions, or arrays — if / else if / else is sufficient. (Plus the no-prompts rule quoted in the rules box above.)
Examples
| Input | Output | Explanation |
|---|---|---|
8 0 0 | 5.00 | child, weekday, non-member |
8 0 0
5.00
30 1 1
10.80
70 0 1
5.40
12 0 0
10.00
60 0 0
6.00
Stuck? First move
One double price. Step 1 is an if / else if / else that sets it. Steps 2 and 3 are two separate ifs (not else if) that each change it, in the statement's order.
Plan in plain words
- Read the three integers.
- price = 5.0 (age < 12), else 10.0 (age < 60), else 6.0.
- If weekend: price += 2.0.
- If member: price = price × 0.9.
- Print with
%.2f.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int age, isWeekend, isMember;
double price;
scanf("%d %d %d", &age, &isWeekend, &isMember);
if (age < 12) price = 5.0; /* step 1: exactly one base price */
else if (age < 60) price = 10.0; /* 12 .. 59 */
else price = 6.0; /* 60 and above */
if (isWeekend == 1) price += 2.0; /* step 2: its own if */
if (isMember == 1) price *= 0.9; /* step 3: 10% off the price so far */
printf("%.2f\n", price);
return 0;
}
Order of steps 2 and 3. Test 2 (adult, weekend, member) is (10 + 2) × 0.9 = 10.80; discounting first gives 10 × 0.9 + 2 = 11.00. Tests 4 and 5 are the age boundaries 12 and 60, where "up to (but not including)" decides. Writing step 3 as else if after step 2 would skip the discount for weekend members.
IF8 · Gym Membership Fee Calculator
Write a program that reads a person's age, a student flag (1 = student, 0 = not), and a plan code (1 = monthly, 2 = quarterly, 3 = annual), and prints the final membership fee.
Base fees (use a switch on the plan code): monthly = 50, quarterly = 130, annual = 450.
Discount rules (only one discount ever applies — they are not combined):
- If age is under 18, or age is 60 or above: 20% off the base fee.
- Otherwise, if the person is a student: 10% off the base fee.
- Otherwise: no discount.
Input Three space-separated integers: age isStudent planCode.
Output A single integer: the final fee.
Sample
30 0 1
50
30 0 1
50
30 1 2
117
60 0 3
360
59 1 1
45
17 1 2
104
Stuck? First move
Two separate jobs, two separate blocks. First a switch (planCode) that sets base. Then an if / else if / else that sets pct to 20, 10 or 0. The arithmetic happens once, at the end.
Plan in plain words
- Read the three integers.
- Switch: plan 1 → 50, 2 → 130, 3 → 450.
- age < 18 or age ≥ 60 → 20; else student → 10; else 0.
- Print base × (100 − pct) / 100.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int age, isStudent, planCode, base, pct;
scanf("%d %d %d", &age, &isStudent, &planCode);
switch (planCode) {
case 1: base = 50; break;
case 2: base = 130; break;
case 3: base = 450; break;
default: base = 0; /* not specified; keeps base initialised */
}
if (age < 18 || age >= 60) pct = 20; /* else-if: only ONE discount */
else if (isStudent == 1) pct = 10;
else pct = 0;
printf("%d\n", base * (100 - pct) / 100); /* whole numbers throughout */
return 0;
}
Test 5 is a 17-year-old student: 20 % only, 130 → 104. Two separate ifs stack both discounts (130 × 0.8 × 0.9 = 93.6) and the test fails: "not combined" means else if. Tests 3 and 4 are the age boundary from both sides (60 gets 20 %, 59 only the student 10 %). If you compute with 0.8 as a double, print it with a cast or %.0f; %d with a double argument prints garbage.
IF9 · Voting Eligibility Checker
Write a program that reads a person's age, a citizenship flag (1 = citizen, 0 = not), and a criminal record flag (1 = has one, 0 = doesn't), and determines whether they're eligible to vote.
Rules: a person is eligible only if age is 18 or above, they are a citizen, and they have no criminal record.
If eligible, print ELIGIBLE. If not, print NOT ELIGIBLE followed by every reason that applies, space-separated, in this order: Age (if under 18), Citizenship (if not a citizen), Record (if they have a criminal record).
Input Three space-separated integers: age isCitizen hasCriminalRecord.
Output Either ELIGIBLE, or NOT ELIGIBLE followed by the applicable reason(s).
Wording "don't write "INELIGIBLE" instead of NOT ELIGIBLE, or "Underage" instead of Age"
Sample
17 1 0
NOT ELIGIBLE Age
25 1 0
ELIGIBLE
18 1 0
ELIGIBLE
17 1 0
NOT ELIGIBLE Age
25 0 1
NOT ELIGIBLE Citizenship Record
16 0 1
NOT ELIGIBLE Age Citizenship Record
Stuck? First move
The outer decision is an if/else (eligible or not). Inside the else, print NOT ELIGIBLE without a newline, then three separate ifs, each printing a space and one word. The newline comes last.
Plan in plain words
- Read the three integers.
- age ≥ 18 and citizen and no record → ELIGIBLE.
- Otherwise print NOT ELIGIBLE, then: if age < 18 print " Age"; if not a citizen print " Citizenship"; if a record print " Record".
- End the line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int age, isCitizen, hasRecord;
scanf("%d %d %d", &age, &isCitizen, &hasRecord);
if (age >= 18 && isCitizen == 1 && hasRecord == 0) {
printf("ELIGIBLE\n");
} else {
printf("NOT ELIGIBLE"); /* no newline yet */
if (age < 18) printf(" Age"); /* three separate ifs: */
if (isCitizen == 0) printf(" Citizenship"); /* each reason is */
if (hasRecord == 1) printf(" Record"); /* checked on its own */
printf("\n");
}
return 0;
}
"Every reason that applies" is the opposite of rule priority: the reasons must not be an else-if chain. With else if, Test 4 prints only Citizenship and Test 5 only Age. Test 2 (exactly 18) checks "18 or above" is >= 18.
Family 2 · One loop over N inputs
The first line says how many values follow (N, or start N, C N, T N); then the values, read one at a time inside a for loop. No arrays: you keep only running totals, counters, the previous value or a streak. LP7 and LP8 are the two exceptions in shape (nested loops over 1 … N, and a loop over the digits of one number); they are in this family because the instructor grouped them with it. The edges these tests use:
- N = 0 and N = 1. The loop runs zero times or once, so every variable must already hold the right answer before the loop starts (LP1, LP4, LP7, LP9).
- A streak that lasts to the last value. Update the best streak on every pass, not only when a streak breaks (LP6, LP9).
- Equal and negative values. 5 5 5 5, −3 −3, downward elevator trips (LP4, LP9).
- Nothing valid. An average over zero valid values must not divide by zero (LP2).
- Exactly on the threshold. Efficiency exactly 10, a curved score exactly 40 (LP3, LP5).
- Input 0 for a digit loop. 0 has one digit, so use
do … while(LP8).
- LP1 · Highway Toll Calculator by Vehicle Type
- LP2 · Survey Response Validator
- LP3 · Quiz Score Curve Adjuster
- LP4 · Elevator Total Distance Traveled
- LP5 · Trip Fuel Efficiency Analyzer
- LP6 · Rainfall Drought Streak
- LP7 · Sum-Divisible Pair Counter
- LP8 · Digit Frequency Counter
- LP9 · Longest Increasing Streak
LP1 · Highway Toll Calculator by Vehicle Type
A toll booth charges different rates by vehicle type: car (code 1) = 100, bike (code 2) = 50, truck (code 3) = 200. Write a program that reads N vehicle type codes as they pass through, and computes the total toll collected along with a count of each vehicle type. Any code other than 1, 2, or 3 should be ignored entirely — no toll charged, no count incremented.
Input First line: N. Second line onward: N space- or newline-separated integers (vehicle type codes).
Output Four space-separated integers: <total toll> <car count> <bike count> <truck count>.
Sample
4 1 2 3 1
450 2 1 1
(2 cars = 200, 1 bike = 50, 1 truck = 200, total 450.)
3 3 3 3
600 0 0 3
0
0 0 0 0
6 1 1 2 2 3 3
700 2 2 2
4 1 5 2 9
150 1 1 0
5 2 2 2 2 2
250 0 5 0
Stuck? First move
Four variables, all set to 0 before the loop: total, cars, bikes, trucks. Then the standard N-loop: for (i = 0; i < n; i++) { scanf one code; … }.
Plan in plain words
- Read N. Set the four totals to 0.
- N times: read a code. Code 1: add 100, one more car. Code 2: add 50, one more bike. Code 3: add 200, one more truck. Anything else: do nothing.
- After the loop, print the four numbers.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int n, code;
int total = 0, cars = 0, bikes = 0, trucks = 0; /* all start at 0 */
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &code);
if (code == 1) { total += 100; cars++; }
else if (code == 2) { total += 50; bikes++; }
else if (code == 3) { total += 200; trucks++; }
/* any other code: ignored entirely */
}
printf("%d %d %d %d\n", total, cars, bikes, trucks);
return 0;
}
Test 2 is N = 0: the loop never runs, so the answer is whatever the four variables held at the start. Uninitialised, that is garbage; set every counter to 0 before the loop. Test 4 mixes in codes 5 and 9: a final else (or a switch default) that charges a toll or counts a vehicle there gets it wrong.
LP2 · Survey Response Validator
A survey asks respondents to rate something from 1 to 5. Some recorded responses are invalid (outside that range) due to data entry errors. Write a program that reads N responses, and computes the count of valid responses, their sum, and their average — invalid responses must be skipped entirely and must not affect the sum or average. If there are no valid responses at all, print the average as 0.00.
Input First line: N. Second line onward: N space- or newline-separated integers (the responses, which may be invalid).
Output Two integers and a decimal, space-separated: <valid count> <sum> <average, to 2 decimal places>.
Sample
5 3 6 1 0 5
3 9 3.00
(6 and 0 are invalid and are skipped; valid responses 3, 1, 5 sum to 9, average 3.00.)
3 4 5 3
3 12 4.00
3 0 6 10
0 0 0.00
2 1 5
2 6 3.00
2 0 6
0 0 0.00
4 -5 2 10 4
2 6 3.00
Stuck? First move
Inside the loop, one if (r >= 1 && r <= 5) guards both count++ and sum += r. The average is worked out once, after the loop, and only if count is not 0.
Plan in plain words
- Read N. count = 0, sum = 0.
- N times: read r; if 1 ≤ r ≤ 5, count it and add it.
- avg = 0.00 if count is 0, else sum ÷ count as a decimal.
- Print count, sum, avg with
%.2f.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int n, r, count = 0, sum = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &r);
if (r >= 1 && r <= 5) { /* invalid ones touch nothing */
count++;
sum += r;
}
}
double avg = 0.0; /* the "no valid responses" answer */
if (count > 0)
avg = (double) sum / count; /* cast first: else whole-number division */
printf("%d %d %.2f\n", count, sum, avg);
return 0;
}
Tests 2 and 4 have no valid response at all. Dividing anyway is 0 / 0: with ints the program crashes, with doubles it prints nan. Guard the division. Test 5 has both a negative and a too-big value, so the range test needs both halves. (Every listed average happens to be a whole number, so sum / count without the cast would pass these five; it still prints 4.00 for ratings 4 and 5, where the answer is 4.50.)
LP3 · Quiz Score Curve Adjuster
An instructor applies a flat curve of C points to every quiz score (capped at 100). Write a program that reads the curve amount C, then N quiz scores (0–100), and counts how many students moved from failing (below 40) to passing (40 or above) specifically because of the curve — a student already at 40 or above before the curve does not count, even if they're still passing afterward.
Input First line: C N. Second line onward: N space- or newline-separated integers (the original scores, before curving).
Output A single integer: the count of students who newly crossed into passing due to the curve.
Sample
10 4 35 25 45 39
2
(35→45 crosses; 25→35 still fails; 45 was already passing, doesn't count; 39→49 crosses. Total: 2.)
15 1 30
1
20 1 50
0
5 1 35
1
3 1 20
0
8 5 32 40 25 33 50
2
Stuck? First move
Note the input order: C comes before N on the first line. Inside the loop keep both numbers: the original s and the curved after. The count needs both.
Plan in plain words
- Read C and N. count = 0.
- N times: read s; after = s + C, capped at 100.
- If s < 40 (failing before) and after ≥ 40 (passing now), count it.
- Print count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int c, n, s, count = 0;
scanf("%d %d", &c, &n); /* C first, then N */
for (int i = 0; i < n; i++) {
scanf("%d", &s);
int after = s + c;
if (after > 100) after = 100; /* the cap, as the statement says */
if (s < 40 && after >= 40) /* failing before AND passing after */
count++;
}
printf("%d\n", count);
return 0;
}
Counting everyone who passes after the curve. Test 2 (50 was already passing) then prints 1, and Test 5 counts 40 and 50 as well and prints 4. Test 3 lands exactly on 40 (35 + 5), so "passing" must be >= 40. Reading N C instead of C N breaks every test.
LP4 · Elevator Total Distance Traveled
Write a program that reads an elevator's starting floor, then N requested floors in the order they're visited. Compute the total distance traveled — the sum of the absolute difference between each stop and the one before it (starting from the initial floor).
Input First line: startFloor N. Second line onward: N space- or newline-separated integers (the requested floors, in order).
Output A single integer: the total distance traveled.
Sample
1 3 5 2 8
13
(|5−1| + |2−5| + |8−2| = 4 + 3 + 6 = 13.)
0 2 3 7
7
5 0
0
2 3 2 2 5
3
0 3 -3 -1 -5
9
10 4 0 15 5 20
50
Stuck? First move
One variable cur holds "where the elevator is now". It starts as the starting floor; at the end of every pass it becomes the floor just visited.
Plan in plain words
- Read cur (the start) and N. total = 0.
- N times: read next; add |next − cur| to total; then cur = next.
- Print total.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int cur, n, next, total = 0;
scanf("%d %d", &cur, &n); /* cur = where the elevator is now */
for (int i = 0; i < n; i++) {
scanf("%d", &next);
int d = next - cur;
if (d < 0) d = -d; /* absolute value by hand (or abs() from stdlib.h) */
total += d;
cur = next; /* the next trip starts from here */
}
printf("%d\n", total);
return 0;
}
Forgetting cur = next, so every trip is measured from the starting floor: Test 1 then gives 3 + 7 = 10, not 3 + 4 = 7. Leaving out the absolute value lets downward trips cancel upward ones (Tests 4 and 5 go down as well as up). Test 2 is N = 0 with nothing on the second line: the loop must simply not run, and the answer is 0.
LP5 · Trip Fuel Efficiency Analyzer
Write a program that reads an efficiency threshold T (km per litre), then N trips, each given as a distance and the fuel used for that trip. Compute the total distance and total fuel across all trips, and count how many individual trips had efficiency (distance ÷ fuel) strictly below the threshold.
Input First line: T N. Second line onward: N pairs of space-separated integers, distance fuel, one trip's data per pair (fuel is always at least 1).
Output Three space-separated integers: <total distance> <total fuel> <count of trips below threshold>.
Sample
10 3 100 8 50 10 30 2
180 20 1
(Trip 1: 100/8=12.5, not below 10. Trip 2: 50/10=5.0, below 10 — counts. Trip 3: 30/2=15.0, not below 10. Totals: distance 180, fuel 20, 1 trip below threshold.)
5 2 50 5 40 4
90 9 0
10 1 100 10
100 10 0
10 1 99 10
99 10 1
5 2 0 5 50 5
50 10 1
8 3 10 5 20 10 5 5
35 20 3
Stuck? First move
Each pass of the loop reads two numbers: scanf("%d %d", &d, &f). The loop still runs N times, once per trip, not 2N times.
Plan in plain words
- Read T and N. Two totals and a count, all 0.
- N times: read d and f; add each to its total; if d ÷ f (as a decimal) < T, count the trip.
- Print the three integers.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int t, n, d, f;
int totalD = 0, totalF = 0, below = 0;
scanf("%d %d", &t, &n);
for (int i = 0; i < n; i++) { /* one pass per trip */
scanf("%d %d", &d, &f); /* a trip is a PAIR */
totalD += d;
totalF += f;
double eff = (double) d / f; /* fuel >= 1, so no division by zero */
if (eff < t) /* strictly below */
below++;
}
printf("%d %d %d\n", totalD, totalF, below);
return 0;
}
Tests 2 and 3 straddle the threshold: 100 / 10 is exactly 10, which is not strictly below 10; 99 / 10 = 9.9 is. Writing <= fails Test 2. Test 4 has a 0 km trip (efficiency 0, so below). Reading only one number per pass mixes distances with fuels: each trip is a pair, so one scanf reads both.
LP6 · Rainfall Drought Streak
Write a program that reads N days of rainfall amounts (0 means no rain that day). Compute the total rainfall across all days, and the length of the longest streak of consecutive zero-rainfall days.
Input First line: N. Second line onward: N space- or newline-separated non-negative integers.
Output Two space-separated integers: <total rainfall> <longest dry streak>.
Sample
6 5 0 0 3 0 0
8 2
(Total rainfall 5+0+0+3+0+0=8. The longest run of consecutive zero days is 2, achieved twice — days 2–3 and days 5–6.)
3 5 3 2
10 0
4 0 0 0 0
0 4
5 3 0 0 0 0
3 4
5 0 5 0 5 0
10 1
1 0
0 1
Stuck? First move
Two streak variables: cur (the dry run happening right now) and best (the longest seen so far). A dry day grows cur; a rainy day resets it to 0.
Plan in plain words
- Read N. total, cur, best = 0.
- N times: read r; total += r. If r is 0: cur++, and if cur > best then best = cur. Otherwise cur = 0.
- Print total and best.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int n, r, total = 0, cur = 0, best = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &r);
total += r;
if (r == 0) {
cur++; /* the dry run gets longer */
if (cur > best) best = cur; /* update best NOW, not when the run ends */
} else {
cur = 0; /* rain breaks the run */
}
}
printf("%d %d\n", total, best);
return 0;
}
Updating best only when rain ends a dry run. Then a run that lasts to the last day is never recorded, and that is exactly Tests 2, 3 and 5 (each ends dry): they print 0 instead of 4, 4 and 1. Compare cur with best on every dry day.
LP7 · Sum-Divisible Pair Counter
Read two integers N and K. Consider every distinct pair of numbers (i, j) with 1 ≤ i < j ≤ N. Using nested loops, count how many such pairs have a sum (i + j) that is evenly divisible by K.
Input Two space-separated integers: N K.
Output A single integer: the count of qualifying pairs.
Sample
5 3
4
(The qualifying pairs are (1,2), (1,5), (2,4), and (4,5) — each sums to a multiple of 3.)
1 2
0
4 1
6
4 100
0
6 4
3
8 5
6
Stuck? First move
Write the two loop headers straight from 1 ≤ i < j ≤ N: i runs 1 to N, and j starts one past i, so j = i + 1. No input values are read inside the loops: the numbers are just 1 … N.
Plan in plain words
- Read N and K. count = 0.
- For i = 1 … N, for j = i + 1 … N: if (i + j) % K is 0, count++.
- Print count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int n, k, count = 0;
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++) /* j > i: each pair once, never (i, i) */
if ((i + j) % k == 0)
count++;
printf("%d\n", count);
return 0;
}
Starting the inner loop at j = 1. Then every pair is counted twice, as (1, 2) and (2, 1), plus pairs like (2, 2). Test 2 shows it most clearly: with K = 1 every sum is divisible, and the 6 real pairs of 1–4 become 16. Test 1 (N = 1) has no pairs at all: with j = i + 1 the inner loop never runs and the answer is 0 (with j = 1 it counts (1, 1) and prints 1).
LP8 · Digit Frequency Counter
Write a program that reads an integer N (which may be negative) and a single target digit D (0–9), and counts how many times D appears among the digits of N. The sign of N should be ignored when counting digits (treat -1000 the same as 1000).
Input Two space-separated integers: N D.
Output A single integer: the count of occurrences of D in N's digits.
Sample
1212 1
2
(The digits of 1212 are 1, 2, 1, 2 — the digit 1 appears twice.)
456 5
1
7373 7
2
123 9
0
0 0
1
-1000 0
3
Stuck? First move
This one has no N-value list: the loop runs over the digits of one number. n % 10 is the last digit, n /= 10 removes it. Make n positive before the loop starts.
Plan in plain words
- Read n and d. If n < 0, n = −n.
- Repeat (at least once): if n % 10 equals d, count++; then n /= 10. Stop when n is 0.
- Print count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int n, d, count = 0;
scanf("%d %d", &n, &d);
if (n < 0) n = -n; /* ignore the sign */
do { /* do-while: 0 still has one digit, 0 */
if (n % 10 == d) count++; /* look at the last digit */
n /= 10; /* drop it */
} while (n > 0);
printf("%d\n", count);
return 0;
}
Test 4 is 0 0: the number 0 has one digit, and it is 0. A while (n > 0) loop never runs for 0 and prints 0; do … while runs the body once first. Test 5 is negative: without the sign removal, −1000 / 10 is −100, n > 0 is false, and the loop stops after one digit (prints 1, not 3).
LP9 · Longest Increasing Streak
Write a program that reads an integer N, followed by N integers. Find and print the length of the longest run of consecutive, strictly increasing values in the sequence.
Input First line: N. Second line onward: N space- or newline-separated integers.
Output A single integer: the length of the longest strictly-increasing run.
Sample
5 1 2 3 2 5
3
(The run 1, 2, 3 has length 3 — the longest in the sequence.)
4 1 2 3 4
4
1 7
1
4 5 5 5 5
1
5 9 1 2 3 0
3
4 -5 -3 -3 -1
2
Stuck? First move
Combine LP4 and LP6: a prev variable (LP4) and a cur/best pair (LP6). A run counts values, so a run starts at length 1, not 0.
Plan in plain words
- Read N. cur = 0, best = 0.
- For each value x: if it is not the first and x > prev, cur++; otherwise a new run starts, cur = 1. Then if cur > best, best = cur. Then prev = x.
- Print best.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int main(void) {
int n, x, prev = 0, cur = 0, best = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
if (i > 0 && x > prev) /* strictly bigger than the one before */
cur++;
else
cur = 1; /* first value, or the run broke */
if (cur > best) best = cur; /* check every time (run may end the list) */
prev = x;
}
printf("%d\n", best);
return 0;
}
"Strictly increasing" means equal values break the run. With >=, Test 3 (5 5 5 5) prints 4 instead of 1, and Test 5 (−3 −3) prints 4 instead of 2. Test 1 is one run to the very end, so best must be checked on every value, not only when a run breaks. Test 2 (N = 1) needs a run to start at length 1.
Family 3 · Function evals
You get a prototype and a starter file with an empty main and an empty function body. main always has the same shape: read T, then loop T times reading one case, calling the function and printing what it returns. All four statements carry the same note; here it is once, verbatim from FN1 (FN2–FN4 say the same with their own function name):
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
clampToRange, and- an empty
main(it does nothing yet) and an emptyclampToRangebody.You must write both parts yourself:
- the body of
clampToRange, and- the code in
mainthat reads the input, callsclampToRange, and prints the value it returns.The calculation must be done inside
clampToRange, not insidemain. If your program never callsclampToRange, you will see a warning when you evaluate.
The edges these tests use: the smallest inputs (n = 1, k = 1, value 0), values exactly on a limit (low, high, n itself a multiple of k), low == high, negatives, perfect squares for divisor counts, and the largest int, 2147483647. One more trap belongs to the format itself: the function's result must be returned, not printed inside the function, and nothing may carry over from one call to the next.
FN1 · Clamp to Range
Write a function
int clampToRange(int value, int low, int high);
that returns value if it lies between low and high (inclusive), returns low if value is smaller than low, and returns high if value is larger than high. You may assume low <= high.
Then write a complete C program that reads an integer T, followed by T lines each containing three integers value low high. For each line, call clampToRange and print the value it returns on its own line.
Starter (given) As the statement describes it: the prototype, an empty main and an empty function body. The exact file on VPL may differ in small ways.
#include <stdio.h>
int clampToRange(int value, int low, int high);
int main(void) {
return 0;
}
int clampToRange(int value, int low, int high) {
}
Input The first line contains T. Each of the next T lines has three integers: value low high.
Output T lines, the clamped value for each line, in order.
Sample
3 4 1 6 -2 1 6 9 1 6
4 1 6
1 5 1 10
5
3 -3 0 10 15 0 10 7 0 10
0 10 7
4 0 0 10 10 0 10 -1 0 10 11 0 10
0 10 0 10
3 -5 -10 -2 -12 -10 -2 -1 -10 -2
-5 -10 -2
3 4 5 5 5 5 5 6 5 5
5 5 5
Stuck? First move
Write main first, with the function body left as just return value;: read T, loop T times, read three numbers, printf("%d\n", clampToRange(value, low, high));. Compile and run it. Then fix the function.
Plan in plain words
clampToRange: if value < low, return low. If value > high, return high. Otherwise return value.main: read T; T times read value, low, high; print the function's result and a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int clampToRange(int value, int low, int high);
int main(void) {
int t, value, low, high;
scanf("%d", &t);
for (int i = 0; i < t; i++) { /* one pass per test line */
scanf("%d %d %d", &value, &low, &high);
printf("%d\n", clampToRange(value, low, high)); /* main: read, call, print */
}
return 0;
}
int clampToRange(int value, int low, int high) {
if (value < low) return low; /* too small */
if (value > high) return high; /* too big */
return value; /* already inside [low, high] */
}
Test 3 puts values exactly on low and high and one step outside each; Test 4 is all negative; Test 5 has low == high. The VPL-specific trap: doing the comparisons in main and leaving the function empty. It may print the right numbers, but the statement requires the calculation inside the function and VPL warns when it is never called. Also, an int function that can reach its closing } without a return gives a -Wreturn-type warning and a garbage result.
FN2 · Sum of Multiples
Write a function
int sumOfMultiples(int n, int k);
that returns the sum of all positive multiples of k that are less than or equal to n. If there are none, it returns 0.
Then write a complete C program that reads an integer T, followed by T lines each containing two integers n k. For each line, call sumOfMultiples and print the value it returns on its own line.
Constraints 1 <= n <= 1000, 1 <= k <= 1000.
How this evaluation is different Same note as FN1, word for word, with this function's name (quoted in full in the family intro above).
Starter (given) As the statement describes it: the prototype, an empty main and an empty function body. The exact file on VPL may differ in small ways.
#include <stdio.h>
int sumOfMultiples(int n, int k);
int main(void) {
return 0;
}
int sumOfMultiples(int n, int k) {
}
Input The first line contains T. Each of the next T lines has two integers: n k.
Output T lines, the sum for each line, in order.
Sample
2 10 4 3 7
12 0
1 10 3
18
3 9 3 1 5 5 5
18 0 5
2 100 7 1000 1
735 500500
3 20 20 19 20 50 25
20 0 75
3 1000 13 30 4 2 1
38038 112 3
Stuck? First move
main is the same T-loop as FN1, reading two numbers instead of three. In the function, a local sum = 0 and a loop that visits only the multiples: for (m = k; m <= n; m += k).
Plan in plain words
sumOfMultiples: sum = 0; m runs k, 2k, 3k, … while m ≤ n; add each m. Return sum.main: read T; T times read n, k; print the result.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int sumOfMultiples(int n, int k);
int main(void) {
int t, n, k;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &n, &k);
printf("%d\n", sumOfMultiples(n, k));
}
return 0;
}
int sumOfMultiples(int n, int k) {
int sum = 0; /* local: fresh 0 on every call */
for (int m = k; m <= n; m += k) /* k, 2k, 3k, ... up to n INCLUSIVE */
sum += m;
return sum; /* no multiples: loop never runs, 0 */
}
"Less than or equal to n": the tests are full of cases where n itself is a multiple (9 and 3, 5 and 5, 20 and 20, 1000 and 1). With m < n, Test 2 prints 9 0 0 and Test 4 prints 0 0 25. k > n (1 and 5, 19 and 20) must give 0, which the loop does on its own because it never starts.
FN3 · Divisor Count
Write a function
int countDivisors(int n);
that returns the number of positive divisors of n, including 1 and n itself.
Then write a complete C program that reads an integer T, followed by T positive integers. For each integer, call countDivisors and print the value it returns on its own line.
How this evaluation is different Same note as FN1, word for word, with this function's name (quoted in full in the family intro above).
Starter (given) As the statement describes it: the prototype, an empty main and an empty function body. The exact file on VPL may differ in small ways.
#include <stdio.h>
int countDivisors(int n);
int main(void) {
return 0;
}
int countDivisors(int n) {
}
Input The first line contains T. The next T values are positive integers (one per line or space-separated).
Output T lines, the divisor count of each number in the order given.
Sample
3 10 7 8
4 2 4
1 1
1
3 2 3 13
2 2 2
1 36
9
4 12 18 30 28
6 6 8 6
3 100 49 64
9 3 7
Stuck? First move
Try every candidate d from 1 to n and count the ones with n % d == 0. The numbers in these tests are small, so the plain loop is fast enough.
Plan in plain words
countDivisors: count = 0; for d = 1 … n, if n % d is 0, count++. Return count.main: read T; T times read n; print the result.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int countDivisors(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", countDivisors(n));
}
return 0;
}
int countDivisors(int n) {
int count = 0;
for (int d = 1; d <= n; d++) /* 1 and n themselves are included */
if (n % d == 0)
count++;
return count;
}
Test 1 is n = 1: its only divisor is 1, so a loop that stops at d < n (or starts at 2) returns 0. Tests 3 and 5 are perfect squares (36, 100, 49, 64): if you speed up with "divisors come in pairs d and n/d", the square root is its own partner and must be counted once. Unpaired that gives 10 for 36 instead of 9. The plain 1 … n loop has no such risk.
FN4 · Sum of Squared Digits
Write a function
int sumSquareDigits(int n);
that returns the sum of the squares of the decimal digits of the non-negative integer n. For example, for n = 123 the answer is 1 + 4 + 9 = 14. For n = 0 the answer is 0.
Then write a complete C program that reads an integer T, followed by T non-negative integers. For each integer, call sumSquareDigits and print the value it returns on its own line.
Constraints 0 <= n <= 2147483647.
How this evaluation is different Same note as FN1, word for word, with this function's name (quoted in full in the family intro above).
Starter (given) As the statement describes it: the prototype, an empty main and an empty function body. The exact file on VPL may differ in small ways.
#include <stdio.h>
int sumSquareDigits(int n);
int main(void) {
return 0;
}
int sumSquareDigits(int n) {
}
Input The first line contains T. The next T values are non-negative integers (one per line or space-separated).
Output T lines, the result for each number, in order.
Sample
2 34 208
25 68
1 0
0
3 5 9 7
25 81 49
2 123 321
14 14
3 100 1000000 505
1 1 50
3 98765 2147483647 99999
255 260 405
Stuck? First move
The digit peel from LP8, now inside a function: d = n % 10 is the last digit, n /= 10 drops it. Square with d * d, no pow needed.
Plan in plain words
sumSquareDigits: sum = 0; while n > 0: d = n % 10, sum += d × d, n /= 10. Return sum.main: read T; T times read n; print the result.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int sumSquareDigits(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", sumSquareDigits(n));
}
return 0;
}
int sumSquareDigits(int n) {
int sum = 0; /* local: starts at 0 on every call */
while (n > 0) { /* n = 0: loop skipped, answer 0 (correct here) */
int d = n % 10; /* last digit */
sum += d * d;
n /= 10; /* drop it */
}
return sum;
}
Keeping sum somewhere that outlives one call (a global, or a variable in main passed in and never reset). The first number is right and every later one carries the previous total: Test 2 prints 25, 106, 155 instead of 25, 81, 49. Each call starts from its own sum = 0. Test 5 includes 2147483647, the largest int: fine as long as you never add 1 to n or multiply it.
Family 4 · Instructor's sample practice programs
Posted by the instructor on LMS as sample practice programs (screenshots received 13 Nov 2026). Both are labelled "Q1", so they may be versions of the same question for different lab sessions; that is our guess, not something the instructor said. Do Number X first: Shifted grid uses the same skeleton and adds leading spaces and a wrap. They differ from the 22 problems above in four ways, and each one matters:
- Each is labelled "Q1 … (30 marks)" and names the file,
q1.c. That looks like one question from a paper with several, marked per question. We have only seen Q1s, so don't guess at the rest. - They have a loop inside a loop. Each program prints a grid, which none of the 22 needed.
- The required function prints; it doesn't return.
void print_row(int i, int n)is the opposite of the Family 3 rule ("return the value, letmainprint it"). Here the statement says the function prints its row itself, newline included. - Each has one sample and no instructor test cases. Test 1 on each card is the instructor's sample. The other tests are ours, aimed at the edges the statement names, and each test's label says where it came from.
Q1 · Number X
Read an integer n and print an n x n grid of numbers as shown below. For n = 5:
1 0 0 0 1 0 2 0 2 0 0 0 3 0 0 0 4 0 4 0 5 0 0 0 5
When n is even, the two diagonals never meet; for n = 4 the middle rows are 0 2 2 0 and 0 3 3 0.
Write a function void print_row(int i, int n) that prints only row i of the grid for a given n, including the newline at the end. main must read n and print the grid by calling print_row.
Input One integer n.
Output If n is not between 1 and 9, print Invalid and nothing else. Otherwise print the grid, with the numbers in each row separated by single spaces and no spaces at the start of a row. Spaces at the end of a row are ignored.
Sample
4
1 0 0 1 0 2 2 0 0 3 3 0 4 0 0 4
Write your complete program in q1.c. Do not print prompts such as "Enter N".
4
1 0 0 1 0 2 2 0 0 3 3 0 4 0 0 4
5
1 0 0 0 1 0 2 0 2 0 0 0 3 0 0 0 4 0 4 0 5 0 0 0 5
1
1
9
1 0 0 0 0 0 0 0 1 0 2 0 0 0 0 0 2 0 0 0 3 0 0 0 3 0 0 0 0 0 4 0 4 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 6 0 6 0 0 0 0 0 7 0 0 0 7 0 0 0 8 0 0 0 0 0 8 0 9 0 0 0 0 0 0 0 9
10
Invalid
Two more inputs worth one run each: 0 and -3 (both Invalid), and 2 (prints 1 1 then 2 2). Our checker ignores spacing, as VPL's usual comparison does. This statement spells the spacing out, though, so write it exactly as described in case this question is checked more strictly.
Stuck? First move
Forget the function for a minute and look at one row. In the n = 5 grid, row 2 is 0 2 0 2 0: the 2s are in columns 2 and 4. Row 4 is 0 4 0 4 0: columns 2 and 4 again. Finish this sentence for any row i and column j: "the cell is i when …, otherwise it is 0." That sentence is the program.
Plan in plain words
main: readn. Ifn < 1orn > 9, printInvalidand stop.main: forifrom 1 ton, callprint_row(i, n). That's allmaindoes.print_row: forjfrom 1 ton: ifjis not the first column, print a space; then ifj == iorj == n + 1 - i, printi, otherwise print0.print_row: after the loop, print\n.
Explanation: from the picture to the code (read after your attempt)
1 · Number the rows and columns from 1. Call the row i and the column j, both running 1 to n. Counting from 1 makes life easy here, because the number printed in row i is i itself. Counting from 0 also works, but then every printed number becomes i + 1; pick one way and keep it.
i holds its own number i in two columns: j = i (blue) and j = n + 1 − i (green). Every other cell is 0. For odd n the two coincide in the middle row; for even n they sit side by side in the two middle rows.2 · Find the rule for one cell. The blue diagonal is easy: row 1 has it in column 1, row 2 in column 2, so it is column j = i. The green diagonal starts at the top-right, column n, and moves one column left for every row down. So in row i (which is i − 1 rows below the top) it is in column n − (i − 1) = n + 1 − i. Check it on row 2 of n = 5: 5 + 1 − 2 = 4, and the second 2 is indeed in column 4. So: cell (i, j) is i if j == i || j == n + 1 - i, otherwise 0.
3 · The middle cell takes care of itself. When n is odd, the middle row has i = n + 1 − i (for n = 5, row 3: 5 + 1 − 3 = 3), so both rules point at the same column. Because the code asks one question per cell, "is this cell on either diagonal?", that cell is printed once. When n is even, i = n + 1 − i would need 2i = n + 1, an odd number, which is impossible. That's the statement's "the diagonals never meet", and why rows 2 and 3 of n = 4 have their two numbers next to each other (0 2 2 0).
4 · Spaces go between numbers, not before them. Print a space before every number except the first in the row: if (j > 1) printf(" ");. (Printing "%d " with a space after every number also matches the statement, because spaces at the end of a row are ignored. Printing " %d" puts a space at the start of the row, which the statement forbids.)
5 · Why a void function, and who prints the newline. print_row's job is to print one row, not to work out a single value, so it returns nothing: void, no return value. The statement puts the newline inside it ("including the newline at the end"), so main is just a loop of calls. Here is print_row(2, 4) traced cell by cell (n + 1 − i = 3):
| j | j > 1? (space) | j == 2 or j == 3? | printed so far |
|---|---|---|---|
| 1 | no | no → 0 | 0 |
| 2 | yes | yes → 2 | 0 2 |
| 3 | yes | yes → 2 | 0 2 2 |
| 4 | yes | no → 0 | 0 2 2 0 |
| end | after the loop: \n | 0 2 2 0⏎ | |
6 · Check the input before printing anything. "Print Invalid and nothing else" means the check comes first and the program stops right after it (return 0;), so no grid follows. We read "between 1 and 9" as including both ends: 1 and 9 are valid, so the test is n < 1 || n > 9. If you want certainty about the ends, ask the instructor; the sample doesn't settle it.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
void print_row(int i, int n);
int main(void) {
int n;
scanf("%d", &n);
if (n < 1 || n > 9) { /* check first, print nothing else */
printf("Invalid\n");
return 0;
}
for (int i = 1; i <= n; i++) /* main only loops over rows */
print_row(i, n);
return 0;
}
void print_row(int i, int n) {
for (int j = 1; j <= n; j++) { /* one pass per cell of row i */
if (j > 1)
printf(" "); /* space BETWEEN numbers, never before the first */
if (j == i || j == n + 1 - i) /* on either diagonal: one test, one print */
printf("%d", i);
else
printf("0");
}
printf("\n"); /* the row's newline belongs to print_row */
}
Two separate ifs for the two diagonals. It looks natural to write if (j == i) printf("%d", i); and then if (j == n + 1 - i) printf("%d", i); else printf("0");. But the else belongs only to the second if, so a blue cell prints its number and then a 0. For n = 4 the first row comes out as 10 0 0 1 and the middle row of n = 5 as 0 0 33 0 0 (we ran it). Every test fails. One condition joined with || and one if/else per cell avoids this.
Also lose marks: printing the grid after Invalid (no return or else); n >= 9 instead of n > 9 (Test 4 then prints Invalid); writing the whole grid inside main, or making print_row print every row (the statement requires main to call it once per row); a printf("Enter N") prompt.
Passed all 5? Three variants on the same skeleton
Keep main and the loop in print_row exactly as they are and change only the cell condition. Work out each condition yourself first, then check it with n = 5.
- A hollow square of 1s (1s on the border, 0s inside): print 1 when
i == 1 || i == n || j == 1 || j == n. - A plus sign for odd
n(the middle row and the middle column hold the row number): printiwheni == (n + 1) / 2 || j == (n + 1) / 2. - Only the upper half of the X (rows below the middle all 0): add
&& i <= (n + 1) / 2to the X condition, with brackets around the||part.
Q1 · Shifted number grid
Read an integer n and print n rows. Each row holds n numbers. Row i starts at i and counts up, and after n it wraps around to 1. Row i starts with 2*(i-1) spaces, so each row is shifted further to the right. For n = 4:
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
Write a function void print_row(int i, int n) that prints only row i of the grid for a given n, including its leading spaces and the newline at the end. main must read n and print the grid by calling print_row.
Input One integer n.
Output If n is not between 1 and 9, print Invalid and nothing else. Otherwise print the grid. Each row has the number of leading spaces described above, and the numbers in a row are separated by single spaces. Spaces at the end of a row are ignored.
Sample
4
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3Write your complete program in q1.c. Do not print prompts such as "Enter N".
4
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 31
1
2
1 2 2 1
9
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 80
Invalid
The paste-checker and the test script compare word by word, as VPL usually does, so a program that forgets the leading spaces still shows "Pass" here. This statement makes the spaces part of the answer, so check them by eye. Run ./a.out | sed 's/ /·/g' in Terminal (type 4 and press Enter): every space shows as a dot, and the result should be exactly
1·2·3·4 ··2·3·4·1 ····3·4·1·2 ······4·1·2·3
That's 0, 2, 4 and 6 dots in front of the rows, and one dot between numbers.
Stuck? First move
Split each row into two jobs and do them one at a time. First, print only the spaces: for n = 4 you should see nothing on row 1 and 2, 4, 6 spaces on rows 2–4. Then make every row print i, i+1, … with no wrap at all; you'll get 2 3 4 5 on row 2. The last step is to turn that 5 back into 1.
Plan in plain words
main: readn. Ifn < 1orn > 9, printInvalidand stop. Otherwise callprint_row(i, n)fori= 1 ton.print_row, part 1: a loop that prints2*(i-1)spaces.print_row, part 2: setv = i. Repeatntimes: print a space if this isn't the first number, printv, add 1 tov, and ifvis now bigger thann, set it back to 1.print_row, part 3: print\n.
Explanation: from the picture to the code (read after your attempt)
1 · Same skeleton as Number X. main checks n, then calls print_row(i, n) once per row. All the work is inside print_row, and it has three parts: the leading spaces, the numbers, the newline.
i just starts at i. After n comes 1 again. Right: the same grid with every space drawn as a dot. The coloured dots are the leading spaces, 2·(i − 1) of them; the grey ones are the single spaces between numbers.2 · The leading spaces are a loop of their own. Row i needs 2*(i-1) spaces: 0, 2, 4, 6 for n = 4. A loop for (s = 0; s < 2 * (i - 1); s++) printf(" "); prints exactly that many. On row 1 the condition 0 < 0 is false at once, so nothing is printed, which is what row 1 needs. Why two spaces per step? Each number is one digit plus one space, two characters wide, so shifting by 2 moves the row one number's width to the right. That's why the grid looks like a staircase.
3 · Counting with a wrap. Keep a variable v for "the number to print next". It starts at i. After printing it, add 1. If that takes it past n, set it back to 1. Row 3 of n = 4: print 3, v becomes 4; print 4, v becomes 5, too big, so v = 1; print 1, v = 2; print 2. Output 3 4 1 2. The loop runs exactly n times because it counts numbers printed (k from 1 to n), not the value of v.
Unpack this step: the one-line version with %
The k-th number of row i (counting k from 0) is (i - 1 + k) % n + 1. Subtracting 1 makes the numbers 0 to n−1, where % wraps correctly; adding 1 at the end shifts them back. Row 3, n = 4, k = 2: (2 + 2) % 4 + 1 = 1 ✓. The if version gives the same output and is easier to get right under time pressure.
4 · Spaces between numbers. As in Number X: print a space before every number except the first (if (k > 1)). Here it matters more. If you print " %d" for every number, each row gets one extra leading space (1, 3, 5, 7 instead of 0, 2, 4, 6). And spaces at the start of a row are exactly what this statement counts.
5 · The input check comes first. Same as Number X: if (n < 1 || n > 9), print Invalid, return 0;. We read "between 1 and 9" as including 1 and 9.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
void print_row(int i, int n);
int main(void) {
int n;
scanf("%d", &n);
if (n < 1 || n > 9) { /* check first, print nothing else */
printf("Invalid\n");
return 0;
}
for (int i = 1; i <= n; i++) /* main only loops over rows */
print_row(i, n);
return 0;
}
void print_row(int i, int n) {
for (int s = 0; s < 2 * (i - 1); s++)
printf(" "); /* the leading spaces: 2*(i-1) of them */
int v = i; /* row i starts at i */
for (int k = 1; k <= n; k++) { /* exactly n numbers */
if (k > 1)
printf(" "); /* one space BETWEEN numbers */
printf("%d", v);
v++; /* count up ... */
if (v > n)
v = 1; /* ... and after n, wrap around to 1 */
}
printf("\n");
}
Wrapping with % n straight. v = (v + 1) % n; looks like the natural wrap, but 4 % 4 is 0, not 4. For n = 4 the first row comes out 1 2 3 0, and every row before the last has a 0 in it (we ran it). The values must wrap from n to 1, so either use if (v > n) v = 1; or the (i - 1 + k) % n + 1 formula from the unpack above.
No wrap at all: 2 3 4 5, 3 4 5 6, 4 5 6 7, so Tests 1, 3 and 4 fail. Also lose marks: one leading space per step instead of two; " %d" for every number (an extra space at every row start); looping while (v <= n), which stops at n and never prints the wrapped numbers; the grid printed after Invalid; a prompt.
Passed all 5? Three variants on the same skeleton
Keep main as it is and change only print_row. Predict the n = 4 output on paper first, then run it.
- Shift left instead of right: leading spaces
2*(n-i). Row 1 now has the most spaces and rownhas none. - Count down with a wrap: row
istarts atiand goesi, i−1, …, and after 1 comesn. That'sv--; if (v < 1) v = n;. Row 2 of n = 4 is2 1 4 3. - No spaces, a square: drop the leading-space loop. You get each row starting one later, the classic "Latin square", where every number appears once in each row and once in each column.
After the bank
Keep a tally: for each problem, tests passed out of 5 on the cold attempt. A test you failed is worth more than one you passed: write down which edge case it was (boundary, priority, N = 0, …). After a few problems the same few names repeat, and that short list is what to check before pressing Evaluate.
When most problems in a family pass 5/5 cold within 15 minutes, move to the mocks. If a family still needs the plan, redo its first three problems tomorrow from a blank file before going on.
"Here is a lab-eval problem statement and my C program: [paste both]. Don't fix it. Give me three test inputs, each aimed at a different edge case in the statement (a boundary, N = 0, rule order), and the exact expected output for each."
"Write me one new problem in the same format as this one [paste a statement]: same input shape, different rules, 5 test cases with exact outputs, at least three of them edge cases. No solution."