CS U111 · Lab-eval ladder · Stage 2
Functions: from one helper to a program built from parts
Twenty programs and five predict-the-output items, in four rungs. Rung A is one function and a main that calls it. Rung A+ drills the function-eval input shape: a given prototype and T test cases. Rung B is five function evals built like the instructor's real ones. Rung C (optional) is the longer lab-sheet-style programs. Every program reads silently and prints only the answer, as VPL requires; every solution compiles with clang -Wall -Wextra -std=c11 with no warnings and passes its five tests.
What this stage covers: writing and calling your own functions (Lab Sheet 5A), then what happens to variables when you do: pass-by-value, local vs global scope, shadowing (Lab Sheet 5B). Nothing here goes beyond those two sheets: no pointers, no arrays (arrays are Stage 3).
What the real evals look like: the instructor's six function evals (on the lab-eval bank) all have one shape. You get a prototype such as int countDivisors(int n);, an empty main and an empty function body. main reads T, then T cases, calls the function once per case, and prints each result. The logic inside is 5–15 lines of Lab 4 loops and ifs, which you have already done in Stage 1. What's new is only the packaging. Rung B is calibrated against those six: same layout, same size, five tests each, different problems.
What each rung is for: A gets the packaging automatic (return type, parameters, return, call). A+ is the eval's input shape with one-line bodies, so B is only about the body. B is eval level. C is optional: longer programs from the old lab-sheet level, useful for the end-semester lab exam.
Time: A about 30 min, A+ 20 min, the predict-the-output set 20 min, B 75–100 min (15–20 min per problem): about 2½–3 hours for the core. C is optional and takes about 3½ hours more. If you have one evening, do A+, the predict set and B1–B3.
How to use it: read the problem, then write something in a blank file before opening anything. If you can't start, open only "Stuck? First move". Then try again. Open "Plan in plain words" next if you need it, and the full solution last, after your own version compiles and you have run the tests, even if some fail.
Every program on this page reads its input silently and prints only the answer, exactly as VPL expects: no prompt before a scanf, no leftover debug prints. Each card has 5 tests; VPL compares your output token by token, ignoring spacing and letter case, and each failed test costs 14%. Check one test with Copy input → run your program → paste its output → Check. Or press Download test script, save it next to your .c file and run sh s2-b1-tests.sh b1.c in Terminal to run all five at once (it compiles with cc -Wall -Wextra). The full explanation is on Stage 0.
Need the teaching first? The functions lesson explains everything used here from scratch; the functions notes are the one-page revision map. The worked answers to the sheet's own problems are on Lab 5A solutions, and the functions & arrays dry-run drill has more tracing practice.
Syntax you need for this stage
| Form | What it means |
|---|---|
for (int i = 0; i < t; i++) | The T-loop. Declaring i inside the for is the same as writing int i; above it; the loop runs exactly t times. |
int maxOf3(int a, int b, int c) { … return m; } | A definition: return type, name, parameters. return hands one value back and leaves the function at once. |
int maxOf3(int a, int b, int c); | A prototype (declaration): needed above main when the definition comes after main. Function evals give you exactly that layout: prototype at the top, empty body below main. Keep it. In Rungs A and C the functions are written above main, so no prototype is needed there. |
void printRow(int n, char ch) | void return type: the function does a job (prints) and returns nothing. |
void showMenu(void) | void in the brackets: it takes no arguments. Call it as showMenu();. |
big = maxOf3(x, y, z); | A call. The values of x, y, z are copied into a, b, c; the returned value takes the place of the call. |
return n % 2 == 0; | A comparison already is 1 (true) or 0 (false), so a yes/no function can return it directly. |
long long f; printf("%lld", f); | Integers up to about 9.2 × 1018 (an int stops near 2.1 × 109). Read with %lld too. |
double x; scanf("%lf", &x); | Read a double with %lf; print with %f, %.6f (6 decimals) or %g (drops trailing zeros: 27 instead of 27.000000). |
scanf(" %c", &ch); | The space before %c skips any spaces and newlines left over from the previous scanf. |
scanf("%d/%d", &a, &b); | Characters in the format (here /) must appear in the input exactly: the input contains 3/4. |
int count = 0; written above all functions | A global: every function below it sees the same single variable. Lab 5B: use sparingly. |
#define MAX_STEPS 30 | A named constant: the preprocessor replaces every MAX_STEPS with 30 before compiling. |
Rung A · Warm-up
About 30 minutes; 5–10 per problem. Each problem has the same shape: write one small function, and a main that reads the input, calls it, and prints the result. This trains the packaging (return type, parameters, return, call) until it is automatic.
A1 · Largest of three, as a function
Write a function int maxOf3(int a, int b, int c) that returns the largest of its three arguments. In main, read three integers and print the value maxOf3 returns. Inputs may be negative or equal.
Input Three integers on one line.
Output One integer: the largest.
4 9 2
9
-5 -1 -7
-1
3 3 3
3
9 4 9
9
1 2 3
3
Stuck? First move
Write the first line of the function before anything else: int maxOf3(int a, int b, int c) {. Inside it you need one local variable, m, which will hold "the largest so far". Start it as a.
Plan in plain words
- In the function: m ← a. If b > m, m ← b. If c > m, m ← c. Return m.
- In main: read x, y, z (no prompt), print the value of maxOf3(x, y, z).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* returns the largest of a, b and c */
int maxOf3(int a, int b, int c) {
int m = a; /* assume a is the largest... */
if (b > m)
m = b; /* ...and correct it if b beats it */
if (c > m)
m = c;
return m;
}
int main(void) {
int x, y, z;
scanf("%d %d %d", &x, &y, &z); /* no prompt: VPL types the input */
printf("%d\n", maxOf3(x, y, z));
return 0;
}
Printing inside maxOf3 instead of returning. The output may look the same, but the function is now useless to any other code that needs the number, and a question that says "returns" loses the mark. Tests 4 and 5 (a tie for largest, largest last) catch a function that only compares a with b.
A2 · Digit sum
Write int digitSum(int n) that returns the sum of the decimal digits of n (0 ≤ n ≤ 2147483647). In main, read n and print the digit sum.
Input One non-negative integer n.
Output One integer: the sum of the digits of n.
4096
19
0
0
7
7
1000000
1
2147483647
46
Stuck? First move
This is the Lab 4 digit loop (n % 10 gives the last digit, n / 10 drops it), moved into a function. Write int digitSum(int n) { and declare int sum = 0;. The loop runs while n > 0.
Plan in plain words
- sum ← 0.
- While n > 0: add n % 10 to sum; n ← n / 10.
- Return sum.
- main: read n, print digitSum(n).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* adds up the decimal digits of n (n >= 0) */
int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum = sum + n % 10; /* last digit */
n = n / 10; /* drop the last digit */
}
return sum;
}
int main(void) {
int n;
scanf("%d", &n);
printf("%d\n", digitSum(n));
return 0;
}
If main printed n after the call, it would still show 4096, even though digitSum divided its n down to 0. The function worked on a copy. That's pass-by-value, and the predict-the-output set below is built around it. (For 0 the while loop never runs and the answer 0 is still right; when counting digits it would not be, which is why B4 uses do … while.)
A3 · A conversion table: calling a function in a loop
Write double toFahrenheit(double c) using F = C × 9/5 + 32. In main, read three integers from to step (step > 0). Print a header line C F, then one line per Celsius value from from up to to in steps of step: the Celsius value, a space, and the Fahrenheit value with one decimal (%.1f). If from is larger than to, print only the header.
Input Three integers: from to step.
Output The line C F, then one line c f per value. (VPL ignores extra spaces, so lining up columns is optional.)
0 100 20
C F 0 32.0 20 68.0 40 104.0 60 140.0 80 176.0 100 212.0
-40 -40 5
C F -40 -40.0
37 37 1
C F 37 98.6
10 0 5
C F
-10 10 10
C F -10 14.0 0 32.0 10 50.0
Stuck? First move
The function body is one line: return c * 9.0 / 5.0 + 32.0;. The work in main is a for loop whose variable goes from, from + step, … while it is ≤ to, calling the function once per line.
Plan in plain words
- Read from, to, step. Print the header.
- For c = from; c ≤ to; c ← c + step: print c and toFahrenheit(c).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
double toFahrenheit(double c) {
return c * 9.0 / 5.0 + 32.0;
}
int main(void) {
int from, to, step, c;
scanf("%d %d %d", &from, &to, &step);
printf("C F\n"); /* the header the statement asks for */
for (c = from; c <= to; c = c + step) {
printf("%d %.1f\n", c, toFahrenheit(c));
}
return 0;
}
Passing the int c to a double parameter is fine: C converts it automatically. Test 4 starts above its end, so the loop runs zero times and only the header is printed.
c * 9 / 5 + 32 with an int parameter does integer division: for 37 °C it gives 98 instead of 98.6, and Test 3 fails. Use double and write 9.0 / 5.0.
A4 · Triangle of symbols: a void function
Write void printRow(int n, char ch) that prints ch exactly n times and then a newline. In main, read a height h ≥ 1 and a symbol, then use printRow to draw a right triangle of height h: row 1 has one symbol, row h has h.
Input An integer h and one non-space character, separated by a space or a newline.
Output h lines of symbols.
4 #
# ## ### ####
1 *
*
2 +
+ ++
5 x
x xx xxx xxxx xxxxx
3 @
@ @@ @@@
Stuck? First move
In Lab 4 this was a nested loop. Now the inner loop goes into printRow, and main keeps only the outer loop: row 1 calls printRow(1, sym), row 2 calls printRow(2, sym), and so on. Read the symbol with scanf(" %c", &sym) (note the space).
Plan in plain words
- printRow: repeat n times: print ch. Then print a newline.
- main: read h, read sym. For row = 1 to h: printRow(row, sym).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* prints ch n times, then ends the line; returns nothing */
void printRow(int n, char ch) {
int i;
for (i = 1; i <= n; i++)
printf("%c", ch);
printf("\n");
}
int main(void) {
int h, row;
char sym;
scanf("%d", &h);
scanf(" %c", &sym); /* the space skips the space or newline before it */
for (row = 1; row <= h; row++)
printRow(row, sym);
return 0;
}
scanf("%c", &sym) without the space reads the space (or newline) that comes after the height, so sym becomes a blank and the "triangle" is invisible. VPL sees no symbols at all and every test fails.
Rung A+ · Input patterns
About 20 minutes; 5–8 per problem. These three are the function-eval shape with one-line bodies, so all your attention goes to the frame: the starter VPL hands you, main reading T and then T cases, one call per case, one printed line per case. Once this frame is automatic, every Rung B problem is only about the function body.
Every real function eval has a section called "How this evaluation is different". In short: the starter gives you only the prototype, an empty main and an empty body; you write both the body and the code in main that reads the input, calls the function, and prints what it returns; the calculation must be done inside the function. The prototype sits above main because main calls the function before the compiler has reached its body: the prototype tells the compiler its name, parameters and return type in advance.
A+1 · Leap year: the whole body is one return
Write the function int isLeap(int y); that returns 1 if y is a leap year and 0 if it is not. A leap year is divisible by 4 and not by 100, or divisible by 400. Then write main: read T, then T years; for each, call isLeap and print the value it returns on its own line.
The calculation must be done inside isLeap, not inside main: main reads the input, calls isLeap, and prints the value it returns. If your program never calls isLeap, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraint: 1 ≤ y ≤ 9999.
Starter (given)
#include <stdio.h>
int isLeap(int y);
int main(void) {
return 0;
}
int isLeap(int y) {
}
Input T, then T years (one per line or space-separated).
Output T lines, each 1 or 0.
3 2024 2023 2000
1 0 1
1 1900
0
2 2100 2400
0 1
4 4 100 400 1
1 0 1 0
1 1996
1
Stuck? First move
Write main first and leave the body as return 0; so it compiles: read t; loop t times; inside, read one year and printf("%d\n", isLeap(y));. Once that runs, replace return 0; with the rule.
Plan in plain words
- Body: return (divisible by 4 AND not by 100) OR divisible by 400.
- main: read t. Repeat t times: read y, print isLeap(y).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int isLeap(int y);
int main(void) {
int t, y;
scanf("%d", &t);
for (int i = 0; i < t; i++) { /* one pass per test case */
scanf("%d", &y);
printf("%d\n", isLeap(y)); /* main reads, calls, prints */
}
return 0;
}
int isLeap(int y) {
/* a comparison is already 1 or 0, so return it directly */
return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}
return y % 4 == 0; passes the sample, then fails Tests 2–4: 1900, 2100 and 100 are divisible by 4 but are not leap years. Tests sit on exactly those years.
A+2 · Absolute difference: two parameters, two values per line
Write the function int absDiff(int a, int b); that returns the distance between a and b, that is |a − b| (never negative). Then write main: read T, then T lines each containing two integers a b; for each line, call absDiff and print the value it returns on its own line.
The calculation must be done inside absDiff, not inside main: main reads the input, calls absDiff, and prints the value it returns. If your program never calls absDiff, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraints: -1000000 ≤ a, b ≤ 1000000. Don't use abs() from a library: write the comparison yourself.
Starter (given)
#include <stdio.h>
int absDiff(int a, int b);
int main(void) {
return 0;
}
int absDiff(int a, int b) {
}
Input T, then T lines a b.
Output T lines, one distance each.
3 5 9 9 5 -3 4
4 4 7
1 7 7
0
2 -10 -2 0 -5
8 5
2 0 0 1000000 -1000000
0 2000000
1 -1000000 1000000
2000000
Stuck? First move
Inside the loop, one scanf("%d %d", &a, &b); reads both numbers of a case. The call passes both: absDiff(a, b). The body is an if: whichever is bigger, subtract the other from it.
Plan in plain words
- Body: if a > b return a − b, otherwise return b − a.
- main: read t. Repeat t times: read a and b, print absDiff(a, b).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int absDiff(int a, int b);
int main(void) {
int t, a, b;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &a, &b); /* two numbers per case, read together */
printf("%d\n", absDiff(a, b));
}
return 0;
}
int absDiff(int a, int b) {
if (a > b)
return a - b;
return b - a;
}
Looping for (i = 0; i <= t; i++). That runs T + 1 times: the extra scanf finds no input, leaves a and b unchanged, and the last answer is printed twice. Test 2 (T = 1) shows it at once. i = 0; i < t or i = 1; i <= t: pick one and always use it.
A+3 · Last digit: main must call it
Write the function int lastDigit(int n); that returns the last decimal digit of n as a non-negative number: 47 → 7, −47 → 7, 100 → 0. Then write main: read T, then T integers; for each, call lastDigit and print the value it returns on its own line.
The calculation must be done inside lastDigit, not inside main: main reads the input, calls lastDigit, and prints the value it returns. If your program never calls lastDigit, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraint: -2147483647 ≤ n ≤ 2147483647.
Starter (given)
#include <stdio.h>
int lastDigit(int n);
int main(void) {
return 0;
}
int lastDigit(int n) {
}
Input T, then T integers (one per line or space-separated).
Output T lines, one digit each.
3 47 100 5
7 0 5
1 0
0
2 -47 -3
7 3
1 2147483647
7
3 10 19 -10
0 9 0
Stuck? First move
In C, % keeps the sign of the left number: -47 % 10 is -7, not 7. So the body first makes n non-negative (if (n < 0) n = -n;), then returns n % 10. Changing n inside the function is safe: it's a copy.
Plan in plain words
- Body: if n is negative, flip its sign. Return n % 10.
- main: read t. Repeat t times: read n, print lastDigit(n).
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int lastDigit(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", lastDigit(n)); /* the call VPL looks for */
}
return 0;
}
int lastDigit(int n) {
if (n < 0)
n = -n; /* -47 % 10 is -7 in C, so drop the sign */
return n % 10;
}
The one-line version, printf("%d\n", n % 10); in main with an empty lastDigit, would print the right digits for the positive tests. It is still wrong for this eval, for the reason in the trap below.
Doing the work in main. The function evals say "The calculation must be done inside …, not inside main. If your program never calls …, you will see a warning when you evaluate." VPL checks your source code for a call to the function, so the warning appears even when every output matches, and the eval is about the function, so that's where the marks are. The safe habit: main contains only scanf, the loop, the call, and printf.
Predict the output · pass-by-value, scope, globals
Lab 5B's debugging and dry-run exercises are all about one question: which variable does this line actually change? Lab evaluations ask it too, because it's quick to check. For each program, write the exact output on paper, then open the answer. Every output below is from a real run.
1. Pass-by-value: a parameter is a new variable that starts as a copy of the argument. Changing it never changes the caller's variable. 2. Nearest declaration wins: inside a function or { } block, a local with the same name as an outer variable hides (shadows) it until the closing brace. 3. A global is one shared variable: every function that uses that name without declaring its own changes the same box.
P1 · The swap that doesn't
#include <stdio.h>
void swap(int a, int b) {
int t = a;
a = b;
b = t;
printf("inside swap: a=%d b=%d\n", a, b);
}
int main(void) {
int a = 3, b = 8;
swap(a, b);
printf("in main: a=%d b=%d\n", a, b);
return 0;
}
Answer
inside swap: a=8 b=3
in main: a=3 b=8
Rule 1. swap exchanges its own copies, prints them, and they vanish when it returns. main's a and b were never touched. (Making a real swap needs pointers, which come later in the course.)
P2 · The ignored return value
#include <stdio.h>
int addTen(int x) {
x = x + 10;
return x;
}
int main(void) {
int a = 5;
addTen(a);
printf("%d\n", a);
a = addTen(a);
printf("%d\n", a);
printf("%d\n", addTen(addTen(a)));
return 0;
}
Answer
5
15
35
Line 1: addTen(a); computes 15 and throws it away, so a is still 5. Line 2: a = addTen(a); stores the 15. Line 3: the inner call gives 25, the outer gives 35; a itself stays 15. This is exactly 5B Debugging Exercise 3's bug (apply_tax(amount); with the result dropped).
P3 · Global vs a local with the same name
#include <stdio.h>
int count = 0; /* global */
void bump(void) {
count++;
}
void fakeBump(void) {
int count = 100; /* local: shadows the global */
count++;
printf("fakeBump sees %d\n", count);
}
int main(void) {
bump();
bump();
fakeBump();
bump();
printf("count = %d\n", count);
return 0;
}
Answer
fakeBump sees 101
count = 3
Rules 2 and 3. Three calls to bump change the global: 0 → 3. Inside fakeBump, the local count hides the global, so count++ changes the local (100 → 101) and the global is untouched.
P4 · A block inside main
#include <stdio.h>
int main(void) {
int x = 1;
if (x > 0) {
int x = 10;
x++;
printf("inner x = %d\n", x);
}
x++;
printf("outer x = %d\n", x);
return 0;
}
Answer
inner x = 11
outer x = 2
Rule 2 works for any { } block, not just functions. The inner x exists only between the braces of the if: it goes 10 → 11 and disappears. The outer x goes 1 → 2. Same mechanism as 5B Debugging Exercise 1.
P5 · One global loop counter, two loops
#include <stdio.h>
int k; /* one global counter, shared by everyone */
int sumTo(int n) {
int s = 0;
for (k = 1; k <= n; k++)
s = s + k;
return s;
}
int main(void) {
for (k = 1; k <= 4; k++)
printf("%d ", sumTo(k));
printf("\n");
return 0;
}
Answer
1 6
Rule 3: main's loop and sumTo's loop share the single global k. Trace it: k = 1, so sumTo(1) runs its loop and leaves k = 2; it returns 1. main does k++ → 3, and 3 ≤ 4, so sumTo(3) returns 6 and leaves k = 4. main does k++ → 5, and the loop ends. Two numbers, not four. (5B Dry-run Exercise 1 is this bug.) The fix: declare a local int k; inside each function.
Rung B · VPL level
About 75–100 minutes; 15–20 per problem, which is the time an eval allows. Five new function evals built like the instructor's six on the lab-eval bank: given prototype, empty main, T cases, the work inside the function, five tests with at least one on an edge (0, 1, negatives, boundaries). None repeats a real eval. Time yourself, and run all five tests before opening the solution.
B1 · Digital root
The digital root of a non-negative integer is found by adding up its digits, then adding up the digits of that sum, and so on, until a single digit is left. For example 942 → 9 + 4 + 2 = 15 → 1 + 5 = 6, so the digital root of 942 is 6. A one-digit number (including 0) is its own digital root.
Write a function int digitalRoot(int n); that returns the digital root of n. Then write a complete C program that reads an integer T, followed by T non-negative integers. For each, call digitalRoot and print the value it returns on its own line.
The calculation must be done inside digitalRoot, not inside main: main reads the input, calls digitalRoot, and prints the value it returns. If your program never calls digitalRoot, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraint: 0 ≤ n ≤ 2147483647.
Starter (given)
#include <stdio.h>
int digitalRoot(int n);
int main(void) {
return 0;
}
int digitalRoot(int n) {
}
Input T, then T non-negative integers (one per line or space-separated).
Output T lines, the digital root of each number, in order.
3 16 942 7
7 6 7
1 0
0
3 9 10 18
9 1 9
2 2147483647 999999999
1 9
4 19 99 100 1000000000
1 9 1 1
Stuck? First move
You already have one round: A2's digit-sum loop. The digital root is "do that round again while the number still has two or more digits", that is, while n >= 10. So the body is a loop around a loop.
Plan in plain words
- While n ≥ 10: sum ← 0; peel every digit of n into sum; n ← sum.
- Return n (now a single digit).
- main: the T-loop: read, call, print.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int digitalRoot(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", digitalRoot(n));
}
return 0;
}
int digitalRoot(int n) {
while (n >= 10) { /* still more than one digit */
int sum = 0;
while (n > 0) { /* one round of digit summing */
sum = sum + n % 10;
n = n / 10;
}
n = sum; /* repeat on the sum */
}
return n;
}
Doing only one round. One digit sum turns 942 into 15 and stops, so Test 1 fails. "Until a single digit is left" always means an outer loop. If you know the shortcut 1 + (n - 1) % 9, it needs a special case for 0 (Test 2); the loop needs none.
B2 · Reverse a number, sign and all
Write a function int reverseNumber(int n); that returns the number whose decimal digits are those of n in reverse order, keeping the sign: 123 → 321, −123 → −321. Zeros at the end of n disappear: 4500 → 54, −4500 → −54, and 0 → 0.
Then write a complete C program that reads an integer T, followed by T integers. For each, call reverseNumber and print the value it returns on its own line.
The calculation must be done inside reverseNumber, not inside main: main reads the input, calls reverseNumber, and prints the value it returns. If your program never calls reverseNumber, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraint: -1000000 ≤ n ≤ 1000000.
Starter (given)
#include <stdio.h>
int reverseNumber(int n);
int main(void) {
return 0;
}
int reverseNumber(int n) {
}
Input T, then T integers (one per line or space-separated).
Output T lines, the reversed number for each, in order.
3 123 4500 7
321 54 7
1 0
0
3 -123 -4500 -7
-321 -54 -7
2 10 1000000
1 1
3 121 987654 -1000000
121 456789 -1
Stuck? First move
The build-up step is rev = rev * 10 + n % 10; followed by n = n / 10;: each step shifts rev one place left and appends the last digit of n. Get it right for positive numbers first, then try −123 by hand (see "Unpack this step").
Plan in plain words
- rev ← 0.
- While n ≠ 0: rev ← rev × 10 + n % 10; n ← n / 10.
- Return rev. (No separate sign handling needed: see the unpack.)
Unpack this step: why the same loop works for negatives
C's / drops the fraction toward zero and % keeps the sign of n: -123 / 10 is −12 and -123 % 10 is −3. So for −123, rev goes −3, −32, −321 and n goes −12, −1, 0. The loop must run while n != 0; n > 0 would never start.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int reverseNumber(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", reverseNumber(n));
}
return 0;
}
int reverseNumber(int n) {
int rev = 0;
while (n != 0) { /* != 0, not > 0: negatives too */
rev = rev * 10 + n % 10; /* for n < 0, n % 10 is negative */
n = n / 10;
}
return rev;
}
while (n > 0), copied from the digit loops for positive numbers. For any negative input the loop never runs and the function returns 0, so Tests 3 and 5 fail. Read the constraint line first: it tells you whether negatives can arrive.
B3 · Perfect number: the function answers, main chooses the words
A positive integer is perfect if it equals the sum of its proper divisors (its positive divisors other than itself). 6 is perfect: 1 + 2 + 3 = 6. 1 has no proper divisors, so its sum is 0 and it is not perfect.
Write a function int isPerfect(int n); that returns 1 if n is perfect and 0 otherwise. Then write a complete C program that reads an integer T, followed by T positive integers. For each, call isPerfect and print YES if it returns 1, NO if it returns 0, on its own line.
The calculation must be done inside isPerfect, not inside main: main reads the input, calls isPerfect, and prints the value it returns. If your program never calls isPerfect, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraints: 1 ≤ T ≤ 20, 1 ≤ n ≤ 100000.
Starter (given)
#include <stdio.h>
int isPerfect(int n);
int main(void) {
return 0;
}
int isPerfect(int n) {
}
Input T, then T positive integers (one per line or space-separated).
Output T lines, each YES or NO.
3 6 10 28
YES NO YES
1 1
NO
2 496 8128
YES YES
4 2 12 495 8127
NO NO NO NO
3 24 6 100000
NO YES NO
Stuck? First move
The function returns a number, not a word: its last line is return sum == n;. The words YES / NO belong in main, in an if (isPerfect(n)). Inside the function, loop d from 1 up to n - 1 and add every d that divides n.
Plan in plain words
- sum ← 0. For d = 1 to n − 1: if n % d = 0, sum ← sum + d.
- Return (sum = n).
- main: T-loop; print YES or NO from the returned value.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int isPerfect(int n);
int main(void) {
int t, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d", &n);
if (isPerfect(n)) /* function answers 1/0; main chooses the words */
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
int isPerfect(int n) {
int sum = 0;
for (int d = 1; d < n; d++) /* proper divisors: strictly less than n */
if (n % d == 0)
sum = sum + d;
return sum == n; /* n = 1: sum is 0, so not perfect */
}
Starting sum at 1 "because 1 divides everything" and looping from 2. That works for every n ≥ 2 but makes 1 perfect (sum 1 = n), so Test 2 fails. The other common slip is d <= n, which adds n itself: then 6, 28 and 496 come out NO (and 1 still comes out YES).
B4 · How many numbers in a range contain a digit?
Write a function int countWithDigit(int lo, int hi, int d); that returns how many integers k with lo ≤ k ≤ hi contain the digit d at least once. A number counts once however many times the digit appears (99 counts once for d = 9). The number 0 contains the digit 0.
Then write a complete C program that reads an integer T, followed by T lines each containing three integers lo hi d. For each line, call countWithDigit and print the value it returns on its own line.
The calculation must be done inside countWithDigit, not inside main: main reads the input, calls countWithDigit, and prints the value it returns. If your program never calls countWithDigit, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraints: 0 ≤ lo ≤ hi ≤ 100000, 0 ≤ d ≤ 9.
Starter (given)
#include <stdio.h>
int countWithDigit(int lo, int hi, int d);
int main(void) {
return 0;
}
int countWithDigit(int lo, int hi, int d) {
}
Input T, then T lines lo hi d.
Output T lines, one count each, in order.
2 1 20 1 10 30 5
11 2
1 0 0 0
1
2 0 9 0 0 10 0
1 2
2 7 7 7 7 7 3
1 0
2 1 100 9 1 1000 0
19 181
Stuck? First move
Solve the inner question first, on paper: "does the single number k contain d?" Copy k into m, peel digits off m, and set a flag found = 1 if one equals d. Then wrap that in for (k = lo; k <= hi; k++) and add 1 to the count when found is 1.
Plan in plain words
- count ← 0. For k = lo to hi:
- m ← k, found ← 0. Do: if m % 10 = d, found ← 1; m ← m / 10. While m ≠ 0.
- If found, count ← count + 1. After the loop, return count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int countWithDigit(int lo, int hi, int d);
int main(void) {
int t, lo, hi, d;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d %d", &lo, &hi, &d);
printf("%d\n", countWithDigit(lo, hi, d));
}
return 0;
}
int countWithDigit(int lo, int hi, int d) {
int count = 0;
for (int k = lo; k <= hi; k++) {
int m = k, found = 0; /* work on a copy: k drives the loop */
do { /* do-while: 0 has the digit 0 */
if (m % 10 == d)
found = 1;
m = m / 10;
} while (m != 0);
if (found)
count++; /* count each number once */
}
return count;
}
Three slips, each caught by a test. Peeling digits off k itself destroys the loop counter (the loop restarts from 0 and may never end). A plain while (m != 0) never looks at 0, so 0 is not counted for d = 0 (Tests 2–3). Adding 1 for every matching digit counts 99 twice (Test 5).
B5 · Binomial coefficient without factorials
Write a function int binomial(int n, int r); that returns C(n, r), the number of ways to choose r items from n. C(n, 0) = C(n, n) = 1; for example C(5, 2) = 10.
Then write a complete C program that reads an integer T, followed by T lines each containing two integers n r. For each line, call binomial and print the value it returns on its own line.
The calculation must be done inside binomial, not inside main: main reads the input, calls binomial, and prints the value it returns. If your program never calls binomial, VPL shows a warning when you evaluate. No prompts, no debug prints.
Constraints: 0 ≤ r ≤ n ≤ 30. Every answer fits in an int (the largest is C(30, 15) = 155117520), but 13! already does not fit in an int and 21! does not fit in a long long, so the formula n! / (r! (n − r)!) cannot be used directly.
Starter (given)
#include <stdio.h>
int binomial(int n, int r);
int main(void) {
return 0;
}
int binomial(int n, int r) {
}
Input T, then T lines n r.
Output T lines, one value each, in order.
3 5 2 6 0 6 6
10 1 1
1 0 0
1
2 30 15 30 1
155117520 30
3 20 10 21 10 25 12
184756 352716 5200300
3 13 6 1 1 30 29
1716 1 30
Stuck? First move
Build the answer in r small steps. Start with result = 1; for i = 1 to r, do result = result * (n - r + i) / i;, multiplying first and dividing second. Make result a long long and return (int) result at the end.
Plan in plain words
- result ← 1 (a long long).
- For i = 1 to r: result ← result × (n − r + i), then ÷ i.
- Return result as an int.
Unpack this step: why each division comes out exact
After step i, result equals C(n − r + i, i), which is a whole number. For C(5, 2): step 1 gives 1 × 4 / 1 = 4 = C(4, 1); step 2 gives 4 × 5 / 2 = 10 = C(5, 2). Writing result * ((n - r + i) / i) instead would divide first and lose the fraction.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int binomial(int n, int r);
int main(void) {
int t, n, r;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &n, &r);
printf("%d\n", binomial(n, r));
}
return 0;
}
int binomial(int n, int r) {
long long result = 1; /* long long: the middle steps get big */
for (int i = 1; i <= r; i++)
result = result * (n - r + i) / i; /* stays exact: equals C(n-r+i, i) */
return (int) result;
}
Using factorials. With an int factorial, 13! overflows silently and Test 5 prints garbage; with a long long factorial, 30! still overflows and Test 3 fails. Even this method passes about 2.3 × 109 on the way to C(30, 15), which is just over the int limit: that is why result is a long long.
Rung C · Beyond the eval (optional)
These are the old lab-sheet-plus-twist problems: longer than any eval we've seen. Do them after B, if time allows; they build fluency for the end-semester lab exam. About 3½ hours in all. C1–C4 are Lab Sheet 5A/5B practice level (split the work into 2–4 functions, main only coordinates). C5–C8 are at the level of 5B's later practice problems and its challenge problem: more functions, validation of bad input, and loops that must be guaranteed to stop. Each uses one idea from those sheets without repeating a sheet problem.
C1 · Prime neighbours
Read n. If n is outside 1 to 1 000 000, print Out of range. Otherwise print whether n is prime, the previous prime (largest prime < n, or none), the next prime (smallest prime > n), and the nearer of those two with its distance; on a tie, print both. Use at least three functions: isPrime, prevPrime, nextPrime.
Input One integer n.
Output Out of range, or four lines: n is prime or n is not prime; Previous prime: p (or Previous prime: none); Next prime: q; then Nearest other prime: p (d away), or on a tie Nearest other primes: p and q (both d away).
20
20 is not prime Previous prime: 19 Next prime: 23 Nearest other prime: 19 (1 away)
9
9 is not prime Previous prime: 7 Next prime: 11 Nearest other primes: 7 and 11 (both 2 away)
2
2 is prime Previous prime: none Next prime: 3 Nearest other prime: 3 (1 away)
1000000
1000000 is not prime Previous prime: 999983 Next prime: 1000003 Nearest other prime: 1000003 (3 away)
0
Out of range
Stuck? First move
Write int isPrime(int n) first and test it alone (it's the Lab 4 divisor loop: return 0 as soon as a divisor is found, return 1 after the loop). Then nextPrime(n) is just "start at n + 1 and keep adding 1 while isPrime says no".
Plan in plain words
- isPrime(n): numbers below 2 are not prime. Try d = 2, 3, … while d × d ≤ n; if d divides n, not prime. Otherwise prime.
- nextPrime(n): k ← n + 1; while k is not prime, k ← k + 1; return k.
- prevPrime(n): k ← n − 1; while k ≥ 2: if k is prime return it, else k ← k − 1. Return 0 for "none".
- main: validate n; print prime/not prime; p ← prevPrime(n), q ← nextPrime(n); print both; compare n − p with q − n (if p is 0, q wins).
Unpack this step: why stop at d × d ≤ n?
If n = a × b with both factors bigger than √n, then a × b > n, which is impossible. So every non-prime has a divisor ≤ √n, and checking up to there is enough. Writing d * d <= n avoids calling sqrt.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* 1 if n is prime, 0 otherwise */
int isPrime(int n) {
int d;
if (n < 2)
return 0;
for (d = 2; d * d <= n; d++)
if (n % d == 0)
return 0;
return 1;
}
/* smallest prime strictly greater than n */
int nextPrime(int n) {
int k = n + 1;
while (!isPrime(k))
k++;
return k;
}
/* largest prime strictly less than n, or 0 if there is none */
int prevPrime(int n) {
int k = n - 1;
while (k >= 2) {
if (isPrime(k))
return k;
k--;
}
return 0;
}
int main(void) {
int n, p, q;
scanf("%d", &n);
if (n < 1 || n > 1000000) {
printf("Out of range\n");
return 0;
}
if (isPrime(n))
printf("%d is prime\n", n);
else
printf("%d is not prime\n", n);
p = prevPrime(n);
q = nextPrime(n);
if (p == 0)
printf("Previous prime: none\n");
else
printf("Previous prime: %d\n", p);
printf("Next prime: %d\n", q);
if (p == 0 || q - n < n - p)
printf("Nearest other prime: %d (%d away)\n", q, q - n);
else if (n - p < q - n)
printf("Nearest other prime: %d (%d away)\n", p, n - p);
else
printf("Nearest other primes: %d and %d (both %d away)\n", p, q, n - p);
return 0;
}
Forgetting if (n < 2) return 0;. Without it the loop never runs for 0 and 1, so the function returns 1 and calls them prime.
C2 · Fraction calculator: GCD and LCM as helpers
Read two fractions written as a/b c/d. Numerators must be ≥ 0 and denominators > 0; otherwise print Error: need numerators >= 0 and denominators > 0. Print the sum and the product, each in lowest terms, and as a plain integer when the denominator becomes 1. Use functions gcd, lcm (which calls gcd) and printReduced(num, den).
Input Two fractions on one line, like 1/6 1/4.
Output The error line, or two lines: Sum = s and Product = p, where each of s and p is num/den in lowest terms, or just num if the denominator is 1.
1/6 1/4
Sum = 5/12 Product = 1/24
3/4 5/4
Sum = 2 Product = 15/16
2/3 1/0
Error: need numerators >= 0 and denominators > 0
0/5 0/7
Sum = 0 Product = 0
7/1 3/1
Sum = 10 Product = 21
Stuck? First move
Read all four numbers in one go: scanf("%d/%d %d/%d", &a, &b, &c, &d);. Then write gcd (Euclid, from Lab 4) as its own function. Everything else is arithmetic on its result.
Plan in plain words
- gcd(a, b): while b ≠ 0: r ← a % b, a ← b, b ← r. Return a.
- lcm(a, b) = a / gcd(a, b) × b.
- printReduced(num, den): g ← gcd(num, den); divide both by g; print "num" if den is 1, else "num/den".
- main: read and validate. L ← lcm(b, d). Sum numerator = a × (L / b) + c × (L / d) over L. Product = a × c over b × d. Print the label, then call printReduced.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
/* Euclid: greatest common divisor of a, b >= 0 */
int gcd(int a, int b) {
int r;
while (b != 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
int lcm(int a, int b) {
return a / gcd(a, b) * b; /* divide first: smaller numbers */
}
/* prints num/den in lowest terms, or just the integer if den becomes 1 */
void printReduced(int num, int den) {
int g = gcd(num, den);
num = num / g;
den = den / g;
if (den == 1)
printf("%d\n", num);
else
printf("%d/%d\n", num, den);
}
int main(void) {
int a, b, c, d, L, sumNum;
scanf("%d/%d %d/%d", &a, &b, &c, &d);
if (b <= 0 || d <= 0 || a < 0 || c < 0) {
printf("Error: need numerators >= 0 and denominators > 0\n");
return 0;
}
L = lcm(b, d);
sumNum = a * (L / b) + c * (L / d);
printf("Sum = "); /* a label the statement asks for, not a prompt */
printReduced(sumNum, L);
printf("Product = ");
printReduced(a * c, b * d);
return 0;
}
Test 4 is the all-zero edge case: gcd(0, 35) = 35, so 0/35 reduces to 0. printf("Sum = "); is not a prompt: it is part of the required output, printed after all input has been read.
Inside printReduced, dividing num by g and then computing gcd(num, den) again for den. Compute g once, before changing either number.
C3 · Number report: four digit functions
Read n (0 ≤ n ≤ 99999, else print Out of range). Print its number of digits, its reverse, whether it is a palindrome, and whether it is an Armstrong number (equal to the sum of its digits each raised to the power of the number of digits, e.g. 153 = 1³ + 5³ + 3³). Write countDigits, reverseNum, isPalindrome (using reverseNum), power, and isArmstrong (using countDigits and power). 0 has 1 digit.
Input One integer n.
Output Out of range, or four lines: Digits: k, Reversed: r, Palindrome: yes or no, Armstrong: yes or no.
153
Digits: 3 Reversed: 351 Palindrome: no Armstrong: yes
1200
Digits: 4 Reversed: 21 Palindrome: no Armstrong: no
0
Digits: 1 Reversed: 0 Palindrome: yes Armstrong: yes
12321
Digits: 5 Reversed: 12321 Palindrome: yes Armstrong: no
100000
Out of range
Stuck? First move
Write the five first lines (signatures) before any bodies: int countDigits(int n), int reverseNum(int n), int isPalindrome(int n), int power(int base, int exp), int isArmstrong(int n). Then fill the easiest, reverseNum: rev = rev * 10 + n % 10 in the digit loop.
Plan in plain words
- countDigits: count how many times you can divide by 10, doing it at least once (so 0 gives 1).
- reverseNum: digit loop building rev = rev × 10 + last digit.
- isPalindrome: reverse equals the number.
- power: multiply 1 by base, exp times.
- isArmstrong: k ← countDigits(n); add power(digit, k) over every digit (again at least once, for 0); compare with n.
- main: validate, then one printf per function.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int countDigits(int n) {
int count = 0;
do { /* do-while so that 0 counts as 1 digit */
count++;
n = n / 10;
} while (n > 0);
return count;
}
int reverseNum(int n) {
int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
return rev;
}
int isPalindrome(int n) {
return reverseNum(n) == n; /* a comparison is already 1 or 0 */
}
int power(int base, int exp) {
int result = 1, i;
for (i = 1; i <= exp; i++)
result = result * base;
return result;
}
int isArmstrong(int n) {
int k = countDigits(n);
int sum = 0, m = n;
do {
sum = sum + power(m % 10, k);
m = m / 10;
} while (m > 0);
return sum == n;
}
int main(void) {
int n;
scanf("%d", &n);
if (n < 0 || n > 99999) {
printf("Out of range\n");
return 0;
}
printf("Digits: %d\n", countDigits(n));
printf("Reversed: %d\n", reverseNum(n));
if (isPalindrome(n))
printf("Palindrome: yes\n");
else
printf("Palindrome: no\n");
if (isArmstrong(n))
printf("Armstrong: yes\n");
else
printf("Armstrong: no\n");
return 0;
}
Why a do … while? A plain while (n > 0) loop never runs for 0, so countDigits(0) would return 0 and isArmstrong(0) would compare against k = 0. The do version always runs the body once.
Destroying the input: running the digit loop on n itself inside main, then comparing with n (now 0). In a separate function this can't happen: the function works on a copy. 1200 reversed is 21, not 0021; an integer has no leading zeros.
C4 · Counting calculator: a command loop
The input is a sequence of commands. Each starts with a choice number: 1 n prints n! = value; 2 n r prints P(n,r) = value; 3 n r prints C(n,r) = value; 4 prints Bye and ends the program. The last command is always 4. Require 0 ≤ n ≤ 20 (20! is the largest factorial that fits in a long long) and 0 ≤ r ≤ n: if n is out of range print Invalid: need 0 <= n <= 20, otherwise if r is out of range print Invalid: need 0 <= r <= n. Any other choice (with no numbers after it) prints Unknown choice. Use factorial, nPr, nCr and validNR functions.
(A terminal version would print a menu each time. VPL feeds the choices straight in, so there is no menu to print: the program prints only results.)
Input Commands separated by spaces or newlines, ending with 4.
Output One line per command, in order, ending with Bye.
1 5 3 5 2 2 10 3 4
5! = 120 C(5,2) = 10 P(10,3) = 720 Bye
3 4 6 7 1 21 4
Invalid: need 0 <= r <= n Unknown choice Invalid: need 0 <= n <= 20 Bye
1 20 3 20 10 4
20! = 2432902008176640000 C(20,10) = 184756 Bye
4
Bye
1 0 2 5 0 3 5 5 4
0! = 1 P(5,0) = 1 C(5,5) = 1 Bye
Stuck? First move
Write main's skeleton first, with no maths in it: scanf("%d", &choice); while (choice != 4) { … scanf("%d", &choice); }. Get that loop running with empty branches. Then write long long factorial(int n).
Plan in plain words
- factorial(n): f ← 1; multiply by 2, 3, …, n. Return it as a long long.
- nPr = n! / (n − r)!. nCr = nPr / r!.
- validNR(n, r): print the right message and return 0 if n is outside 0..20 or r outside 0..n; otherwise return 1.
- main: command loop. Inside: read the numbers the choice needs, then if validNR(…) print the result.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
long long factorial(int n) {
long long f = 1;
int i;
for (i = 2; i <= n; i++)
f = f * i;
return f;
}
long long nPr(int n, int r) {
return factorial(n) / factorial(n - r);
}
long long nCr(int n, int r) {
return nPr(n, r) / factorial(r);
}
/* 1 if 0 <= r <= n <= 20, else prints why and returns 0 */
int validNR(int n, int r) {
if (n < 0 || n > 20) {
printf("Invalid: need 0 <= n <= 20\n");
return 0;
}
if (r < 0 || r > n) {
printf("Invalid: need 0 <= r <= n\n");
return 0;
}
return 1;
}
int main(void) {
int choice, n, r;
scanf("%d", &choice); /* no menu, no prompt: choices just arrive */
while (choice != 4) {
if (choice == 1) {
scanf("%d", &n);
if (validNR(n, 0))
printf("%d! = %lld\n", n, factorial(n));
} else if (choice == 2 || choice == 3) {
scanf("%d %d", &n, &r);
if (validNR(n, r)) {
if (choice == 2)
printf("P(%d,%d) = %lld\n", n, r, nPr(n, r));
else
printf("C(%d,%d) = %lld\n", n, r, nCr(n, r));
}
} else {
printf("Unknown choice\n");
}
scanf("%d", &choice); /* read the next choice at the bottom */
}
printf("Bye\n");
return 0;
}
Test 4 is a session with no work at all (just 4): the loop body never runs and only Bye is printed. Test 5 sits on the edges 0! and r = 0, r = n.
Returning int from factorial: 13! = 6 227 020 800 is already too big for an int, and C gives no error, just a wrong number. Use long long and %lld everywhere the value travels (Test 3 has 20!).
C5 · Cube root by Newton's method
Without math.h, approximate the cube root of a real number a (which may be negative). Start from the guess x = 1 and repeat the Newton step
xnew = x − (x³ − a) / (3x²)
printing every new guess. Stop when two consecutive guesses differ by less than the tolerance, or after 100 iterations (then print (stopped after 100 iterations)). Then print the root and a check (root cubed). Validate first: tolerance ≤ 0 → Error: tolerance must be positive; then a = 0 → print Cube root of 0 is 0 and stop.
Input Two real numbers: a and the tolerance.
Output One of the two short messages, or one line iter k: x = guess per step (6 decimals), then Cube root of a is about root and Check: root cubed = value (6 decimals; a printed with %g).
27 0.000001
iter 1: x = 9.666667 iter 2: x = 6.540758 iter 3: x = 4.570877 iter 4: x = 3.478019 iter 5: x = 3.062689 iter 6: x = 3.001274 iter 7: x = 3.000001 iter 8: x = 3.000000 Cube root of 27 is about 3.000000 Check: 3.000000 cubed = 27.000000
-8 0.000001
iter 1: x = -2.000000 iter 2: x = -2.000000 Cube root of -8 is about -2.000000 Check: -2.000000 cubed = -8.000000
10 0
Error: tolerance must be positive
0 0.001
Cube root of 0 is 0
1 0.000001
iter 1: x = 1.000000 Cube root of 1 is about 1.000000 Check: 1.000000 cubed = 1.000000
Stuck? First move
Name the pieces as functions first: double absVal(double x) (you need |difference| and can't use fabs), double newtonStep(double x, double a) (one line: the formula), and double cubeRoot(double a, double tol) (the loop). The loop keeps two variables, x (current guess) and next.
Plan in plain words
- main: read a and tol; handle tol ≤ 0 and a = 0 and stop.
- cubeRoot: x ← 1. Repeat up to 100 times: next ← newtonStep(x, a); print it; if |next − x| < tol, return next; else x ← next.
- main: print the root and root × root × root.
Unpack this step: where does the Newton formula come from?
We want a zero of f(x) = x³ − a. Newton slides down the tangent line at x to where it hits zero: x − f(x)/f′(x), and f′(x) = 3x². You only need the formula to code it; the calculus is optional.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
double absVal(double x) {
if (x < 0)
return -x;
return x;
}
/* one Newton step for f(x) = x^3 - a: x - f(x)/f'(x) */
double newtonStep(double x, double a) {
return x - (x * x * x - a) / (3 * x * x);
}
/* prints each iteration; returns the approximate cube root of a */
double cubeRoot(double a, double tol) {
double x = 1.0, next; /* starting guess */
int iter;
for (iter = 1; iter <= 100; iter++) {
next = newtonStep(x, a);
printf("iter %2d: x = %.6f\n", iter, next);
if (absVal(next - x) < tol)
return next; /* two guesses agree: done */
x = next;
}
printf("(stopped after 100 iterations)\n");
return x;
}
int main(void) {
double a, tol, root;
scanf("%lf %lf", &a, &tol);
if (tol <= 0) {
printf("Error: tolerance must be positive\n");
return 0;
}
if (a == 0) {
printf("Cube root of 0 is 0\n");
return 0;
}
root = cubeRoot(a, tol);
printf("Cube root of %g is about %.6f\n", a, root);
printf("Check: %.6f cubed = %.6f\n", root, root * root * root);
return 0;
}
Why the a == 0 case is separate: from x = 1 the guesses for 0 shrink by only a third each step, so convergence is slow. Special-casing it is cleaner. The 100-iteration cap is the guarantee the loop ends whatever happens. Test 5 (a = 1) stops after one step, because the first guess is already right.
Stopping on next == x. Two doubles computed differently are rarely exactly equal, so that loop may never end. Always compare the size of the difference with a tolerance.
C6 · Is my dice generator fair?
Without rand(), simulate die rolls with the Park–Miller generator: keep a global long long state; each call does state = (16807 * state) % 2147483647; a die face is state % 6 + 1. Read a seed (1 to 2147483646) and a number of rolls n ≥ 1; on bad input print Error: invalid seed or roll count. Print the first (up to) 10 rolls, the count of each face, and the chi-square statistic
χ² = Σ over the six faces of (observed − expected)² / expected, expected = n/6
with 2 decimals. Verdict: if n < 30, too few rolls (need at least 30); else if χ² < 11.07, consistent with a fair die; else suspicious.
Input Two integers: the seed and n.
Output The error line, or four lines: First rolls: r1 r2 …; Counts: 1:c1 2:c2 3:c3 4:c4 5:c5 6:c6 (expected E each) with E to 1 decimal; Chi-square = X; Verdict: ….
42 6000
First rolls: 1 2 6 6 3 4 6 3 3 4 Counts: 1:1002 2:1005 3:1030 4:1034 5:982 6:947 (expected 1000.0 each) Chi-square = 5.22 Verdict: consistent with a fair die
7 12
First rolls: 2 2 1 6 2 2 1 5 2 2 Counts: 1:2 2:6 3:1 4:0 5:2 6:1 (expected 2.0 each) Chi-square = 11.00 Verdict: too few rolls (need at least 30)
0 100
Error: invalid seed or roll count
1 1
First rolls: 2 Counts: 1:0 2:1 3:0 4:0 5:0 6:0 (expected 0.2 each) Chi-square = 5.00 Verdict: too few rolls (need at least 30)
2147483646 30
First rolls: 1 1 3 6 4 6 2 6 3 1 Counts: 1:7 2:4 3:5 4:4 5:5 6:5 (expected 5.0 each) Chi-square = 1.20 Verdict: consistent with a fair die
Stuck? First move
The generator must remember its state between calls, which a local variable can't do, so this is the one place a global is the right tool. Write long long state; above everything, then void seedRand(long long seed) and long long nextRand(void). Print 10 values of nextRand() % 6 + 1 before writing anything else.
Plan in plain words
- Functions: seedRand, nextRand, rollDie (= nextRand() % 6 + 1), chiTerm(observed, expected) = (observed − expected)² / expected.
- main: read and validate seed and n; seed the generator.
- Loop n times: face ← rollDie(); print it if among the first 10 (the label goes with the first one); add 1 to that face's counter (six counters, chosen with a
switch). - expected ← n / 6.0; χ² ← sum of six chiTerm calls; print counts, χ², verdict.
Unpack this step: what is 11.07?
χ² measures how far the counts are from perfectly even (0 = perfectly even). For six faces, a truly fair die gives χ² above 11.07 only 5% of the time, so a bigger value is "suspicious". It's a standard table value; you only need to compare against it. Below about 30 rolls the test isn't meaningful, hence that check.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
long long state; /* the generator's memory between calls */
void seedRand(long long seed) {
state = seed;
}
/* Park-Miller generator: next state in 1 .. 2147483646 */
long long nextRand(void) {
state = (16807 * state) % 2147483647;
return state;
}
int rollDie(void) {
return nextRand() % 6 + 1;
}
/* one face's contribution to the chi-square statistic */
double chiTerm(int observed, double expected) {
double diff = observed - expected;
return diff * diff / expected;
}
int main(void) {
long long seed;
int n, i, face;
int c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0;
double expected, chi;
scanf("%lld %d", &seed, &n);
if (seed < 1 || seed > 2147483646 || n < 1) {
printf("Error: invalid seed or roll count\n");
return 0;
}
seedRand(seed);
for (i = 1; i <= n; i++) {
face = rollDie();
if (i == 1)
printf("First rolls: %d", face); /* label goes with the first roll */
else if (i <= 10)
printf(" %d", face);
switch (face) {
case 1: c1++; break;
case 2: c2++; break;
case 3: c3++; break;
case 4: c4++; break;
case 5: c5++; break;
case 6: c6++; break;
}
}
printf("\n");
expected = n / 6.0;
printf("Counts: 1:%d 2:%d 3:%d 4:%d 5:%d 6:%d (expected %.1f each)\n",
c1, c2, c3, c4, c5, c6, expected);
chi = chiTerm(c1, expected) + chiTerm(c2, expected) + chiTerm(c3, expected)
+ chiTerm(c4, expected) + chiTerm(c5, expected) + chiTerm(c6, expected);
printf("Chi-square = %.2f\n", chi);
if (n < 30)
printf("Verdict: too few rolls (need at least 30)\n");
else if (chi < 11.07)
printf("Verdict: consistent with a fair die\n");
else
printf("Verdict: suspicious\n");
return 0;
}
Test 2 shows why the n < 30 rule exists: with 12 rolls χ² = 11.00 is meaningless noise. Test 5 sits exactly on n = 30.
Writing int state. 16807 * state reaches about 3.6 × 1013, far beyond an int, and the overflow silently produces a different (and bad) sequence. The state and the multiplication need long long.
C7 · Date calculator: functions built on functions
Read two dates, each as d m y (years 1900 to 2100). For each valid date print its day number within its year and its weekday; if a date is invalid, print Invalid date: d/m/y and stop. Finally print the number of days between the two dates (never negative). Leap years: divisible by 4 and not by 100, or divisible by 400. 1 January 1900 was a Monday.
Input Six integers: d m y for the first date, then for the second.
Output For each date read, d/m/y is day k of y, a Weekday (or Invalid date: d/m/y, and nothing after it). If both are valid, a last line Days between: g.
3 11 2026 15 8 1947
3/11/2026 is day 307 of 2026, a Tuesday 15/8/1947 is day 227 of 1947, a Friday Days between: 28935
1 3 2000 28 2 2000
1/3/2000 is day 61 of 2000, a Wednesday 28/2/2000 is day 59 of 2000, a Monday Days between: 2
29 2 1900 1 1 2000
Invalid date: 29/2/1900
1 1 1900 31 12 2100
1/1/1900 is day 1 of 1900, a Monday 31/12/2100 is day 365 of 2100, a Friday Days between: 73413
15 8 1947 31 4 2026
15/8/1947 is day 227 of 1947, a Friday Invalid date: 31/4/2026
Stuck? First move
Build from the bottom: int isLeap(int y) (one line), then int daysInMonth(int m, int y) which calls isLeap. Test those two on Feb 1900 (28), Feb 2000 (29) and April (30) before writing anything else. Every later function is a loop over these.
Plan in plain words
- isLeap(y); daysInMonth(m, y).
- isValidDate(d, m, y): year in range, month 1–12, 1 ≤ d ≤ daysInMonth(m, y).
- dayOfYear(d, m, y) = d + days in all earlier months of that year.
- daysSince1900(d, m, y) = 365 or 366 for every full year from 1900 up to y − 1, plus dayOfYear − 1 (so 1/1/1900 is day 0).
- Weekday = daysSince1900 % 7, where 0 is Monday; a
switchprints the name. - readDate(): read, validate, print the line, return the day count (or −1 if invalid). main calls it twice and prints |difference|.
Unpack this step: why does % 7 give the weekday?
Weekdays repeat every 7 days. Day 0 (1/1/1900) is Monday, so days 7, 14, … are Mondays too: any day count with remainder 0 is a Monday, remainder 1 a Tuesday, and so on.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
int isLeap(int y) {
return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}
int daysInMonth(int m, int y) {
if (m == 2) {
if (isLeap(y))
return 29;
return 28;
}
if (m == 4 || m == 6 || m == 9 || m == 11)
return 30;
return 31;
}
int isValidDate(int d, int m, int y) {
if (y < 1900 || y > 2100)
return 0;
if (m < 1 || m > 12)
return 0;
if (d < 1 || d > daysInMonth(m, y))
return 0;
return 1;
}
/* 1 for 1 January, 365 or 366 for 31 December */
int dayOfYear(int d, int m, int y) {
int total = d, k;
for (k = 1; k < m; k++)
total = total + daysInMonth(k, y);
return total;
}
/* days since 1/1/1900 (which counts as day 0) */
int daysSince1900(int d, int m, int y) {
int total = 0, yr;
for (yr = 1900; yr < y; yr++) {
if (isLeap(yr))
total = total + 366;
else
total = total + 365;
}
return total + dayOfYear(d, m, y) - 1;
}
/* 1/1/1900 was a Monday */
void printWeekday(int days) {
switch (days % 7) {
case 0: printf("Monday"); break;
case 1: printf("Tuesday"); break;
case 2: printf("Wednesday"); break;
case 3: printf("Thursday"); break;
case 4: printf("Friday"); break;
case 5: printf("Saturday"); break;
case 6: printf("Sunday"); break;
}
}
/* reads one date; returns its day count, or -1 if invalid */
int readDate(void) {
int d, m, y, days;
scanf("%d %d %d", &d, &m, &y);
if (!isValidDate(d, m, y)) {
printf("Invalid date: %d/%d/%d\n", d, m, y);
return -1;
}
days = daysSince1900(d, m, y);
printf("%d/%d/%d is day %d of %d, a ", d, m, y, dayOfYear(d, m, y), y);
printWeekday(days);
printf("\n");
return days;
}
int main(void) {
int first, second, gap;
first = readDate();
if (first < 0)
return 0;
second = readDate();
if (second < 0)
return 0;
gap = second - first;
if (gap < 0)
gap = -gap;
printf("Days between: %d\n", gap);
return 0;
}
Weekdays, day numbers and gaps were cross-checked against Python's datetime module. 1900 is divisible by 100 but not 400, so it is not a leap year and 29/2/1900 is rejected (Test 3). Test 5 has a valid first date and an invalid second one (April has 30 days).
Leap year as just y % 4 == 0. It's right for every year you've lived through, so tests on recent dates pass, but 1900 and 2100 come out wrong. Testers pick exactly those years.
C8 · Reverse-and-add to a palindrome
Reverse-and-add: replace a number by itself plus its reverse (e.g. 87 → 87 + 78 = 165 → 165 + 561 = 726 → … ). Most numbers soon reach a palindrome. Read a range L R (1 ≤ L ≤ R ≤ 10000, else print Error: bad range). For each number in the range, count the steps needed to reach a palindrome (0 if it already is one). Give up on a number after 30 steps, or once the value passes 1015, and print Gave up on n. Then print the three counts, and the number that needed the most steps (the smallest such number on a tie), with its step count and the palindrome it reached.
Input Two integers L R.
Output The error line, or: one Gave up on n line per number given up on, in order; then Already palindromes: a, Became palindromes: b, Gave up: g, and Hardest: n took s steps -> p.
80 100
Already palindromes: 2 Became palindromes: 19 Gave up: 0 Hardest: 89 took 24 steps -> 8813200023188
190 200
Gave up on 196 Already palindromes: 1 Became palindromes: 9 Gave up: 1 Hardest: 193 took 8 steps -> 233332
5 5
Already palindromes: 1 Became palindromes: 0 Gave up: 0 Hardest: 5 took 0 steps -> 5
0 5
Error: bad range
1 10
Already palindromes: 9 Became palindromes: 1 Gave up: 0 Hardest: 10 took 1 steps -> 11
Stuck? First move
You need long long: 89 needs 24 steps and ends at a 13-digit number. Start with long long reverseNum(long long n) (C3's function with a bigger type) and int isPal(long long n). Then int stepsToPal(long long n) returns the step count, or −1 to mean "gave up".
Plan in plain words
- stepsToPal(n): steps ← 0. While n is not a palindrome: if steps = 30 or n > 1015, return −1; n ← n + reverse(n); steps ← steps + 1. Return steps.
- applySteps(n, k): do reverse-and-add k times and return the value (used to print the hardest one's palindrome).
- main: validate. For n = L..R: s ← stepsToPal(n). If −1: count and print "Gave up". Else count as "already" (s = 0) or "became", and if s beats the record, store n and s.
- Print the three counts and the record holder.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#define MAX_STEPS 30
#define LIMIT 1000000000000000LL /* 10^15: stay far from long long's limit */
long long reverseNum(long long n) {
long long rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
return rev;
}
int isPal(long long n) {
return reverseNum(n) == n;
}
/* number of reverse-and-add steps until a palindrome; -1 if we give up */
int stepsToPal(long long n) {
int steps = 0;
while (!isPal(n)) {
if (steps == MAX_STEPS || n > LIMIT)
return -1;
n = n + reverseNum(n);
steps++;
}
return steps;
}
/* the value after k reverse-and-add steps */
long long applySteps(long long n, int k) {
int i;
for (i = 1; i <= k; i++)
n = n + reverseNum(n);
return n;
}
int main(void) {
int L, R, n, s;
int already = 0, became = 0, gaveUp = 0;
int hardest = 0, hardestSteps = -1;
scanf("%d %d", &L, &R);
if (L < 1 || R > 10000 || L > R) {
printf("Error: bad range\n");
return 0;
}
for (n = L; n <= R; n++) {
s = stepsToPal(n);
if (s == -1) {
gaveUp++;
printf("Gave up on %d\n", n);
} else {
if (s == 0)
already++;
else
became++;
if (s > hardestSteps) {
hardestSteps = s;
hardest = n;
}
}
}
printf("Already palindromes: %d\n", already);
printf("Became palindromes: %d\n", became);
printf("Gave up: %d\n", gaveUp);
if (hardestSteps >= 0)
printf("Hardest: %d took %d steps -> %lld\n",
hardest, hardestSteps, applySteps(hardest, hardestSteps));
return 0;
}
196 is the famous number that has never been shown to reach a palindrome (Test 2). All counts were cross-checked with a separate Python script using the same give-up rule.
No give-up rule. For 196 the loop never finds a palindrome; the value just grows until it overflows long long and turns into garbage. Any "repeat until" loop in an evaluation needs a second way out.
Self-test before moving on
- You can do B2 and B4 from the starter in under 20 minutes each, without opening a hint, with all 5 tests passing on your first full run (use the test script) and no prompt or debug print in the file.
- You can say in one sentence why the
main-only answer to A+3 gets a warning even when every output matches. - You get all five predict-the-output items right and can say which of the three rules each one uses.
- Optional, for the end-semester lab exam: you can do C4 in under 25 minutes after only reading "Stuck? First move".
If item 3 is shaky, do the dry-run drill first; it's quicker than another program.
"Here is my C solution to a VPL function evaluation: [paste statement + code]. Don't rewrite it. Tell me: does any of the calculation happen in main instead of the function, does it print anything other than the required output, and give me one edge-case input (T = 1, 0, a negative, a boundary value) that would break it."
"Write me a new predict-the-output C program, under 20 lines, that tests pass-by-value and a global shadowed by a local. Don't tell me the answer until I reply with mine." Then compile its program yourself to check its answer: AI predictions of output are sometimes wrong.