C / BCSZC313 / Modules 02–11

Make C come back.
One complete answer at a time.

Trace the state. Repair the bug. Write the program. Explain why it works. A substantial practice course that takes you from forgotten syntax to pointers, memory, files and integrated cases.

90 original questions10 modules72 runnable referencesNo login

Choose your next session.

The full question bank

All 90 original questions, organised by the ten course modules. Start with a foundation question, then write or debug, then explain a boundary case. Every question includes hints, a full answer and a self-marking checklist.

Attempt → compare → rewrite

Find a question.

Download C programs ↓
90 of 90 questions shown

Drafts and self-ratings save on this browser only. Export before changing devices.

02

Computing & algorithms

Inputs, decisions, flowcharts, execution · 4 questions

M2-01Judge every claimFoundation~8 minFrom source text to a running processNot attempted

Judge EACH statement independently as true or false, and correct every false statement in one sentence. Assume an ordinary Unix command-line C toolchain. A. Saving a file named hello.c is enough to make the operating system execute its C statements. B. A compiler can accept an individual source file even though linking later fails because a called function has no definition in the linked program or libraries. C. A successful compile and link prove that every input will produce the intended answer. D. When an executable is launched, the operating system creates a process and arranges resources such as its address space and standard input/output. E. Changing hello.c after a successful build changes the already-built executable automatically. Then give the source → executable → running process sequence. Distinguish the roles of CPU, main memory, persistent storage and operating system; do not just list their names.

Link to this question
Saves in this browser
Hint 1

Separate the file containing instructions from the executable produced by the tools.

Hint 2

A source change needs another build. A successful build checks some rules, not the meaning of every calculation.

Worked solution & self-marking checklist

A false; B true; C false; D true; E false. Building a program and running it are separate operations.

Reason it through

  1. A: false. Source text must normally be translated and linked before the resulting executable can be launched; the .c suffix does not make source directly executable.
  2. B: true. Compilation can translate a call using a declaration; the linker must find a matching external definition. Missing definitions can cause a link error.
  3. C: false. Logical errors and input-dependent runtime faults can survive compilation and linking.
  4. D: true. The OS starts and manages the process; CPU hardware executes machine instructions using data and instructions made available in main memory.
  5. E: false. The source file and executable are distinct stored files. Rebuild, then run the new executable to observe the source change.
  6. Typical pipeline: source on persistent storage → preprocessing → compilation → assembly to object code → linking into an executable → OS loading/starting a process → CPU execution. A compiler driver may hide several stages behind one command.

Common mistakes

  • Confusing a compiler driver with the operating system or CPU.
  • Treating a successful build as a proof of correctness, or assuming the executable reads the source on each run.

Before calling this one solid

  • Judged A–E separately with all five verdicts correct.
  • Explained at least one possible link failure and one possible logic error.
  • Gave an ordered build/run sequence and a distinct role for all four named components.
M2-02Design & integrateFoundation~15 minDesign a sentinel algorithm before writing CNot attempted

A sensor supplies at most 100 integers, each between -100 and 100. A zero ends the sequence; input may instead end at EOF. Count and sum only the positive readings before the first zero. Negative readings are ignored. Print count=K sum=S on one line. Empty input and an immediate zero both produce zero count and zero sum. First write language-independent pseudocode. Then describe a flowchart using Start/End, input/output, process and decision nodes, with labelled yes/no arrows. Finally write a C program and dry-run -4, 7, 3, 0, 9; explicitly state whether 9 is processed. The bounded input guarantees the int sum and count fit.

Link to this question
Saves in this browser
Hint 1

Initialize count and sum before reading any value; every continuing path must return to a fresh read.

Hint 2

Use two separate decisions: whether input ended or the reading is zero, then whether the accepted reading is positive.

Worked solution & self-marking checklist

Repeatedly read a value, stop on zero or EOF, and update both totals only when the value is positive.

Reason it through

  1. Pseudocode: set count=0, sum=0; while a reading is available: if it is zero, stop; if it is positive, add one to count and add the value to sum; output both totals.
  2. Flowchart: Start → initialize totals (process) → read (input) → read succeeded? (decision). No goes to output and End. Yes goes to value=0?; Yes also goes to output and End.
  3. The nonzero path goes to value>0?. Yes goes to update count and sum; No skips the update. Both arrows return to the read node. The sentinel is never counted.
  4. Dry-run: -4 leaves (count,sum)=(0,0); 7 makes (1,7); 3 makes (2,10); 0 ends the loop. The later 9 is not processed. The output is count=2 sum=10.
  5. In the C version scanf returns the number of successful conversions. Comparing it with 1 prevents using x when no integer was read. && stops before the x test on EOF.
Model C answer
#include <stdio.h>
int main(void)
{
    int x;
    int count = 0;
    int sum = 0;
    while (scanf("%d", &x) == 1 && x != 0) {
        if (x > 0) {
            ++count;
            sum += x;
        }
    }
    printf("count=%d sum=%d\n", count, sum);
    return 0;
}

Common mistakes

  • Counting the sentinel, or continuing to read values after it.
  • Returning from an ignored negative reading to a decision without reading again, which can repeat forever.

Before calling this one solid

  • Initialized both accumulators and handled EOF as well as zero.
  • Drew or described all flowchart paths with decisions and loop-back arrows.
  • Correctly traced the ignored negative, two positives, sentinel and unprocessed suffix.
  • Printed the required format for empty, immediate-stop and mixed input.

Reference program checked with GCC and Clang in C17 mode.

M2-03Debug & repairCore~12 minRepair a digit-counting algorithm and justify terminationNot attempted

The pseudocode is intended to count decimal digits in a nonnegative integer, including one digit for 0. Identify both independent defects, repair the algorithm, and show a dry-run for 5070. Explain why your repaired algorithm terminates; a corrected final answer without that reasoning is incomplete. Translate your repair into a standalone C program reading one integer n in 0..1000000000. Print digits=D, or invalid for missing/out-of-range input. Use an explicit special case for zero and a while loop for positive values. The reference uses long for the input so the stated upper bound is within the minimum range guaranteed for that type. Assume every integer token supplied is representable in long.

C
INPUT n
    digits ← 0
    WHILE n > 0
        next ← n DIV 10
        digits ← digits + 1
    END WHILE
    OUTPUT digits
Link to this question
Saves in this browser
Hint 1

For positive values, the variable tested at the loop head must actually move toward zero.

Hint 2

Ask separately what should happen when the initial value is zero. Copying n preserves the original input while the copy is reduced.

Worked solution & self-marking checklist

Reduce a working copy by integer division by 10 on each pass, and count zero as one digit.

Reason it through

  1. Defect 1: next is computed but never assigned to n, so a positive n never changes and the given loop does not terminate.
  2. Defect 2: when n is initially zero, the loop body runs zero times and reports zero digits. Decimal 0 has one digit.
  3. Repair with remaining=n and digits=0: if remaining is zero, set digits=1; otherwise repeatedly count one digit and replace remaining by remaining/10 while remaining>0. Preserve n by reducing the working copy.
  4. For 5070 the post-iteration states (remaining,digits) are (507,1), (50,2), (5,3), (0,4). Thus the result is digits=4.
  5. For every positive remaining, integer division by 10 produces a smaller nonnegative integer. Repeated reductions reach zero, so the loop terminates. The long type can represent the whole input range on every C17 implementation; the digit count is at most 10 and fits in int.
Model C answer
#include <stdio.h>
int main(void)
{
    long n;
    if (scanf("%ld", &n) != 1 || n < 0 || n > 1000000000L) {
        puts("invalid");
        return 0;
    }
    long remaining = n;
    int digits = 0;
    if (remaining == 0) {
        digits = 1;
    }
    while (remaining > 0) {
        ++digits;
        remaining /= 10;
    }
    printf("digits=%d\n", digits);
    return 0;
}

Common mistakes

  • Computing a new value into an unused variable and assuming the old value changed.
  • Fixing nontermination but still reporting zero digits for the input zero.

Before calling this one solid

  • Identified and corrected the missing update and the zero case.
  • Showed all four state changes for 5070.
  • Explained a decreasing nonnegative quantity, not merely that the loop eventually stops.
  • Produced the required outputs for 0, a power of ten and invalid input.

Reference program checked with GCC and Clang in C17 mode.

M2-04ExplainCore~10 minAn algorithm that loses the all-negative caseNot attempted

A proposed algorithm reads exactly three integers a, b and c, sets largest to 0, then replaces largest with each input if that input is larger. It prints largest. Inputs can be negative, zero or positive. Give a concrete failing input and a state-by-state dry-run. Repair the algorithm without assuming a machine-specific smallest integer. State the meaning of largest after processing one input, two inputs and three inputs. Describe the two comparison diamonds and their paths in a repaired flowchart. Include equal values and an all-negative case among your examples. You do not need to write C for this question.

Link to this question
Saves in this browser
Hint 1

A candidate maximum should come from the actual input when every input is allowed to be negative.

Hint 2

After initializing from a, only b and c remain to be compared. A tie does not require changing the maximum value.

Worked solution & self-marking checklist

Initialize largest to a, then compare b and c with it. Zero is an invalid default when zero may exceed every input.

Reason it through

  1. Counterexample: a=-8, b=-3, c=-5. Starting at 0, every comparison with 0 is false, so the algorithm prints 0 even though no input is 0 and the maximum is -3.
  2. Repair: read all three values; set largest=a; if b>largest set largest=b; if c>largest set largest=c; output largest.
  3. Meaning after one value: largest=a is the maximum of the first input alone. After comparing b it is max(a,b). After comparing c it is max(a,b,c). This invariant explains the algorithm.
  4. Flowchart: Start → input a,b,c → largest=a → b>largest?. The Yes arrow updates largest=b; the No arrow skips that box. Both paths merge before c>largest?, whose Yes arrow updates largest=c. Both paths merge before output → End.
  5. For (-8,-3,-5), largest progresses -8 → -3 → -3. For (4,4,1), it stays 4. Using > rather than >= still gives the correct maximum value because equal values need no replacement.

Common mistakes

  • Using zero as a universal initial maximum, which silently fails on all-negative inputs.
  • Using else-if between the b and c comparisons, which may prevent c from being considered after b changes the maximum.

Before calling this one solid

  • Provided an actual all-negative counterexample and traced the faulty state.
  • Initialized from an input and compared both remaining values independently.
  • Stated the invariant after each processed input.
  • Included a correct tie example and explained the merged flowchart paths.
03

C foundations

Types, expressions, conversions, input/output · 10 questions

M3-01Write CFoundation~12 minWrite, compile and run a complete first C programNot attempted

Starting from a blank file, write rectangle.c. Read two integer dimensions width and height, each in 0..100. Print area=A perimeter=P on one line. Print invalid if two integers are not available or either value is outside the allowed range. A zero dimension is valid. No interactive prompt text should be printed. Explain the purpose of the include line, main, declarations, the address-of symbols in scanf and return 0. Give Unix shell commands to show the current directory, list its files, create and enter a practice directory, compile with C17 warnings enabled, and run the program with input 3 4. Include an example using input redirection from an existing input.txt file. Assume every integer token supplied is representable in int.

Link to this question
Saves in this browser
Hint 1

A complete hosted C program needs main. stdio.h declares the input/output library functions.

Hint 2

scanf reports the number of items assigned. Read both dimensions successfully before calculating with either one.

Worked solution & self-marking checklist

Use a checked two-integer read, calculate area and perimeter in int, and build/run the saved source explicitly.

Reason it through

  1. #include <stdio.h> supplies declarations for scanf, printf and puts. int main(void) is the entry function for this hosted program, and braces enclose its body.
  2. Declare each dimension as int. scanf("%d %d", &width, &height) needs addresses so it can store the read values; require its return value to equal 2 before using both dimensions.
  3. Validate 0..100, then compute area=width*height and perimeter=2*(width+height). These bounded results fit even a 16-bit int; zero is deliberately permitted.
  4. printf substitutes decimal values for %d. Its ends the output line. Returning 0 from main reports successful termination to the host environment.
  5. A suitable shell sequence is: pwd; ls; mkdir c-practice; cd c-practice. Save rectangle.c there, then run gcc -std=c17 -Wall -Wextra -pedantic rectangle.c -o rectangle followed by ./rectangle, and type 3 4. To use a prepared file, run ./rectangle < input.txt. These are shell commands, not C statements.
Model C answer
#include <stdio.h>
int main(void)
{
    int width;
    int height;
    if (scanf("%d %d", &width, &height) != 2 ||
        width < 0 || width > 100 || height < 0 || height > 100) {
        puts("invalid");
        return 0;
    }
    int area = width * height;
    int perimeter = 2 * (width + height);
    printf("area=%d perimeter=%d\n", area, perimeter);
    return 0;
}

Common mistakes

  • Copying Java/JS syntax such as public static void main, let or console.log into C.
  • Omitting & for an int destination in scanf, or using unread variables after a failed conversion.

Before calling this one solid

  • Wrote a complete program with the right header and main signature.
  • Checked conversion count and all four range boundaries.
  • Printed exact outputs including the zero-dimension case.
  • Gave working directory/list/create/change/build/run commands and explained input redirection.

Reference program checked with GCC and Clang in C17 mode.

M3-02Judge every claimFoundation~9 minTypes and storage: judge each claimNot attempted

Judge EACH claim independently for standard C17. Explain a correction for every false claim; distinguish a language guarantee from a common implementation choice. A. sizeof(char) is always 1, but that alone does not prove a C byte has exactly 8 bits. B. int is guaranteed to occupy exactly four bytes on every conforming C implementation. C. For an ordinary uninitialized automatic local int, reading it is a reliable way to obtain zero. D. A file-scope int defined without an explicit initializer is zero-initialized before program startup. E. After int score = 5;, a later assignment score = 5.9 changes score into a floating-point variable, as an untyped JavaScript mental model might suggest. F. const int limit = 10; means ordinary assignments to limit are permitted as long as the value remains an int.

Link to this question
Saves in this browser
Hint 1

A declared C object keeps its declared type; conversion changes a value, not the variable into another type.

Hint 2

Separate automatic local initialization from static-storage initialization. const restricts modification through that declared object.

Worked solution & self-marking checklist

A true; B false; C false; D true; E false; F false.

Reason it through

  1. A: true. sizeof counts C bytes, and char occupies one such byte. CHAR_BIT from <limits.h> gives the number of bits per byte; it is at least 8, not necessarily exactly 8.
  2. B: false. C specifies minimum ranges and relationships between integer types, not a universal four-byte int. Inspect a particular implementation when its exact size matters.
  3. C: false. This ordinary automatic local has an indeterminate value. Reading it in a calculation is not a portable default-zero operation and can have undefined behavior; initialize it before use.
  4. D: true. An object with static storage duration, including a file-scope int definition, is initialized to zero when no explicit initializer is supplied.
  5. E: false. score remains int. The representable floating value 5.9 is converted to int by discarding its fractional part, so the assigned value is 5.
  6. F: false. An ordinary assignment to a const-qualified object violates a language constraint. const is about permitted modification, not merely the type of a replacement value.

Common mistakes

  • Learning the size of int from one laptop and treating it as a C-wide rule.
  • Importing automatic zero-initialization or dynamically changing variable types from another language.

Before calling this one solid

  • Gave six separate correct verdicts.
  • Distinguished sizeof units, CHAR_BIT and integer range guarantees.
  • Explained local versus static-storage initialization.
  • Explained both the conversion in E and the modification restriction in F.
M3-03TraceFoundation~9 minDivision happens before assignmentNot attempted

Without running the program, give its exact two output lines. For p and q, state the type of the division operation before explaining the stored double value. Explain the sign and magnitude of r and s using C17 integer division, and check the relationship between quotient, divisor and remainder. Finally explain why changing double p = a / b; to double p = (double)(a / b); does not recover the discarded fraction. All shown divisions have nonzero divisors and small representable results.

C
#include <stdio.h>
int main(void)
{
    int a = 7;
    int b = 2;
    double p = a / b;
    double q = (double)a / b;
    int r = -7 / 2;
    int s = -7 % 2;
    printf("p=%.1f q=%.1f r=%d s=%d\n", p, q, r, s);
    printf("rebuild=%d\n", r * 2 + s);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The destination type of an assignment does not reach backward and change an integer division already performed.

Hint 2

Integer division truncates toward zero. Verify -7 = (quotient)*2 + remainder.

Worked solution & self-marking checklist

p is 3.0, q is 3.5, r is -3 and s is -1; casting after division cannot recover a lost fractional part.

Reason it through

  1. a and b are int, so a/b computes the integer quotient 3 first. Assigning that result to p converts 3 to the double value 3.0.
  2. (double)a converts 7 to double before division. The usual arithmetic conversions convert b to double as well, so q receives 3.5.
  3. C17 integer division truncates toward zero: -7/2 is -3. The corresponding remainder is -1, because -3*2 + (-1) equals -7.
  4. The first printf uses %.1f for one digit after the decimal point and %d for ints. The second calculation reconstructs -7.
  5. (double)(a/b) converts the already-computed integer 3 to double. To keep the fraction, convert an operand before the division, as in q.
Model C answer
#include <stdio.h>
int main(void)
{
    int a = 7;
    int b = 2;
    double p = a / b;
    double q = (double)a / b;
    int r = -7 / 2;
    int s = -7 % 2;
    printf("p=%.1f q=%.1f r=%d s=%d\n", p, q, r, s);
    printf("rebuild=%d\n", r * 2 + s);
    return 0;
}

Expected output

p=3.0 q=3.5 r=-3 s=-1
rebuild=-7

Common mistakes

  • Assuming a double destination forces floating-point evaluation of the right-hand expression.
  • Using floor division for negative integers, or assuming a C remainder must always be nonnegative.

Before calling this one solid

  • Gave both exact output lines.
  • Identified integer versus floating-point division before assignment.
  • Explained truncation toward zero and verified the quotient/remainder identity.
  • Explained the difference between an operand cast and a result cast.

Reference program checked with GCC and Clang in C17 mode.

M3-04Debug & repairCore~12 minRepair both sides of formatted input/outputNot attempted

The broken program should read an int units, a double price and a non-whitespace character grade, even when grade is on the next line. Valid numeric tokens are representable in their destination types. For input 3 2.5 followed by a newline and A, the required output is units=3 price=2.50 grade=A. Print invalid if fewer than three conversions succeed. Identify every address/type/whitespace defect and provide a corrected complete program. Explain why scanf needs %lf for this price while printf uses %.2f. Do not attempt to predict output from the broken program; its mismatched variadic arguments can cause undefined behavior.

C
#include <stdio.h>
int main(void)
{
    int units;
    double price;
    char grade;
    scanf("%d %f%c", units, &price, &grade);
    printf("%d %.2f %s\n", units, price, grade);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

Match scanf conversion specifiers to pointer destination types; match printf specifiers to value types.

Hint 2

A space in a scanf format consumes any run of whitespace, including a newline, before %c reads the next character.

Worked solution & self-marking checklist

Use &units, %lf with &price, whitespace before %c, %c when printing grade, and check that scanf returns 3.

Reason it through

  1. scanf must store into units, so its %d argument must be &units, an int pointer. Passing an uninitialized int value in place of that pointer is invalid.
  2. price is double. scanf %lf expects double*, whereas scanf %f expects float*. Use %lf with &price; these destination types are not interchangeable.
  3. Unlike numeric conversions, %c does not skip leading whitespace. The space before %c consumes separating whitespace so grade receives A rather than the newline or a space.
  4. printf receives values. Use %d for units, %.2f for the double price, and %c for grade, which undergoes integer promotion. %s would require a pointer to a null-terminated character sequence.
  5. Check the conversion count before printing any read value. printf %f consumes a double; a float argument would be promoted to double, which is why its rules differ from scanf pointer destinations.
Model C answer
#include <stdio.h>
int main(void)
{
    int units;
    double price;
    char grade;
    if (scanf("%d %lf %c", &units, &price, &grade) != 3) {
        puts("invalid");
        return 0;
    }
    printf("units=%d price=%.2f grade=%c\n", units, price, grade);
    return 0;
}

Common mistakes

  • Applying scanf format rules to printf without noticing pointer destinations versus promoted values.
  • Using %s for one char or assuming %c automatically skips the previous newline.

Before calling this one solid

  • Fixed all format-type mismatches and the missing address-of.
  • Handled whitespace before grade and checked exactly three conversions.
  • Explained scanf %f/%lf versus printf %f accurately.
  • Did not claim an observed output for the broken program.

Reference program checked with GCC and Clang in C17 mode.

M3-05TraceCore~12 minShort-circuiting is part of the traceNot attempted

Give the exact output, but also show a row for each initialization of a, b, c and d. Each row must list the left operand's value, whether the right operand is evaluated, the result stored, and the current x and y. Explain why this program does not divide by zero. Fully parenthesize the expression initializing d according to C precedence. State the possible numerical results of &&, || and ! in C; importing JavaScript's “return one of the operands” rule would give the wrong model.

C
#include <stdio.h>
int main(void)
{
    int x = 0;
    int y = 4;
    int a = x != 0 && 12 / x > 2;
    int b = y > 0 || ++x > 0;
    int c = x == 0 && ++y > 4;
    int d = 2 + 3 * 4 > 10 && !0;
    printf("a=%d b=%d c=%d d=%d x=%d y=%d\n", a, b, c, d, x, y);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

For &&, a false left operand skips the right; for ||, a true left operand skips it.

Hint 2

Only the increment of y is reached. Arithmetic binds more tightly than comparisons, which bind more tightly than &&.

Worked solution & self-marking checklist

The skipped operations leave x at 0, the reached increment makes y 5, and logical operators store normalized 0 or 1 results.

Reason it through

  1. a: x!=0 is false (0), so 12/x>2 is skipped. a=0, x=0, y=4; no division by zero occurs.
  2. b: y>0 is true (1), so ++x>0 is skipped. b=1, x=0, y=4.
  3. c: x==0 is true (1), so ++y executes and becomes 5; 5>4 is true. c=1, x=0, y=5.
  4. d groups as (((2 + (3 * 4)) > 10) && (!0)). The left comparison is true, the right !0 is 1, and d=1. Neither x nor y changes.
  5. && and || yield int 0 or 1, and ! yields int 0 or 1. They do not return an arbitrary operand value. Each declaration is a separate full expression, so the state changes are well defined.
Model C answer
#include <stdio.h>
int main(void)
{
    int x = 0;
    int y = 4;
    int a = x != 0 && 12 / x > 2;
    int b = y > 0 || ++x > 0;
    int c = x == 0 && ++y > 4;
    int d = 2 + 3 * 4 > 10 && !0;
    printf("a=%d b=%d c=%d d=%d x=%d y=%d\n", a, b, c, d, x, y);
    return 0;
}

Expected output

a=0 b=1 c=1 d=1 x=0 y=5

Common mistakes

  • Evaluating a skipped right operand while constructing the trace.
  • Treating logical results as the original nonzero operand or replacing && with the non-short-circuit operator &.

Before calling this one solid

  • Tracked x and y after each declaration.
  • Explicitly identified both skipped right operands and the reached increment.
  • Parenthesized d correctly and explained the absence of zero division.
  • Printed all six final values with the exact required line.

Reference program checked with GCC and Clang in C17 mode.

M3-06Judge every claimStretch~12 minCan this expression have one guaranteed answer?Not attempted

Judge EACH statement independently, explain the relevant category, and correct false statements. Assume signed int arithmetic unless stated otherwise. No experiment on one compiler can turn undefined behavior into a guaranteed output. A. If i starts at 1, printf("%d %d\n", i++, i++); has one portable output determined by evaluating function arguments left to right. B. Given side-effect-free functions f and g that each return a valid int, C requires f() to run before g() in printf("%d %d\n", f(), g());. C. Overflow of signed int arithmetic is guaranteed to wrap around like a Java int. D. A conforming C implementation may choose whether plain char behaves as signed char or unsigned char, and must document its choice. E. For int a=3, b=2, c=1;, the expression a < b < c means the same as a < b && b < c. In your answer, distinguish undefined behavior, unspecified evaluation order and an implementation-defined choice.

Link to this question
Saves in this browser
Hint 1

Associativity groups operators; it does not impose left-to-right evaluation of function arguments.

Hint 2

For E, evaluate the first relational comparison to 0 or 1, then compare that int with c.

Worked solution & self-marking checklist

A false; B false; C false; D true; E false. These failures have different reasons and must not all be labelled compiler-dependent.

Reason it through

  1. A: false. The two modifications of the same scalar i in different argument expressions are unsequenced relative to one another in C17, producing undefined behavior. Do not give it a predicted output.
  2. B: false. C does not specify which argument expression is evaluated first. With the stated side-effect-free functions, the first conversion still prints f()'s result and the second prints g()'s result; unspecified evaluation order does not swap argument positions.
  3. C: false. A signed arithmetic result outside the representable range has undefined behavior. C does not guarantee Java-style wraparound for signed int.
  4. D: true. Plain char signedness is an implementation-defined choice. Unlike an unspecified order, the implementation must document this choice.
  5. E: false. < associates left to right, so a<b<c means (a<b)<c. For a=3,b=2,c=1, the first comparison 3<2 gives 0, then 0<1 gives 1. The conjunction (3<2)&&(2<1) is 0 because its first comparison is false. Test each intended inequality separately and combine them with &&.
  6. Undefined behavior imposes no requirements for the execution; unspecified behavior permits a choice without a required documented selection; implementation-defined behavior is a documented choice among permitted alternatives.

Common mistakes

  • Giving an output for A because one local run happened to print it.
  • Using the vague word unpredictable for all three categories, or equating operator associativity with evaluation order.

Before calling this one solid

  • Gave five independent correct verdicts.
  • Explained why A is undefined and B merely has unspecified argument order.
  • Distinguished signed overflow from documented plain-char signedness.
  • Expanded the chained comparison and supplied a genuine counterexample to equivalence.
M3-07Write CFoundation~10 minTurn a character digit into a numberNot attempted

Read one non-whitespace character representing a single decimal digit. If it is not in '0'..'9', print invalid. Otherwise interpret it as a quantity, charge 125 cents per item, and print quantity=Q price=D.CC with exactly two digits after the decimal point. For example, character '3' must produce quantity=3 price=3.75. Only the first non-whitespace character is part of this task. Use integer arithmetic for money. Explain why assigning digit directly to an int does not in general produce the intended quantity, why subtraction of '0' works in C, and why you must not hard-code the numeric value 48.

Link to this question
Saves in this browser
Hint 1

A character code and the value represented by a written digit are different things.

Hint 2

C guarantees consecutive increasing codes for the decimal digits. Divide total cents by 100 and take its remainder for the printed parts.

Worked solution & self-marking checklist

Validate the character, compute quantity=digit-'0', and format the integer cents as whole units plus a two-digit remainder.

Reason it through

  1. Read into a char using %c and an address. The leading space in " %c" skips preceding whitespace; a failed conversion is invalid input.
  2. Compare against character constants '0' and '9'. In C, ordinary character constants have type int; the char operand is promoted for comparison and subtraction.
  3. C guarantees that '0' through '9' have contiguous increasing character codes. Thus digit-'0' gives 0..9 after validation, without assuming ASCII or an absolute code of 48.
  4. The total cost is at most 9*125=1125 cents. cents/100 gives whole units and cents%100 gives a nonnegative remainder below 100.
  5. %02d prints the remainder in a field of width two padded with a leading zero. For zero quantity the required price is 0.00, not an omitted decimal part.
Model C answer
#include <stdio.h>
int main(void)
{
    char digit;
    if (scanf(" %c", &digit) != 1 || digit < '0' || digit > '9') {
        puts("invalid");
        return 0;
    }
    int quantity = digit - '0';
    int cents = quantity * 125;
    printf("quantity=%d price=%d.%02d\n", quantity, cents / 100, cents % 100);
    return 0;
}

Common mistakes

  • Using a character code as the numerical quantity, or assuming ASCII is required by the C standard.
  • Using floating-point money and overlooking the explicit two-digit formatting requirement.

Before calling this one solid

  • Checked conversion success and character bounds.
  • Used subtraction of '0' and explained the consecutive-digit guarantee.
  • Computed money entirely in integers and used a two-digit remainder.
  • Handled zero, the largest digit and a non-digit.

Reference program checked with GCC and Clang in C17 mode.

M3-08Judge every claimCore~10 minRead declarations and grouping preciselyNot attempted

Judge EACH statement independently. For false statements, show a corrected statement or a small safe counterexample. A. In int a, b = 4; inside a function, both a and b are explicitly initialized to 4. B. In int x = 2; x += 3 * 4;, the final x is 14. C. The grouping of a = b = 7 is a = (b = 7), so for ordinary int variables both end with value 7. D. The expression !2 + 3 is equivalent to !(2 + 3). E. In if (x = 0), the assignment stores zero in x and the condition is false; using == would test equality instead. F. In C17, writing 4 / 0 is a valid way to request a special infinite integer value. Do not evaluate an uninitialized local in an example or execute division by zero.

Link to this question
Saves in this browser
Hint 1

An initializer after one declarator belongs to that declarator, not automatically to every name on the line.

Hint 2

Unary ! binds more tightly than addition. Assignment expressions have the value that was stored.

Worked solution & self-marking checklist

A false; B true; C true; D false; E true; F false.

Reason it through

  1. A: false. Only b has the explicit initializer. Write int a=4, b=4; to initialize both. An automatic a without an initializer must not be used as if it were zero.
  2. B: true. Multiplication gives 12 first; compound addition stores the old 2 plus 12, yielding 14.
  3. C: true. Assignment associates right to left. For distinct ordinary int objects, b receives 7 and the outer assignment stores that value into a.
  4. D: false. !2 is 0, so (!2)+3 is 3. !(2+3) is !5, which is 0.
  5. E: true. Assignment and equality are different operators. The assignment expression has value 0 here, so the controlled statement is skipped; most compilers warn about this likely mistake.
  6. F: false. Integer division by zero has undefined behavior; integers have no special infinity result. Validate a divisor before division.

Common mistakes

  • Transferring one initializer to earlier names in a declaration.
  • Confusing = with == or assuming precedence is a universal left-to-right rule.

Before calling this one solid

  • Gave six separate verdicts and corrected A, D and F.
  • Showed numerical evaluation for B and D.
  • Explained right-associative assignment without making a general argument-evaluation-order claim.
  • Avoided running invalid expressions to guess their results.
M3-09Debug & repairCore~10 minA percentage program that compiles but liesNot attempted

The starter program compiles successfully but does not print the intended percentage. Explain its actual value, then replace the constants with checked input of earned and possible. Valid input satisfies 0 <= earned <= possible <= 10000 and possible > 0. Print percent=P with two digits after the decimal point, or invalid for missing/out-of-range input. Explain both where you introduce floating-point arithmetic and why the validation must occur before division. Include tests for 3/8, zero earned, full credit and a zero possible value. Assume every integer token supplied is representable in int.

C
#include <stdio.h>
int main(void)
{
    int earned = 3;
    int possible = 8;
    double percent = earned / possible * 100;
    printf("%.2f\n", percent);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The expression on the right is evaluated using its operands, before conversion to the destination type.

Hint 2

Use 100.0, or cast one operand before division. A cast around earned/possible is too late.

Worked solution & self-marking checklist

The starter computes integer 3/8 as zero. Validate input, then evaluate 100.0*earned/possible to retain the fraction.

Reason it through

  1. In the starter, earned/possible is int division and yields 0; multiplying by integer 100 still yields 0, then assignment converts it to double 0.0.
  2. Require both conversions to succeed, a positive denominator and 0<=earned<=possible<=10000. After the failed read, short-circuit evaluation avoids consulting unassigned variables.
  3. 100.0*earned converts earned to double before multiplication; division by possible is then floating-point division. For 3 and 8, the result is exactly 37.5.
  4. Print with %.2f to obtain percent=37.50. For (0,8), print 0.00; for (8,8), print 100.00.
  5. A denominator of zero is invalid input and is rejected before any division. Merely making the destination double does not fix either integer truncation or validation.
Model C answer
#include <stdio.h>
int main(void)
{
    int earned;
    int possible;
    if (scanf("%d %d", &earned, &possible) != 2 ||
        earned < 0 || possible <= 0 || earned > possible || possible > 10000) {
        puts("invalid");
        return 0;
    }
    double percent = 100.0 * earned / possible;
    printf("percent=%.2f\n", percent);
    return 0;
}

Common mistakes

  • Casting the already-truncated quotient, or changing only the type of percent.
  • Checking possible==0 after performing the division.

Before calling this one solid

  • Explained the starter result without calling it a compiler bug.
  • Checked conversion count and every domain condition before division.
  • Introduced a floating operand early enough.
  • Matched all four boundary/result cases and the required output format.

Reference program checked with GCC and Clang in C17 mode.

M3-10TraceFoundation~8 minPrefix, postfix and assignment: one statement at a timeNot attempted

Produce a trace table after every declaration or assignment in the program, then give the exact output. Distinguish the value yielded by x++ from the new value eventually stored in x by the end of that statement. Explain whether unary - modifies its operand. Finally say why this example can be traced statement by statement, while combining multiple unsequenced modifications of x inside one expression would require a separate validity check. Do not combine the increments in your answer.

C
#include <stdio.h>
int main(void)
{
    int x = 3;
    int a = x++;
    int b = ++x;
    x += a * 2;
    int c = -x;
    int d = x > b;
    printf("a=%d b=%d x=%d c=%d d=%d\n", a, b, x, c, d);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

Postfix yields the old value; prefix yields the incremented value.

Hint 2

Each shown full expression finishes before the next statement begins, so record both the assigned value and the updated x.

Worked solution & self-marking checklist

a receives 3, b receives 5, the compound assignment makes x 11, and unary minus produces -11 without changing x.

Reason it through

  1. Initially x=3. int a=x++; gives a the old value 3 and leaves x=4 by the end of the declaration.
  2. int b=++x; increments x from 4 to 5 before yielding the value, so b=5 and x=5.
  3. x+=a*2; multiplies 3 by 2 first, then adds 6 to x, so x becomes 11. a and b remain 3 and 5.
  4. c=-x creates the value -11 without changing x. d=x>b compares 11 with 5 and stores int 1.
  5. These operations occupy separate full expressions, so the state effects complete before the next begins. This is not permission to write expressions such as x++ + ++x, whose modifications would be unsequenced and undefined in C17.
Model C answer
#include <stdio.h>
int main(void)
{
    int x = 3;
    int a = x++;
    int b = ++x;
    x += a * 2;
    int c = -x;
    int d = x > b;
    printf("a=%d b=%d x=%d c=%d d=%d\n", a, b, x, c, d);
    return 0;
}

Expected output

a=3 b=5 x=11 c=-11 d=1

Common mistakes

  • Changing a later when x changes, as if a retained a live reference to x.
  • Treating unary - as a decrement or claiming that every use of ++ is inherently undefined.

Before calling this one solid

  • Recorded the old yielded value and final x for the postfix statement.
  • Recorded the new yielded value for prefix and the multiplication before +=.
  • Kept x unchanged during unary negation and gave the exact output.
  • Explained the separate-statement sequencing reason.

Reference program checked with GCC and Clang in C17 mode.

04

Branches & loops

Conditions, switch, iteration, traces · 10 questions

M4-01Debug & repairFoundation~10 minFind the else that indentation hidNot attempted

A learner intends to print APPROVED only when score >= 50 and attendance >= 75, and REJECTED in every other valid case. The starter uses fixed inputs 40 and 90. Explain its actual behavior and show which if owns its else; indentation is not evidence. Repair the logic with explicit braces. Your complete program must instead read score and attendance, each in 0..100, print APPROVED or REJECTED, and print invalid for failed/out-of-range input. Show test cases immediately below, exactly on and immediately above both thresholds. Assume every integer token supplied is representable in int.

C
#include <stdio.h>
int main(void)
{
    int score = 40;
    int attendance = 90;
    if (score >= 50)
        if (attendance >= 75)
            puts("APPROVED");
    else
        puts("REJECTED");
    return 0;
}
Link to this question
Saves in this browser
Hint 1

An else attaches to the nearest preceding unmatched if, regardless of indentation.

Hint 2

You can express “both gates pass” with && and put one explicit else on that combined decision.

Worked solution & self-marking checklist

The starter prints nothing for 40 and 90 because its else belongs to the inner if. A braced combined condition implements the intended two-gate decision.

Reason it through

  1. The parse is if(score>=50) { if(attendance>=75) { APPROVED; } else { REJECTED; } }. The else matches attendance, not score.
  2. With score=40, the outer condition is false and its entire controlled statement is skipped. It has no else, so there is no output. This is defined behavior, but it fails the specification.
  3. Read and validate two percentages before testing eligibility. Both thresholds are inclusive: score 50 and attendance 75 qualify.
  4. Use if(score>=50 && attendance>=75) with braced approved and rejected branches. Equivalently, use an explicit rejection branch for each failed gate in nested braced if statements.
  5. Check (49,75), (50,74), (50,75), (51,75), (50,76), and the original (40,90). The exact pair (50,75), (51,75) and (50,76) pass; the other three pairs fail.
Model C answer
#include <stdio.h>
int main(void)
{
    int score;
    int attendance;
    if (scanf("%d %d", &score, &attendance) != 2 ||
        score < 0 || score > 100 || attendance < 0 || attendance > 100) {
        puts("invalid");
        return 0;
    }
    if (score >= 50 && attendance >= 75) {
        puts("APPROVED");
    } else {
        puts("REJECTED");
    }
    return 0;
}

Common mistakes

  • Matching else by visual alignment or assuming C requires braces around every single statement.
  • Using > rather than >= and silently excluding the exact thresholds.

Before calling this one solid

  • Attached the original else to the correct if and explained the empty output.
  • Wrote explicitly braced intended logic with inclusive thresholds.
  • Validated both input percentages.
  • Checked both individual gate failures and the exact boundary pair.

Reference program checked with GCC and Clang in C17 mode.

M4-02TraceCore~12 minTrace continue, update and break separatelyNot attempted

Give the exact output and a trace table with one row for each entered iteration. Include i, sum on entry, which branch is taken, sum on exit and whether the for update executes. Also record the loop's final i. Explain why continuing at i=3 does not leave i stuck at 3, why the value that would exceed the limit is not included, and why breaking is different from merely making the next condition false.

C
#include <stdio.h>
int main(void)
{
    int sum = 0;
    int i;
    for (i = 1; i <= 8; ++i) {
        if (i == 3) {
            continue;
        }
        if (sum + i > 12) {
            break;
        }
        sum += i;
        printf("take=%d sum=%d\n", i, sum);
    }
    printf("end i=%d sum=%d\n", i, sum);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

In a for loop, continue goes to the update expression before the next condition test.

Hint 2

At i=5, compute sum+i using the total already built from 1, 2 and 4.

Worked solution & self-marking checklist

The loop takes 1, 2, 4 and 5, skips 3, and breaks at 6 with sum 12 and i 6.

Reason it through

  1. i=1 enters with sum=0, takes 1, prints sum=1 and updates i to 2. i=2 takes 2, prints sum=3 and updates i to 3.
  2. i=3 triggers continue before either the limit check or addition. sum remains 3; the for update still runs, producing i=4.
  3. i=4 sees 3+4<=12, takes 4 and prints sum=7. i=5 sees 7+5<=12, takes 5 and prints sum=12. The update then produces i=6.
  4. i=6 sees 12+6>12, so break exits immediately. It does not add 6, print a take line, or execute ++i.
  5. The final line therefore shows i=6 and sum=12. A natural condition-based termination normally follows the update and condition check; this break occurs inside the body before those steps.
Model C answer
#include <stdio.h>
int main(void)
{
    int sum = 0;
    int i;
    for (i = 1; i <= 8; ++i) {
        if (i == 3) {
            continue;
        }
        if (sum + i > 12) {
            break;
        }
        sum += i;
        printf("take=%d sum=%d\n", i, sum);
    }
    printf("end i=%d sum=%d\n", i, sum);
    return 0;
}

Expected output

take=1 sum=1
take=2 sum=3
take=4 sum=7
take=5 sum=12
end i=6 sum=12

Common mistakes

  • Skipping the for update on continue, or performing it after break.
  • Adding the rejected value before testing the limit and then reporting an excessive sum.

Before calling this one solid

  • Showed all six entered iterations, including the skipped and broken ones.
  • Distinguished update behavior after continue and break.
  • Tracked sum before the prospective-addition test.
  • Produced the exact five output lines and final i.

Reference program checked with GCC and Clang in C17 mode.

M4-03Judge every claimFoundation~9 minControl-flow rules without guessworkNot attempted

Judge EACH statement independently. Explain false statements with a minimal safe example or a corrected rule. A. A while loop whose condition is false on the first test executes its body zero times. B. In a for loop with an update expression, continue skips that update as well as the rest of the body. C. A break executed in the inner of two nested loops automatically exits both loops. D. Without a break or another transfer of control, execution after one matching switch label can continue through statements following later labels. E. The default label of a switch must be written last to be valid C. F. In an if or loop condition, a negative integer is false because it is below zero.

Link to this question
Saves in this browser
Hint 1

C conditions test zero versus nonzero, not positive versus nonpositive.

Hint 2

A label identifies an entry point; it is not an automatic barrier that stops execution.

Worked solution & self-marking checklist

A true; B false; C false; D true; E false; F false.

Reason it through

  1. A: true. while tests before each body execution, including the first one, so a zero initial condition permits zero iterations.
  2. B: false. continue in a for loop transfers to the update expression, then the condition is tested. It skips the remainder of that body iteration, not the update.
  3. C: false. break exits only the nearest enclosing loop or switch. An outer loop can continue after the inner one ends.
  4. D: true. This is switch fallthrough. Add break when the case should stop, or deliberately group labels when they share behavior.
  5. E: false. default may appear elsewhere among the labels. Its location affects where execution continues once entered, but not whether the label is valid.
  6. F: false. Any nonzero scalar integer value, including -1, is true as a condition. Zero is false.

Common mistakes

  • Treating continue as equivalent to break, or expecting break to escape every enclosing control structure.
  • Reading switch labels as if they were independent if statements with automatic stopping.

Before calling this one solid

  • Gave six correct independent verdicts.
  • Described the for update and nearest-enclosing break rule.
  • Explained fallthrough and the role/location of default.
  • Stated zero/nonzero truth correctly, including negative integers.
M4-04Write CCore~15 minTranslate a progressive tariff into branchesNot attempted

Read integer usage u in 0..1000. Charge 2 credits per unit for the first 100 units, 3 per unit for the next 100, and 5 per unit beyond 200. These are progressive bands: usage 101 costs 100*2 + 1*3, rather than 101*3. There is no fixed fee. Write a complete C program printing bill=B, or invalid for failed/out-of-range input. State the expression used in each branch and give hand calculations for 0, 100, 101, 200 and 201. Show how your branch conditions cover every valid value exactly once. Assume every integer token supplied is representable in int.

Link to this question
Saves in this browser
Hint 1

Finish charging all earlier bands before adding the current band’s excess.

Hint 2

At u>200, the first two bands already cost 100*2+100*3=500.

Worked solution & self-marking checklist

Use three exclusive ranges with accumulated earlier-band costs: 2u, 200+3(u-100), and 500+5(u-200).

Reason it through

  1. Validate a successful integer read and 0<=u<=1000. The maximum bill is 500+800*5=4500, safely within the minimum required int range.
  2. For 0..100 use 2*u. For 101..200 use 200+3*(u-100). For 201..1000 use 500+5*(u-200).
  3. An if / else-if / else chain tests u<=100 first, then u<=200 only when the first test failed. Hence the ranges are disjoint and cover all valid u.
  4. Boundary bills are: u=0 → 0; u=100 → 200; u=101 → 203; u=200 → 500; u=201 → 505.
  5. The count charged in a later band is the excess beyond its starting threshold, not the entire usage. This distinction is the main modeling requirement.
Model C answer
#include <stdio.h>
int main(void)
{
    int units;
    if (scanf("%d", &units) != 1 || units < 0 || units > 1000) {
        puts("invalid");
        return 0;
    }
    int bill;
    if (units <= 100) {
        bill = units * 2;
    } else if (units <= 200) {
        bill = 200 + (units - 100) * 3;
    } else {
        bill = 500 + (units - 200) * 5;
    }
    printf("bill=%d\n", bill);
    return 0;
}

Common mistakes

  • Applying the highest reached rate to every unit instead of only that band.
  • Subtracting the wrong threshold or leaving a threshold uncovered between separate if statements.

Before calling this one solid

  • Implemented progressive rather than flat-rate charging.
  • Covered all valid inputs exactly once with inclusive boundaries.
  • Matched all five hand-calculated bills.
  • Validated input and printed the required one-line format.

Reference program checked with GCC and Clang in C17 mode.

M4-05Debug & repairFoundation~12 minSwitch selection is not automatic case isolationNot attempted

The modes are: 1 doubles value, 2 triples value, and 3 returns zero. Any other mode is invalid. The starter accidentally overwrites its answer. Trace its fixed inputs and explain the exact value it prints; then repair it using switch and explicit control transfers. Your corrected complete program must read mode and value, where value is 0..100. Print result=R for a valid mode, otherwise invalid. Failed input or an out-of-range value is invalid too. Explain why reaching default by fallthrough is possible even though a matching case was found. Assume every integer token supplied is representable in int.

C
#include <stdio.h>
int main(void)
{
    int mode = 1;
    int value = 4;
    int result = 0;
    switch (mode) {
        case 1: result = value * 2;
        case 2: result = value * 3;
        case 3: result = 0;
        default: result = -1;
    }
    printf("result=%d\n", result);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The selected label decides where execution begins; ordinary statements continue until something transfers control.

Hint 2

After the case 1 assignment, trace each subsequent assignment before reaching printf.

Worked solution & self-marking checklist

The starter prints result=-1 after falling through every later assignment. Add a break after each completed valid case and reject unsupported modes in default.

Reason it through

  1. mode=1 jumps to case 1 and sets result=8. Execution then reaches case 2 and overwrites it with 12.
  2. It continues through case 3, setting result=0, then through default, setting result=-1. The original output is therefore result=-1.
  3. case and default are labels, not separate automatically exclusive blocks. default can be reached by fallthrough as well as selected when no case matches.
  4. In the corrected switch, each valid case assigns result and breaks out of the switch. default prints invalid and returns, so no uninitialized result is printed.
  5. Validate the two input values and value range first. A mode outside 1,2,3 is rejected even when its value would otherwise be valid.
Model C answer
#include <stdio.h>
int main(void)
{
    int mode;
    int value;
    if (scanf("%d %d", &mode, &value) != 2 || value < 0 || value > 100) {
        puts("invalid");
        return 0;
    }
    int result;
    switch (mode) {
        case 1:
            result = value * 2;
            break;
        case 2:
            result = value * 3;
            break;
        case 3:
            result = 0;
            break;
        default:
            puts("invalid");
            return 0;
    }
    printf("result=%d\n", result);
    return 0;
}

Common mistakes

  • Assuming finding a matching case makes default unreachable.
  • Adding one break only at the end of the switch, after all unintended overwrites.

Before calling this one solid

  • Traced the starter through 8, 12, 0 and -1.
  • Placed breaks after each valid case.
  • Handled default without subsequently printing an invalid result.
  • Checked mode, value and failed-input cases.

Reference program checked with GCC and Clang in C17 mode.

M4-06Write CStretch~17 minWrite an iterative GCD with a defensible loopNot attempted

Write a nonrecursive C program for the greatest common divisor of two integers in 0..30000. Use the repeated-remainder rule gcd(a,b)=gcd(b,a%b) while b is nonzero. Print gcd=G; if both inputs are zero print undefined, meaning this task deliberately leaves gcd(0,0) without a value. For failed/out-of-range input print invalid. Show the successive (a,b) pairs for 48 and 18, explain the update order, and justify termination. Handle a zero in either position. The word undefined in the specified output refers to the mathematical convention of this task, not undefined behavior in the C program. Assume every integer token supplied is representable in int.

Link to this question
Saves in this browser
Hint 1

Compute a%b before overwriting a. A temporary variable preserves the remainder while a and b are updated.

Hint 2

For positive b, the nonnegative remainder is strictly less than b. When b becomes zero, a is the answer.

Worked solution & self-marking checklist

Preserve the remainder in a temporary and repeatedly replace (a,b) by (b,remainder), stopping before any remainder by zero.

Reason it through

  1. Validate both reads and the nonnegative range. Handle (0,0) explicitly with the requested word; no arithmetic with a zero divisor is needed.
  2. For b!=0, compute remainder=a%b while a and b still hold the old pair. Then set a=b and b=remainder.
  3. For (48,18), the pairs are (48,18) → (18,12) → (12,6) → (6,0), so the answer is 6.
  4. The common divisors are unchanged by replacing a with its remainder modulo b. At termination gcd(a,0)=a for the nonzero original pair.
  5. After an iteration with positive b, the new b lies in 0..old_b-1, so it decreases until zero. For (0,9), one iteration produces (9,0); for (9,0), the body executes zero times.
Model C answer
#include <stdio.h>
int main(void)
{
    int a;
    int b;
    if (scanf("%d %d", &a, &b) != 2 || a < 0 || a > 30000 || b < 0 || b > 30000) {
        puts("invalid");
        return 0;
    }
    if (a == 0 && b == 0) {
        puts("undefined");
        return 0;
    }
    while (b != 0) {
        int remainder = a % b;
        a = b;
        b = remainder;
    }
    printf("gcd=%d\n", a);
    return 0;
}

Common mistakes

  • Overwriting a before calculating the remainder, which can change the divisor pair.
  • Using a%b before checking b!=0, or confusing the task output word with permission to execute C undefined behavior.

Before calling this one solid

  • Wrote an iterative loop with a correctly preserved temporary.
  • Handled both one-zero cases and the explicit both-zero convention.
  • Traced the four GCD states and stated why common divisors are preserved.
  • Explained strict decrease and avoided remainder by zero.

Reference program checked with GCC and Clang in C17 mode.

M4-07Debug & repairCore~12 minRepair a while loop that never reaches its updateNot attempted

The starter should print the integers from 1 through 7 except multiples of 3, each on its own line. Explain where it stops making progress and give the finite output prefix printed before that happens. Repair it while retaining both while and continue. Then write an equivalent for loop and explain the placement of its update. Your answer must account for every possible control-flow path that continues the loop; “add an increment somewhere” is not enough. Do not run the broken loop without a timeout.

C
#include <stdio.h>
int main(void)
{
    int i = 1;
    while (i <= 7) {
        if (i % 3 == 0) {
            continue;
        }
        printf("%d\n", i);
        ++i;
    }
    return 0;
}
Link to this question
Saves in this browser
Hint 1

At i=3, continue jumps to the while condition and bypasses the increment at the bottom.

Hint 2

One clean while pattern starts at 0, tests i<7, and increments at the top of every iteration before a possible continue.

Worked solution & self-marking checklist

The starter prints 1 and 2, then repeats forever at i=3. Move progress to a path guaranteed to occur before continue.

Reason it through

  1. At i=1 and i=2, the modulo test is false, so each number is printed and i increments. At i=3, the modulo test is true.
  2. continue skips both printf and ++i. The next while test still sees 3<=7, so the same state repeats forever. The finite printed prefix is 1 followed by 2, each on a line.
  3. The repaired while initializes i=0, tests i<7, and executes ++i at the top. Every entered iteration therefore advances once, including those that continue.
  4. The repaired program prints 1,2,4,5,7 on separate lines and terminates when the test sees i=7 after the final iteration.
  5. An equivalent for fragment is for (int j=1; j<=7; ++j) { if (j%3==0) { continue; } printf("%d\n", j); }. Here continue reaches the for update before the next condition test, which is different from jumping to the condition in the original while.
Model C answer
#include <stdio.h>
int main(void)
{
    int i = 0;
    while (i < 7) {
        ++i;
        if (i % 3 == 0) {
            continue;
        }
        printf("%d\n", i);
    }
    return 0;
}

Expected output

1
2
4
5
7

Common mistakes

  • Incrementing only on the print path and leaving the skipped path stuck.
  • Changing the bound without checking whether 7 is still included or whether 8 is accidentally processed.

Before calling this one solid

  • Identified the repeating state i=3 and the exact finite prefix.
  • Retained while and continue in a terminating repair.
  • Showed why every continuing path advances exactly once.
  • Gave an equivalent for loop and the final required five-number output.

Reference program checked with GCC and Clang in C17 mode.

M4-08TraceStretch~15 minNested loops need a separate state for each levelNot attempted

Give the exact output and list every (row,col) pair that enters the inner body, including pairs skipped by continue or stopped by break. Label each pair printed/skipped/break. State when col is reinitialized, whether a break here prevents the next row, and why count is cumulative across rows. Do not replace the actual control-flow trace with “three times four iterations”; some entered bodies skip the addition and printing.

C
#include <stdio.h>
int main(void)
{
    int count = 0;
    for (int row = 1; row <= 3; ++row) {
        for (int col = 1; col <= 4; ++col) {
            if (col == row) {
                continue;
            }
            if (row + col > 5) {
                break;
            }
            ++count;
            printf("%d:%d\n", row, col);
        }
        printf("row=%d total=%d\n", row, count);
    }
    return 0;
}
Link to this question
Saves in this browser
Hint 1

col starts at 1 for each new row, while count was declared outside both loops.

Hint 2

Test col==row before testing row+col>5. At row=3,col=3, the first condition decides the path.

Worked solution & self-marking checklist

Seven pairs are printed. The inner continue skips diagonal pairs, and rows 2 and 3 break at col 4.

Reason it through

  1. Row 1 enters col=1,2,3,4. Pair (1,1) continues; (1,2),(1,3),(1,4) print, making count=3. The row summary prints row=1 total=3.
  2. Row 2 starts col at 1 again. (2,1) prints, (2,2) continues, (2,3) prints, and (2,4) breaks because 2+4>5. Count is now 5; the row summary still runs.
  3. Row 3 starts col at 1. (3,1),(3,2) print, (3,3) continues before the sum test, and (3,4) breaks. Count is now 7.
  4. A break exits only the inner for here, after which the row summary executes and the outer row update can proceed. continue affects only the nearest loop and takes its update path.
  5. count is initialized once before both loops. It is never reset at a row boundary, so the summaries are cumulative: 3,5,7.
Model C answer
#include <stdio.h>
int main(void)
{
    int count = 0;
    for (int row = 1; row <= 3; ++row) {
        for (int col = 1; col <= 4; ++col) {
            if (col == row) {
                continue;
            }
            if (row + col > 5) {
                break;
            }
            ++count;
            printf("%d:%d\n", row, col);
        }
        printf("row=%d total=%d\n", row, count);
    }
    return 0;
}

Expected output

1:2
1:3
1:4
row=1 total=3
2:1
2:3
row=2 total=5
3:1
3:2
row=3 total=7

Common mistakes

  • Applying break to both loops or resetting count for each row without a corresponding statement.
  • Checking row+col before the earlier continue condition and incorrectly breaking at (3,3).

Before calling this one solid

  • Listed all twelve entered pairs with the correct action for each.
  • Printed seven pair lines and three cumulative summary lines in the right order.
  • Explained reinitialization of col versus persistence of count.
  • Applied continue and break to the inner loop only.

Reference program checked with GCC and Clang in C17 mode.

M4-09Design & integrateStretch~20 minBuild a stream summary with three different exitsNot attempted

A stream contains at most 100 representable integer marks, then EOF; a -1 may end processing earlier. Mark 0..100 is accepted. Any other mark except the sentinel is rejected and counted, then processing continues. The sentinel is neither accepted nor rejected, and later tokens are ignored. You may assume all supplied tokens are valid integer representations. Write a complete program with no arrays. Print count=K rejected=R average=A with two decimal places; if no mark was accepted, print average=NA instead. Design state variables and state their meanings. Trace 80, 120, 0, -2, 100, -1, 40. Include EOF without a sentinel, immediate sentinel and rejected-only input among your tests.

Link to this question
Saves in this browser
Hint 1

Separate input exhaustion, the sentinel, an invalid mark and a valid mark. They require different actions.

Hint 2

Keep sum and accepted count separate from the rejected count, then guard the final division with count!=0.

Worked solution & self-marking checklist

Use count/sum for accepted marks, rejected for invalid nonsentinel marks, break for -1, and continue after a rejection.

Reason it through

  1. Initialize count=sum=rejected=0. After every processed nonsentinel token, count is the number accepted, sum is their sum, and rejected counts only out-of-range tokens.
  2. On a successful read, test mark==-1 first and break. Then test the range; increment rejected and continue for other invalid marks. Otherwise increment count and add mark to sum.
  3. For the given stream: 80 → (1,80,0); 120 → (1,80,1); 0 → (2,80,1); -2 → (2,80,2); 100 → (3,180,2). The tuple is (count,sum,rejected). -1 stops; 40 is untouched.
  4. Print count=3 rejected=2 average=60.00. If count is zero, print NA without dividing. Otherwise cast sum before division to retain a fractional mean.
  5. EOF ends the while loop cleanly. The 100-token bound gives sum<=10000 and both counts<=100, so int arithmetic remains in range even on an implementation with the minimum C int range.
Model C answer
#include <stdio.h>
int main(void)
{
    int mark;
    int count = 0;
    int sum = 0;
    int rejected = 0;
    while (scanf("%d", &mark) == 1) {
        if (mark == -1) {
            break;
        }
        if (mark < 0 || mark > 100) {
            ++rejected;
            continue;
        }
        ++count;
        sum += mark;
    }
    if (count == 0) {
        printf("count=0 rejected=%d average=NA\n", rejected);
    } else {
        printf("count=%d rejected=%d average=%.2f\n", count, rejected, (double)sum / count);
    }
    return 0;
}

Common mistakes

  • Counting -1 as a rejection by checking the range before the sentinel.
  • Dividing by zero on empty/rejected-only input, or counting rejected marks in the mean denominator.

Before calling this one solid

  • Defined three state variables with precise meanings.
  • Handled EOF, sentinel, rejection and acceptance on distinct paths.
  • Traced the mixed input and ignored the suffix after -1.
  • Handled a zero accepted count and retained fractional averages.
  • Used no arrays and respected the exact output format.

Reference program checked with GCC and Clang in C17 mode.

M4-10Judge every claimCore~12 minLoop equivalence and empty statementsNot attempted

Judge EACH claim independently. Where a claim is false, give the actual control-flow behavior and a minimal correction. All values in these examples stay within int range. A. for (int i=0; i<3; ++i) { puts("x"); } prints x three times and keeps i out of scope after that loop. B. In int i=0; while (i<3); { ++i; }, the semicolon is harmless formatting and the braced block runs three times. C. For int i=0;, while (i<3) { ++i; } and for (; i<3; ++i) { } leave the same final i. D. Moving an increment from the end of a while body into a for update always preserves behavior, even if the body contains continue before that increment. E. In int n=0; for (; n<5; ++n) { if (n==2) break; }, final n is 3 because the update still runs after break. Do not execute the nonterminating fragment in B just to guess what happens.

Link to this question
Saves in this browser
Hint 1

A semicolon can be an entire empty statement. The next braced block need not be the loop body.

Hint 2

Equivalence must preserve all paths, including continue and break, rather than only ordinary iterations.

Worked solution & self-marking checklist

A true; B false; C true; D false; E false.

Reason it through

  1. A: true. The entered values are i=0,1,2, producing three lines. A variable declared in the for initializer has the scope of that loop, not the following surrounding block.
  2. B: false. The semicolon is the empty while body. i stays zero forever, so the following block is never reached. Remove the semicolon to make the braced block the body.
  3. C: true. Both loops execute their increment three times from an initial i=0 and finish at i=3. The for body is deliberately empty, but its update changes i.
  4. D: false. A while continue skips the remaining body including an increment at its end; a for continue executes the update. Such a translation can change nontermination or the sequence of visited values.
  5. E: false. The loop reaches n=2 and breaks immediately before its update. Final n is 2. break exits the loop without the update or another condition test.

Common mistakes

  • Ignoring an empty-statement semicolon after while because it looks like punctuation.
  • Claiming two loop spellings are universally interchangeable without checking continue paths.

Before calling this one solid

  • Gave five separate correct verdicts.
  • Explained the zero-progress infinite loop in B and repaired it.
  • Justified equivalence in C using actual visited/final values.
  • Explained why D and E fail specifically at continue and break.
05

Functions & lifetime

Calls, scope, storage, memory snapshots · 6 questions

M5-01Write CFoundation~14 minBuild a function interface before its implementationNot attempted

Write a complete program whose main appears before the definition of int clamp(int value, int low, int high). clamp returns low when value is below low, high when it is above high, and value otherwise. Put an appropriate prototype before main. Read three representable integers value, low and high; reject a failed read or low>high with invalid. Otherwise print original=V bounded=B. The original caller variable must remain unchanged. Explain the declaration, definition, invocation, actual arguments, formal parameters and returned result. Test equality to either endpoint and the low==high case. Do not use pointers to modify the caller.

Link to this question
Saves in this browser
Hint 1

The prototype tells the compiler the return type and parameter types before it checks a call.

Hint 2

The function receives copies of the three argument values. Return the bounded value and store that result in a different variable in main.

Worked solution & self-marking checklist

Declare the interface before main, define it afterward, and pass three int values to a function that returns one bounded int.

Reason it through

  1. The prototype int clamp(int value,int low,int high); is a declaration that describes the interface. Its semicolon ends the declaration; it has no function body.
  2. The definition repeats a compatible return/parameter type list and supplies the braced body. The parameter names describe new local parameter objects on each call.
  3. In main, require three conversions and low<=high. Invoke clamp(value,low,high); the argument values are copied into the callee parameters.
  4. Inside clamp, return low for a value below the lower bound, return high above the upper bound, and return value for either endpoint or the interior. Each return ends that function call.
  5. Store the returned value in bounded. main's value remains its original number. When low==high, every successful call returns that single allowed value.
Model C answer
#include <stdio.h>
int clamp(int value, int low, int high);
int main(void)
{
    int value;
    int low;
    int high;
    if (scanf("%d %d %d", &value, &low, &high) != 3 || low > high) {
        puts("invalid");
        return 0;
    }
    int bounded = clamp(value, low, high);
    printf("original=%d bounded=%d\n", value, bounded);
    return 0;
}
int clamp(int value, int low, int high)
{
    if (value < low) {
        return low;
    }
    if (value > high) {
        return high;
    }
    return value;
}

Common mistakes

  • Placing a call before any declaration and assuming JavaScript-style hoisting makes it valid C17.
  • Writing a prototype with a body, or expecting assignment to a by-value parameter to change the caller’s variable.

Before calling this one solid

  • Placed a compatible prototype before main and a definition after it.
  • Used the required function and correctly separated actual arguments from formal parameters.
  • Preserved the original value and returned the bounded result.
  • Handled both endpoints, equal bounds, reversed bounds and a failed read.

Reference program checked with GCC and Clang in C17 mode.

M5-02TraceCore~15 minDraw the caller and callee memory snapshotNot attempted

Trace the exact output. Draw a labelled conceptual memory snapshot at three moments: immediately before adjust is called, inside adjust just before its printf, and in main just after the call returns. Show main's x, adjust's parameter x, both distinct objects named total, and y where relevant. Use symbolic object names rather than inventing physical addresses. State which total each source occurrence names, which objects still exist after the call, and how the return value reaches y. A variable whose initialization is not yet complete must not be shown as already containing the returned result.

C
#include <stdio.h>
int total = 100;
int adjust(int x)
{
    int total = x + 1;
    x += 2;
    printf("callee x=%d total=%d\n", x, total);
    return total;
}
int main(void)
{
    int x = 4;
    int y = adjust(x);
    printf("caller x=%d y=%d total=%d\n", x, y, total);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

A parameter is a new object holding a copy of the argument value. A same-named local can hide a global without being the same object.

Hint 2

During int y=adjust(x);, y has not finished its initialization while adjust is still executing.

Worked solution & self-marking checklist

The callee prints x=6 and local total=5; after return, main prints its unchanged x=4, y=5 and global total=100.

Reason it through

  1. Before the call: the static-storage global total is 100 and main's automatic x is 4. y has no completed initialized value yet because its initializer requires the call to finish.
  2. Call entry copies main.x=4 into a distinct adjust.x parameter. int total=x+1 creates a distinct automatic adjust.total=5 that hides the file-scope total within its scope.
  3. Immediately before the callee printf: global.total=100, main.x=4, adjust.x=6, adjust.total=5, and main.y still awaits the returned value. Both total occurrences in adjust after the local declaration name adjust.total.
  4. return total evaluates the local value 5, ends adjust, and makes 5 the call expression's result. The parameter and automatic local lifetimes end; their values do not become main's x or the global total.
  5. The result initializes main.y=5. main's final printf names main.x, main.y and global.total, so it prints 4,5,100. The global object exists for the entire program execution.
Model C answer
#include <stdio.h>
int total = 100;
int adjust(int x)
{
    int total = x + 1;
    x += 2;
    printf("callee x=%d total=%d\n", x, total);
    return total;
}
int main(void)
{
    int x = 4;
    int y = adjust(x);
    printf("caller x=%d y=%d total=%d\n", x, y, total);
    return 0;
}

Expected output

callee x=6 total=5
caller x=4 y=5 total=100

Common mistakes

  • Merging same-named caller/callee variables into a single object, or treating the local total as a reset of the global.
  • Putting y=5 into the snapshot while the call that computes its initializer is still running.

Before calling this one solid

  • Drew three separate moments and distinguished all named objects.
  • Tracked the parameter copy and local shadow without changing main.x or global.total.
  • Represented y as not yet initialized during the call.
  • Ended automatic callee lifetimes on return and produced both exact output lines.

Reference program checked with GCC and Clang in C17 mode.

M5-03TraceCore~13 minA static local persists; an automatic local restartsNot attempted

Give the exact output and a table for both calls showing step, total before/after the update, calls before/after its increment and the returned value. Explain how a variable can be local in scope while living for the whole program. Predict the new output if static is removed from the declaration of total AND the declaration is changed to int total = 0;. Explain why simply removing static without adding that initializer would be a different and invalid way to obtain a clean per-call counter.

C
#include <stdio.h>
int record(int step)
{
    static int total;
    int calls = 0;
    total += step;
    ++calls;
    printf("inside total=%d calls=%d\n", total, calls);
    return total;
}
int main(void)
{
    int first = record(2);
    int second = record(3);
    printf("saved first=%d second=%d\n", first, second);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The uninitialized static int is initialized to zero before program startup. It is not zeroed on every function entry.

Hint 2

calls has an explicit automatic initializer, so each function invocation begins with its own calls=0.

Worked solution & self-marking checklist

The static total accumulates 2 then 3 across calls; the automatic calls prints 1 on each invocation.

Reason it through

  1. Before the first call, the single static-storage total has value 0. First call: step=2, total changes 0→2, calls changes 0→1, and the returned result is 2.
  2. The first result is copied into main.first. Returning ends that call's parameter and automatic calls, but it does not end total's lifetime.
  3. Second call: step=3, the same total changes 2→5, a newly initialized automatic calls changes 0→1, and the returned result is 5. main.second receives 5.
  4. Block scope controls where the name total can be used. Static storage duration controls how long its object exists. These are different properties, so local scope and program-long lifetime are compatible.
  5. With int total=0; instead, each call starts a fresh automatic total. The inside lines would be total=2 calls=1 and total=3 calls=1, followed by saved first=2 second=3. Removing static alone leaves an uninitialized automatic total, so total+=step would read an indeterminate value; it is not a defined reset-to-zero program.
Model C answer
#include <stdio.h>
int record(int step)
{
    static int total;
    int calls = 0;
    total += step;
    ++calls;
    printf("inside total=%d calls=%d\n", total, calls);
    return total;
}
int main(void)
{
    int first = record(2);
    int second = record(3);
    printf("saved first=%d second=%d\n", first, second);
    return 0;
}

Expected output

inside total=2 calls=1
inside total=5 calls=1
saved first=2 second=5

Common mistakes

  • Assuming every local variable is created afresh and initialized to zero on each call.
  • Combining the two record calls as printf arguments and assuming a fixed order of execution.

Before calling this one solid

  • Distinguished both calls with correct before/after values.
  • Explained one-time static initialization and per-call automatic initialization.
  • Separated scope from storage duration.
  • Gave the automatic-initialized variant and rejected the uninitialized variant without assigning it an output.

Reference program checked with GCC and Clang in C17 mode.

M5-04ExplainCore~14 minScope, lifetime and the usual memory diagramNot attempted

Analyze the fragment; do not add a call or execute it. For shared, hidden, local, calls and limit, make a table with declaration location, scope, storage duration, initial value and whether the function can modify the object by an ordinary assignment. Assume report is called only enough times for calls to stay in range. Sketch the usual introductory text/code, initialized-static-data, zero-initialized-static-data and automatic-call-storage regions. Map the objects where appropriate, but distinguish that common implementation diagram from what C17 actually guarantees. Explain what exists before the first call, what is newly initialized on each call and what survives return. State whether the fragment itself creates any dynamically allocated object.

C
int shared;
    static int hidden = 7;
    void report(void)
    {
        int local = 3;
        static int calls;
        const int limit = 5;
        ++calls;
        /* Classify the objects; no output is requested. */
    }
Link to this question
Saves in this browser
Hint 1

Scope is visibility of a name; storage duration is lifetime of an object. const is a type qualifier, not a request for static storage.

Hint 2

Global objects and block-scope static objects both have static storage duration. A typical diagram is useful without being a mandated C address map.

Worked solution & self-marking checklist

shared, hidden and calls have static storage duration; local and limit have automatic duration. Only limit is protected from ordinary assignment by const.

Reason it through

  1. shared is a file-scope int with file scope from its declaration and static storage duration; its initial value is 0. hidden is also file-scope/static-duration, initially 7, with internal linkage due to file-scope static.
  2. local is block-scoped in report and automatic, initialized to 3 on each call. limit is similarly block-scoped and automatic, initialized to 5 on each call; const does not make its duration static.
  3. calls is block-scoped yet has static storage duration. Its single object starts at 0 before program startup and survives returns. ++calls updates that same object on every call.
  4. Ordinary assignments in report may modify shared, hidden, local and calls. Assigning to limit would violate a constraint because it is const-qualified.
  5. In a common implementation, executable instructions occupy a code/text region, hidden goes into initialized static data, shared and calls into zero-initialized static storage, and automatic locals/parameters use call-stack storage. C17 guarantees the relevant initialization, scope and lifetime semantics, not named segments, physical addresses, stack direction or that an optimized local must occupy memory.
  6. The static-duration objects already exist before the first report call. local and limit are initialized per call and their lifetimes end with the block. No malloc or other dynamic allocation appears, so the fragment creates no dynamically allocated object.

Common mistakes

  • Calling every local variable a stack variable regardless of static, or calling every static variable globally visible.
  • Treating a typical text/data/BSS/stack picture as a portable requirement, or assuming const makes an automatic local static.

Before calling this one solid

  • Classified all five objects by scope, duration and initial value.
  • Distinguished the file-scope use of static from the block-scope use.
  • Identified limit as const-qualified without extending its lifetime.
  • Mapped a usual memory diagram while stating its implementation limits.
  • Explained before/during/after-call existence and absence of dynamic allocation.
M5-05Debug & repairCore~13 minRepair a function that changes only its parameterNot attempted

The starter intends to add five to a mark, capped at 100, but main does not print the intended result. Explain the actual output using distinct caller and callee objects. Repair it WITHOUT global variables or pointer parameters: the function must return the adjusted value, and the caller must use that return value. Your corrected complete program should read mark in 0..100, print mark=M after the adjustment, and print invalid for failed/out-of-range input. Include tests for 0, 94, 95, 98 and 100. Explain one benefit of the small function and one cost/tradeoff of decomposing code into functions; do not claim that every function call necessarily remains as runtime overhead after optimization. Assume every integer token supplied is representable in int.

C
#include <stdio.h>
void add_bonus(int mark)
{
    mark += 5;
    if (mark > 100) {
        mark = 100;
    }
}
int main(void)
{
    int mark = 98;
    add_bonus(mark);
    printf("mark=%d\n", mark);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The parameter receives a copy. Changing that copy cannot change main's independent int object.

Hint 2

Change the return type, return the adjusted mark, and assign the call expression back to main's mark. All three parts matter.

Worked solution & self-marking checklist

The starter prints mark=98. Return the capped result as int and use mark=add_bonus(mark) in the caller.

Reason it through

  1. In the starter, main.mark=98 is copied into add_bonus.mark. The parameter becomes 103 then 100, but main.mark remains 98; the output is mark=98.
  2. Change the function interface from void to int consistently in its prototype and definition. End the function with return mark to supply the computed value.
  3. Use mark=add_bonus(mark) in main. Merely adding a return statement without using its result would still leave the caller's mark unchanged.
  4. After validation, adding 5 gives at most 105 and cannot overflow even a minimum-range int. Capping above 100 yields the boundary results 5,99,100,100,100 for the five requested inputs.
  5. The function names and isolates the adjustment rule, which aids reuse and focused reasoning. A tradeoff is the need to design/understand an interface and follow control across a call; a compiler may inline a call, so unavoidable runtime overhead is not a sound universal claim.
Model C answer
#include <stdio.h>
int add_bonus(int mark);
int main(void)
{
    int mark;
    if (scanf("%d", &mark) != 1 || mark < 0 || mark > 100) {
        puts("invalid");
        return 0;
    }
    mark = add_bonus(mark);
    printf("mark=%d\n", mark);
    return 0;
}
int add_bonus(int mark)
{
    mark += 5;
    if (mark > 100) {
        mark = 100;
    }
    return mark;
}

Common mistakes

  • Calling ordinary C parameter passing call by reference, or assuming matching names imply one shared variable.
  • Returning a result but discarding it, or updating main while leaving the prototype incompatible with the definition.

Before calling this one solid

  • Explained the starter output using two distinct objects.
  • Changed declaration/definition/return consistently.
  • Stored the returned result in the caller without globals or pointer parameters.
  • Checked the five cap-boundary cases and rejected invalid input.
  • Gave a concrete function benefit and a measured interface tradeoff.

Reference program checked with GCC and Clang in C17 mode.

M5-06Judge every claimStretch~12 minFunction and storage-class claimsNot attempted

Judge EACH claim independently for C17. Correct every false statement and distinguish scope, linkage and storage duration when relevant. A. A declaration int twice(int); tells the compiler a function's interface but does not itself provide the function body. B. A file-scope static int counter; and a block-scope static int counter; have identical scope because both use static. C. Inside a function, extern int shared; can refer to a compatible externally defined int shared, rather than creating a fresh automatic int on every call. D. Declaring an automatic variable register guarantees that the hardware will keep it in a CPU register for its whole lifetime. E. Every argument to a C function is passed by value; later pointer-based interfaces can use a copied address value to reach some other object. F. A function defined later in the same source file can always be called earlier with no declaration, because its name is automatically hoisted as in JavaScript. No pointer syntax is required in your answer to E; explain the two distinct ideas in words.

Link to this question
Saves in this browser
Hint 1

A storage-class keyword can have different effects at file scope and block scope. The name's visibility and the object's lifetime are not one property.

Hint 2

A declaration can describe a function or refer to an existing object without allocating a fresh per-call object.

Worked solution & self-marking checklist

A true; B false; C true; D false; E true; F false.

Reason it through

  1. A: true. This is a prototype declaration with one int parameter and an int return type. A compatible definition with a body is needed when that function is used in the program.
  2. B: false. Both int objects have static storage duration and, without explicit initializers, start at zero. The file-scope name has file scope and internal linkage; the block-scope name has block scope and no linkage.
  3. C: true under the stated compatible-definition premise. The extern declaration refers to the existing shared object; it does not create a new automatic local value per call.
  4. D: false. register is a request/hint for fast access and imposes some language restrictions, but it does not require a particular hardware register allocation. The object still has automatic storage duration.
  5. E: true. A parameter receives an argument value. Copying an address value can later permit operations on a separate addressed object, but it does not change the parameter-passing rule to native call by reference.
  6. F: false. C17 requires an appropriate declaration before use; there is no JavaScript-style implicit hoisting rule. Put a compatible prototype before the earlier call or place the definition first.

Common mistakes

  • Using static as a synonym for global visibility or calling extern a per-call allocation.
  • Treating register as a hardware guarantee, or describing pointer-mediated mutation as a different native argument-passing mechanism.

Before calling this one solid

  • Gave six separate correct verdicts.
  • Separated prototype declaration from definition and rejected undeclared earlier calls.
  • Explained both static contexts and extern without confusing scope, linkage and duration.
  • Described register as a nonbinding access hint.
  • Stated universal value passing, including the later address-value case.
06

Arrays & algorithms

Bounds, search, selection sort, character arrays · 10 questions

M6-01TraceFoundation~8 minRecover an array from its loopNot attempted

Without running the program, write all six array values immediately after initialization. Then show the array after each loop iteration and give the exact output. Explain why the last three initial values are known even though the array is local. Name the first and last valid subscripts.

C
#include <stdio.h>
int main(void) {
    int a[6] = {4, 1, 7};
    for (int i = 1; i < 6; ++i) {
        a[i] += a[i - 1];
    }
    for (int i = 0; i < 6; ++i) {
        printf("%s%d", i == 0 ? "" : " ", a[i]);
    }
    putchar('\n');
    return 0;
}
Link to this question
Saves in this browser
Hint 1

An initializer that supplies fewer values than the declared array length initializes the remaining elements to zero.

Hint 2

Each iteration reads the previous element after that element has already been updated. This is a running total, not six independent additions.

Worked solution & self-marking checklist

The initial array is {4, 1, 7, 0, 0, 0}; the loop replaces it with prefix sums.

Reason it through

  1. The declared length is six, so valid subscripts are 0 through 5. The initializer supplies 4, 1 and 7 and zero-initializes the rest.
  2. After i=1 the array is {4,5,7,0,0,0}; after i=2 it is {4,5,12,0,0,0}.
  3. After i=3, i=4 and i=5 the arrays are {4,5,12,12,0,0}, {4,5,12,12,12,0} and {4,5,12,12,12,12}.
  4. The second loop visits exactly six elements and prints a single space before every element except the first.
Model C answer
#include <stdio.h>
int main(void) {
    int a[6] = {4, 1, 7};
    for (int i = 1; i < 6; ++i) {
        a[i] += a[i - 1];
    }
    for (int i = 0; i < 6; ++i) {
        printf("%s%d", i == 0 ? "" : " ", a[i]);
    }
    putchar('\n');
    return 0;
}

Expected output

4 5 12 12 12 12

Common mistakes

  • Do not treat the omitted initializer elements as uninitialized local variables.
  • Do not use the original a[i-1] after an earlier iteration has changed it.

Before calling this one solid

  • I wrote the six initial values and valid bounds.
  • I showed all five update states.
  • My output has six values and one final newline.

Reference program checked with GCC and Clang in C17 mode.

M6-02ExplainFoundation~9 minDraw contiguous storage without guessing sizeof(int)Not attempted

A laboratory stores four integer readings from consecutive hours. Explain why one array is more suitable than four separately named variables for indexed traversal. Draw its element order and give the byte-address formula for reading[i], using B for the address of reading[0] and S for sizeof(int). Give offsets for i=0,1,2,3, the total array size in terms of S, and the exact output of the program. Explain why reading[4] is not an extra reading. Do not assume an int occupies four bytes.

C
#include <stdio.h>
int main(void) {
    int reading[4] = {12, 15, 11, 18};
    size_t count = sizeof reading / sizeof reading[0];
    for (size_t i = 0; i < count; ++i) {
        printf("index=%zu value=%d offset=%zu elements\n", i, reading[i], i);
    }
    printf("count=%zu\n", count);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

An array groups a fixed number of objects of one element type under one name; loops can vary the subscript.

Hint 2

Adjacent elements are separated by sizeof one element, so convert an element offset i to a byte offset i*S.

Worked solution & self-marking checklist

The readings occupy four contiguous int elements. Their byte offsets are 0, S, 2S and 3S, and the array occupies 4S bytes.

Reason it through

  1. The element order is [0]:12, [1]:15, [2]:11, [3]:18. A loop can apply the same operation to each hour using one subscript.
  2. For a valid i, the conceptual byte address is B+i*S. Arrays have no padding between their elements, although the element type itself has its own size.
  3. sizeof reading is 4*sizeof(int); dividing by sizeof reading[0] gives four in this scope, where reading is the actual array.
  4. reading[4] would attempt to access beyond the four elements. A one-past position is a boundary, not an element to read or write.
Model C answer
#include <stdio.h>
int main(void) {
    int reading[4] = {12, 15, 11, 18};
    size_t count = sizeof reading / sizeof reading[0];
    for (size_t i = 0; i < count; ++i) {
        printf("index=%zu value=%d offset=%zu elements\n", i, reading[i], i);
    }
    printf("count=%zu\n", count);
    return 0;
}

Expected output

index=0 value=12 offset=0 elements
index=1 value=15 offset=1 elements
index=2 value=11 offset=2 elements
index=3 value=18 offset=3 elements
count=4

Common mistakes

  • Do not hard-code an int byte size that the question did not supply.
  • The largest valid index is count-1, not count.

Before calling this one solid

  • My diagram includes exactly four elements in increasing subscript order.
  • I gave B+i*S and total size 4S.
  • I explained indexed traversal and rejected access at subscript 4.

Reference program checked with GCC and Clang in C17 mode.

M6-03TraceCore~10 minAn array parameter and a length parameter behave differentlyNot attempted

Trace the caller and callee separately. Give the exact output, list the changed elements, and explain why setting n=0 does not change the caller’s n. If adjust must work with arrays of different lengths, explain why it needs the explicit n argument rather than calculating the element count with sizeof a inside the function. Assume each caller passes a nonnegative length no larger than its actual array.

C
#include <stdio.h>
static void adjust(int a[], int n) {
    for (int i = 1; i < n; i += 2) {
        a[i] += 10;
    }
    n = 0;
    printf("inside n=%d\n", n);
}
int main(void) {
    int a[5] = {2, 4, 6, 8, 10};
    int n = 5;
    adjust(a, n);
    printf("outside n=%d\n", n);
    for (int i = 0; i < n; ++i) {
        printf("%s%d", i == 0 ? "" : " ", a[i]);
    }
    putchar('\n');
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The loop uses indices 1 and 3. The parameter n is a separate integer object.

Hint 2

An array parameter is adjusted to a pointer parameter; it provides access to the caller’s elements but carries no automatic length metadata.

Worked solution & self-marking checklist

The function changes a[1] and a[3], while its assignment to its local n leaves the caller’s n equal to five.

Reason it through

  1. The first loop visits i=1 and i=3, changing 4 to 14 and 8 to 18.
  2. The array parameter accesses the existing caller array, so those writes remain visible after the call.
  3. The integer parameter receives a copy of the value 5. Its later value 0 is printed inside the function only.
  4. Inside adjust, sizeof a would measure the adjusted pointer parameter, not the caller array. An explicit length defines which elements the function may use.
Model C answer
#include <stdio.h>
static void adjust(int a[], int n) {
    for (int i = 1; i < n; i += 2) {
        a[i] += 10;
    }
    n = 0;
    printf("inside n=%d\n", n);
}
int main(void) {
    int a[5] = {2, 4, 6, 8, 10};
    int n = 5;
    adjust(a, n);
    printf("outside n=%d\n", n);
    for (int i = 0; i < n; ++i) {
        printf("%s%d", i == 0 ? "" : " ", a[i]);
    }
    putchar('\n');
    return 0;
}

Expected output

inside n=0
outside n=5
2 14 6 18 10

Common mistakes

  • Do not say that C changes to pass-by-reference: C passes the pointer value and integer value by value.
  • Do not copy the caller’s sizeof-array length formula into an array-parameter function.

Before calling this one solid

  • I separated the caller’s n from the callee’s n.
  • I identified exactly two changed indices.
  • I explained the function’s length contract.

Reference program checked with GCC and Clang in C17 mode.

M6-04Debug & repairCore~14 minRepair first-occurrence linear searchNot attempted

The fragment is meant to return the first index containing target, or -1 if absent, for lengths 0 through 8. Identify three independent defects and repair them. Do not execute the broken fragment or assign it a reliable output. Then write a complete test driver: input is n, n integer elements, then target, separated by whitespace; element and target values lie in [-100,100]. Print only the returned index and a newline. For the named duplicate sample, input is 5 / 8 3 8 2 8 / 8 (slashes denote line breaks). Explain the empty-array and absent-target cases.

C
int find_first(const int a[], int n, int target) {
    int answer = 0;
    for (int i = 0; i <= n; ++i) {
        if (a[i] == target) answer = i;
    }
    return answer;
}
Link to this question
Saves in this browser
Hint 1

The loop may inspect only indices 0 through n-1. A failed search needs a value distinguishable from index zero.

Hint 2

Returning immediately on a match both selects the first occurrence and avoids unnecessary later comparisons.

Worked solution & self-marking checklist

Use i<n, return the matching index immediately, and return -1 only after every valid element has failed to match.

Reason it through

  1. The condition i<=n reads a[n], outside the specified logical range and outside the actual array if n equals its capacity.
  2. Initializing answer to zero makes an absent target indistinguishable from a match at index zero.
  3. Overwriting answer on every match selects the last occurrence. An immediate return guarantees the first occurrence.
  4. When n is zero the loop executes no iterations, so the function safely returns -1. The duplicate sample returns 0.
Model C answer
#include <stdio.h>
static int find_first(const int a[], int n, int target) {
    for (int i = 0; i < n; ++i) {
        if (a[i] == target) return i;
    }
    return -1;
}
int main(void) {
    int a[8], n, target;
    if (scanf("%d", &n) != 1 || n < 0 || n > 8) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%d", &a[i]) != 1 || a[i] < -100 || a[i] > 100) return 1;
    }
    if (scanf("%d", &target) != 1 || target < -100 || target > 100) return 1;
    printf("%d\n", find_first(a, n, target));
    return 0;
}

Common mistakes

  • Do not read a[0] merely to initialize a search when n can be zero.
  • Do not print a last-occurrence result while describing a first-occurrence contract.

Before calling this one solid

  • I identified bounds, sentinel and duplicate-handling defects separately.
  • My function returns -1 for both empty and absent cases.
  • My driver reads exactly n elements and prints one index.

Reference program checked with GCC and Clang in C17 mode.

M6-05TraceCore~14 minSelection sort: each chosen minimum and every stateNot attempted

Produce a pass table with outer index i, selected minimum index before swapping, array after the pass, and whether a swap occurred. Give the exact output and count comparisons between array values separately from swaps. Explain what is guaranteed about the prefix after pass i+1, and why a strict < comparison keeps the first minimum in the current suffix. Here min is an index, not the minimum value.

C
#include <stdio.h>
int main(void) {
    int a[5] = {7, 3, 7, 1, 3};
    int comparisons = 0, swaps = 0;
    for (int i = 0; i < 4; ++i) {
        int min = i;
        for (int j = i + 1; j < 5; ++j) {
            ++comparisons;
            if (a[j] < a[min]) min = j;
        }
        if (min != i) {
            int temp = a[i]; a[i] = a[min]; a[min] = temp;
            ++swaps;
        }
        printf("pass=%d min=%d:", i + 1, min);
        for (int j = 0; j < 5; ++j) printf(" %d", a[j]);
        putchar('\n');
    }
    printf("comparisons=%d swaps=%d\n", comparisons, swaps);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

At the beginning of each pass, only the suffix starting at i is searched.

Hint 2

On the duplicate 3 values in pass 2, a later equal value does not replace the current minimum because the test is strict.

Worked solution & self-marking checklist

The selected indices are 3,1,4,3. Selection sort performs ten value comparisons and two swaps.

Reason it through

  1. Pass 1 compares 3,7,1,3 with the best-so-far value and selects index 3. Swapping gives {1,3,7,7,3}.
  2. Pass 2 searches indices 1..4. Index 1 already contains the first minimum 3, so there is no swap and the array is unchanged.
  3. Pass 3 selects index 4 and swaps its 3 with the 7 at index 2, producing {1,3,3,7,7}. Pass 4 selects index 3 and does not swap.
  4. The inner loops make 4+3+2+1=10 value comparisons. After a pass, the prefix through i contains the smallest i+1 values in ascending order, each no larger than the remaining suffix.
Model C answer
#include <stdio.h>
int main(void) {
    int a[5] = {7, 3, 7, 1, 3};
    int comparisons = 0, swaps = 0;
    for (int i = 0; i < 4; ++i) {
        int min = i;
        for (int j = i + 1; j < 5; ++j) {
            ++comparisons;
            if (a[j] < a[min]) min = j;
        }
        if (min != i) {
            int temp = a[i]; a[i] = a[min]; a[min] = temp;
            ++swaps;
        }
        printf("pass=%d min=%d:", i + 1, min);
        for (int j = 0; j < 5; ++j) printf(" %d", a[j]);
        putchar('\n');
    }
    printf("comparisons=%d swaps=%d\n", comparisons, swaps);
    return 0;
}

Expected output

pass=1 min=3: 1 3 7 7 3
pass=2 min=1: 1 3 7 7 3
pass=3 min=4: 1 3 3 7 7
pass=4 min=3: 1 3 3 7 7
comparisons=10 swaps=2

Common mistakes

  • The minimum index is measured in the current array before that pass’s swap.
  • Sorted input or duplicate values do not reduce this implementation’s number of value comparisons.

Before calling this one solid

  • My table has all four passes, including unchanged states.
  • I recorded selected indices rather than just selected values.
  • I separated ten comparisons from two swaps and stated the prefix guarantee.

Reference program checked with GCC and Clang in C17 mode.

M6-06Write CStretch~20 minWrite a counted selection-sort functionNot attempted

Write selection_sort(int a[], int n, int counts[2]) for ascending integer order. counts[0] must receive the number of a[j]<a[min] comparisons and counts[1] the number of actual exchanges between different indices; use the first minimum when equal values occur. The caller supplies 0<=n<=8 and n values in [-100,100]. Write a complete program that reads that input and prints sorted: followed by each value prefixed with one space, then a line comparisons=C swaps=S. Empty input data must produce sorted: with no following space. Explain why n=0 and n=1 are safe and derive the comparison count for general n>=1.

Link to this question
Saves in this browser
Hint 1

Initialize both counters even when no sorting pass runs. The suffix starts at i, and the scan starts at i+1.

Hint 2

Use i+1<n for the outer loop. Add one comparison inside the inner loop and one swap only when min differs from i.

Worked solution & self-marking checklist

Count operations where they occur. The algorithm works for zero or one element without accessing any element.

Reason it through

  1. Set both output counters to zero before the loops; an array output parameter lets the caller receive both counts.
  2. For each i with i+1<n, find the index of the first smallest value in a[i..n-1], then exchange only if that index differs from i.
  3. For n>=1 the number of comparisons is (n-1)+(n-2)+...+1=n(n-1)/2, independent of the data order. With n=0 it is also zero by direct loop analysis.
  4. The outer condition is false for lengths zero and one, so there is no minimum read, exchange or inner-loop access in those cases.
Model C answer
#include <stdio.h>
static void selection_sort(int a[], int n, int counts[2]) {
    counts[0] = 0;
    counts[1] = 0;
    for (int i = 0; i + 1 < n; ++i) {
        int min = i;
        for (int j = i + 1; j < n; ++j) {
            ++counts[0];
            if (a[j] < a[min]) min = j;
        }
        if (min != i) {
            int temp = a[i]; a[i] = a[min]; a[min] = temp;
            ++counts[1];
        }
    }
}
int main(void) {
    int a[8], n, counts[2];
    if (scanf("%d", &n) != 1 || n < 0 || n > 8) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%d", &a[i]) != 1 || a[i] < -100 || a[i] > 100) return 1;
    }
    selection_sort(a, n, counts);
    printf("sorted:");
    for (int i = 0; i < n; ++i) printf(" %d", a[i]);
    printf("\ncomparisons=%d swaps=%d\n", counts[0], counts[1]);
    return 0;
}

Common mistakes

  • Do not count an unnecessary self-exchange as an actual swap under this contract.
  • Do not leave counts uninitialized on the empty-array path.

Before calling this one solid

  • I implemented the sort as the requested function.
  • My counters match sorted, reversed, duplicate, singleton and empty examples.
  • I justified bounds and the comparison formula.

Reference program checked with GCC and Clang in C17 mode.

M6-07TraceFoundation~9 minA character array has storage beyond its terminatorNot attempted

Draw all five elements of code, distinguishing the null character from the digit character zero. Trace length and sum, give the exact output, and explain why code[4] exists but does not appear in the %s field. Justify code[length]-'0' and '0'+sum%10 without assuming ASCII. All characters examined by the loop before its terminator are decimal digits.

C
#include <stdio.h>
int main(void) {
    char code[5] = {'5', '0', '8', '\0', '9'};
    int sum = 0, length = 0;
    while (length < 5 && code[length] != '\0') {
        sum += code[length] - '0';
        ++length;
    }
    code[1] = (char)('0' + sum % 10);
    printf("length=%d sum=%d code=%s tail=%c\n", length, sum, code, code[4]);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

A string ends at its first null character, even when the containing character array has additional elements.

Hint 2

C guarantees consecutive increasing codes for the decimal digits. It does not require ASCII for this digit conversion.

Worked solution & self-marking checklist

The loop reads three digits, obtaining sum 13; replacing index 1 with digit 3 changes the visible string to 538.

Reason it through

  1. The array positions are 0:'5', 1:'0', 2:'8', 3:'\0', 4:'9'. The digit '0' is not the null character.
  2. The successive digit values are 5,0,8. length becomes 3 and sum becomes 13; the loop stops before index 3 contributes anything.
  3. Because decimal digits are consecutive in the execution character set, subtracting '0' gives each digit’s numeric value, and adding a value 0..9 to '0' creates that digit character.
  4. The remainder is 3, so code[1] becomes the character 3. %s stops at index 3, while the separate %c prints the valid stored element at index 4.
Model C answer
#include <stdio.h>
int main(void) {
    char code[5] = {'5', '0', '8', '\0', '9'};
    int sum = 0, length = 0;
    while (length < 5 && code[length] != '\0') {
        sum += code[length] - '0';
        ++length;
    }
    code[1] = (char)('0' + sum % 10);
    printf("length=%d sum=%d code=%s tail=%c\n", length, sum, code, code[4]);
    return 0;
}

Expected output

length=3 sum=13 code=538 tail=9

Common mistakes

  • Do not confuse '\0', '0' and the integer value 0 when describing the stored character and visible text.
  • Do not assume %s prints every byte in the containing array.

Before calling this one solid

  • I labelled all five array elements.
  • I traced three digit contributions and the later replacement.
  • I justified portable digit arithmetic and both printed fields.

Reference program checked with GCC and Clang in C17 mode.

M6-08Write CCore~16 minCompact an array while preserving retained orderNot attempted

Write keep_nonnegative(int a[], int n), which removes negative values from the logical sequence in place, preserves the relative order of the retained values, and returns the new logical length. No second data array is allowed. Storage after the new length may contain any old values and must not be printed as retained data. Input is 0<=n<=10 followed by n values in [-100,100]. Print length=L values: followed by each retained value with one preceding space and a newline. For the mixed sample 6 / -2 0 5 -1 0 4, trace the read index and next write index. Explain why writing cannot overwrite an unread value.

Link to this question
Saves in this browser
Hint 1

Use one index to inspect every original element and another to count the accepted prefix.

Hint 2

Before each iteration, used<=read. Copy an accepted element to a[used] and then increment used.

Worked solution & self-marking checklist

A read index and a write-count index compact the accepted elements into the prefix without moving ahead of unread data.

Reason it through

  1. Initialize used=0. At each read index, ignore a negative element and otherwise copy it to a[used], then increment used.
  2. For {-2,0,5,-1,0,4}, used after each read is 0,1,2,2,3,4. The retained prefix becomes {0,5,0,4}.
  3. Before each read, used<=read, so a write targets the current element or an earlier position. No later unread element is overwritten.
  4. The allocated capacity remains ten; the logical sequence length becomes used. With all negative values or n=0, used remains zero.
Model C answer
#include <stdio.h>
static int keep_nonnegative(int a[], int n) {
    int used = 0;
    for (int read = 0; read < n; ++read) {
        if (a[read] >= 0) {
            a[used] = a[read];
            ++used;
        }
    }
    return used;
}
int main(void) {
    int a[10], n;
    if (scanf("%d", &n) != 1 || n < 0 || n > 10) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%d", &a[i]) != 1 || a[i] < -100 || a[i] > 100) return 1;
    }
    int used = keep_nonnegative(a, n);
    printf("length=%d values:", used);
    for (int i = 0; i < used; ++i) printf(" %d", a[i]);
    putchar('\n');
    return 0;
}

Common mistakes

  • Zero is retained because the condition is >=0, not >0.
  • Do not inspect or print the stale suffix as though it were part of the compacted sequence.

Before calling this one solid

  • I preserved the order of zeros and positive values.
  • I returned and used the new logical length.
  • I explained the used<=read safety argument.

Reference program checked with GCC and Clang in C17 mode.

M6-09Judge every claimCore~12 minJudge array claims independentlyNot attempted

Judge EACH claim true or false and justify each judgment with a rule or a small counterexample. A: In a block, int a[4]={2,4}; makes a[2] and a[3] zero. B: For two declared int arrays a and b of length four, a=b; copies all four elements. C: Every valid neighboring pair a[i],a[i+1] is separated by sizeof a[0] bytes. D: void f(int a[10]) automatically prevents a caller from passing an array with only three elements. E: A linear search for the first occurrence can return immediately when it finds a match. F: In a function parameter declared int a[], sizeof a / sizeof a[0] reliably gives the caller’s array length. The claims are independent; more than one may be true.

Link to this question
Saves in this browser
Hint 1

Separate properties of an actual declared array from properties of an array parameter.

Hint 2

Array assignment, array initialization, and element-by-element copying are three different operations.

Worked solution & self-marking checklist

A true; B false; C true; D false; E true; F false.

Reason it through

  1. A is true: a partial initializer zero-initializes the remaining elements, including elements of a local automatic array.
  2. B is false: arrays are not assignable as whole objects. Copy with a loop or an appropriate library operation; initialization syntax is not later assignment.
  3. C is true: array elements are contiguous, with each element occupying sizeof a[0] bytes.
  4. D is false: the parameter is adjusted to a pointer type. The written 10 does not automatically check the actual extent; the function must respect a valid caller/function length contract.
  5. E is true: the first match encountered by an increasing-index search is the first occurrence. F is false: sizeof the adjusted parameter measures a pointer, so the quotient is not a length calculation.

Common mistakes

  • Do not pick a single true statement: each claim needs its own judgment.
  • Do not treat the bracket number in an ordinary array parameter as a run-time bounds check.

Before calling this one solid

  • I marked all six claims independently.
  • I distinguished array assignment from initialization.
  • I explained both array-parameter claims without guessing pointer sizes.
M6-10Design & integrateStretch~23 minDesign an earliest longest-plateau reportNot attempted

Original practice scenario: a sensor logs at most twelve integer readings. A plateau is a maximal consecutive run of equal values. Design and write a function that reports the start index, length and value of the longest plateau; break length ties by earliest start. Preserve the input array. Use a three-int result array and return length zero for an empty log. Write a full program reading 0<=n<=12 and n values in [-100,100]. Print EMPTY when n=0; otherwise print start=S length=L value=V. Explain how your algorithm closes the final plateau without reading a[n]. The tie sample is 8 / 5 5 2 2 9 9 9 1.

Link to this question
Saves in this browser
Hint 1

Keep the start of the current run and the best run found so far. A run ends when the next value changes or the data end is reached.

Hint 2

At the end boundary, test i==n before any a[i] access. Replace the best only for a strictly longer run, so earlier ties survive.

Worked solution & self-marking checklist

Scan run boundaries once; record only strictly longer runs and use a short-circuit end check to close the last run safely.

Reason it through

  1. For n=0, write result length zero and return before inspecting any element. For nonempty input, initialize the best to the first one-element run.
  2. Track start for the current run. At each boundary i, its length is i-start. If that length is greater than the best, record start and length.
  3. The condition i==n || a[i]!=a[start] uses short-circuit evaluation. At i=n, the left side is true and a[n] is never evaluated.
  4. After a boundary, begin the next run at i. Keeping the old best on equal lengths enforces earliest-start ties. The stated sample has start 4, length 3 and value 9.
  5. Return the value at the saved best start, not the last current-run value; the input itself remains unchanged.
Model C answer
#include <stdio.h>
static void longest_run(const int a[], int n, int result[3]) {
    result[0] = 0; result[1] = 0; result[2] = 0;
    if (n == 0) return;
    int start = 0, best_start = 0, best_length = 1;
    for (int i = 1; i <= n; ++i) {
        if (i == n || a[i] != a[start]) {
            int length = i - start;
            if (length > best_length) {
                best_start = start;
                best_length = length;
            }
            start = i;
        }
    }
    result[0] = best_start;
    result[1] = best_length;
    result[2] = a[best_start];
}
int main(void) {
    int a[12], n, result[3];
    if (scanf("%d", &n) != 1 || n < 0 || n > 12) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%d", &a[i]) != 1 || a[i] < -100 || a[i] > 100) return 1;
    }
    longest_run(a, n, result);
    if (result[1] == 0) puts("EMPTY");
    else printf("start=%d length=%d value=%d\n", result[0], result[1], result[2]);
    return 0;
}

Common mistakes

  • Do not require the last run to be followed by a different stored value: the end of the array also closes a run.
  • Using >= for best-length replacement selects the latest equal-length run instead of the earliest.

Before calling this one solid

  • I handled empty, singleton, all-equal and final-longest cases.
  • I preserved the input and returned all three requested results.
  • I justified final-boundary safety and the tie rule.

Reference program checked with GCC and Clang in C17 mode.

07

Matrices & strings

Row-major layout, matrix loops, safe string handling · 10 questions

M7-01TraceFoundation~10 minRead a row-major map in both directionsNot attempted

Trace the updates and give the exact output. Draw the row-major sequence of all six values after the updates. If B is the byte address of grid[0][0] and S=sizeof(int), give the byte-address formula for grid[r][c] and the offset of grid[1][2]. An element has row-major element offset 4: identify its row and column. Explain why the multiplier is three rather than two; no numeric int byte size is supplied.

C
#include <stdio.h>
int main(void) {
    int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int r = 0; r < 2; ++r) {
        for (int c = 0; c < 3; ++c) {
            grid[r][c] += 10 * r + c;
        }
    }
    for (int r = 0; r < 2; ++r) {
        for (int c = 0; c < 3; ++c) {
            printf("(%d,%d)=%d offset=%d\n", r, c, grid[r][c], r * 3 + c);
        }
    }
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The last subscript varies fastest in row-major order. Each complete row contains three integers.

Hint 2

The element offset is r*3+c. Recover r and c with integer division and remainder by three.

Worked solution & self-marking checklist

The final rows are {1,3,5} and {14,16,18}; grid[r][c] is at conceptual byte address B+(r*3+c)*S.

Reason it through

  1. For r=0 the added amounts are 0,1,2, producing 1,3,5. For r=1 the added amounts are 10,11,12, producing 14,16,18.
  2. The row-major sequence is 1,3,5,14,16,18. Element offsets are 0 through 5 in that order.
  3. grid[1][2] has element offset 1*3+2=5 and byte offset 5S. An offset of 4 gives row 4/3=1 and column 4%3=1.
  4. The multiplier is the number of columns, since advancing one row skips three elements, regardless of the number of rows.
Model C answer
#include <stdio.h>
int main(void) {
    int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int r = 0; r < 2; ++r) {
        for (int c = 0; c < 3; ++c) {
            grid[r][c] += 10 * r + c;
        }
    }
    for (int r = 0; r < 2; ++r) {
        for (int c = 0; c < 3; ++c) {
            printf("(%d,%d)=%d offset=%d\n", r, c, grid[r][c], r * 3 + c);
        }
    }
    return 0;
}

Expected output

(0,0)=1 offset=0
(0,1)=3 offset=1
(0,2)=5 offset=2
(1,0)=14 offset=3
(1,1)=16 offset=4
(1,2)=18 offset=5

Common mistakes

  • Do not multiply the row index by the number of rows.
  • Do not confuse element offset 5 with byte offset 5 when sizeof(int) is unspecified.

Before calling this one solid

  • I gave six updated values in the correct storage order.
  • I derived the forward address formula and reverse mapping.
  • I kept element offsets separate from byte offsets.

Reference program checked with GCC and Clang in C17 mode.

M7-02Judge every claimCore~13 minJudge dimensions, strings and storage independentlyNot attempted

Judge EACH independent claim true or false and justify it. A: int cube[2][3][4]; contains 24 int elements, and cube[i][j][k] has row-major element offset (i*3+j)*4+k for valid indices. B: In void show(int a[][3], int rows), the trailing dimension three tells the function the width of each row. C: A 2x3 matrix can be multiplied by a 2x4 matrix, producing a 3x4 matrix. D: char s[3]="cat"; is valid C initialization of a character array, but it does not create a null-terminated C string. E: strlen(s) includes the terminating null character in its result. F: char names[4][9]; has space for four simultaneously stored strings of at most eight characters each, when each row is terminated correctly. Do not call a string function on an array that lacks a terminator.

Link to this question
Saves in this browser
Hint 1

For matrix multiplication, compare the first matrix’s column count with the second matrix’s row count.

Hint 2

Separate the storage bytes required for text from the count of visible characters returned by strlen.

Worked solution & self-marking checklist

A true; B true; C false; D true; E false; F true.

Reason it through

  1. A is true: 2*3*4=24 elements. The first index skips blocks of 12 elements, the second skips rows of four, and the third selects within a row.
  2. B is true: the adjusted parameter accesses rows whose type is an array of three int elements. Its row width is needed for indexing; rows still supplies the logical row count.
  3. C is false: the inner dimensions are 3 and 2, so the product is not defined. A 2x3 matrix times a 3x4 matrix would produce a 2x4 matrix.
  4. D is true: C permits a character array to be initialized by exactly the non-null characters of a literal when there is no room for its null terminator. Passing this array alone to strlen or %s would violate the string requirement.
  5. E is false: strlen counts characters before the first null character, not the terminator. F is true: each of the four nine-char rows can hold eight text characters plus a null terminator.

Common mistakes

  • Do not assume matching outer matrix dimensions are sufficient for multiplication.
  • Do not infer that a valid char-array declaration necessarily provides a valid C string.

Before calling this one solid

  • I judged all six statements separately.
  • I explained the 3D offset formula and matrix compatibility.
  • I distinguished capacity, text length and null termination.
M7-03Write CCore~15 minWrite matrix addition with logical dimensionsNot attempted

Write a complete program for adding two equally shaped matrices. Input gives rows and cols, each 1..3, then all entries of A in row-major order followed by all entries of B in row-major order. Entries lie in [-20,20]. Use fixed-capacity int arrays [3][3] and traverse only the requested rectangle. Print the sum matrix with one space between values, no leading/trailing spaces, and one row per line. For the named rectangle sample, input is 2 3 / 1 2 3 / 4 5 6 / 6 5 4 / 3 2 1. State the dimension condition for addition, and distinguish the allocated row width from the logical number of columns.

Link to this question
Saves in this browser
Hint 1

Addition combines corresponding positions; both operands must have the same rows and columns.

Hint 2

Use r<rows and c<cols even though every allocated row has capacity three. Compute sum[r][c]=a[r][c]+b[r][c].

Worked solution & self-marking checklist

Use matching row and column loops to compute one output element from each corresponding pair of input elements.

Reason it through

  1. An R by C matrix can be added to another R by C matrix. There is no summation over a third index in matrix addition.
  2. Read A’s R*C entries, then B’s R*C entries. An allocated width of three allows any requested width 1..3 but does not turn unused columns into logical data.
  3. For each valid pair r,c, store a[r][c]+b[r][c]. The largest absolute result is 40 under the input bounds.
  4. The rectangle sample produces two rows of 7 7 7. A 1x1 input exercises the smallest nonempty matrix and a 3x1 input checks single-column traversal.
Model C answer
#include <stdio.h>
int main(void) {
    int a[3][3], b[3][3], sum[3][3], rows, cols;
    if (scanf("%d%d", &rows, &cols) != 2 || rows < 1 || rows > 3 || cols < 1 || cols > 3) return 1;
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            if (scanf("%d", &a[r][c]) != 1 || a[r][c] < -20 || a[r][c] > 20) return 1;
        }
    }
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            if (scanf("%d", &b[r][c]) != 1 || b[r][c] < -20 || b[r][c] > 20) return 1;
            sum[r][c] = a[r][c] + b[r][c];
        }
    }
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) printf("%s%d", c == 0 ? "" : " ", sum[r][c]);
        putchar('\n');
    }
    return 0;
}

Common mistakes

  • Do not read alternating A/B entries when the specified input contains the entire A matrix before B.
  • Do not iterate all three columns when cols is smaller than three.

Before calling this one solid

  • I used exactly rows*cols entries from each matrix.
  • I stated equal-shape compatibility.
  • My spacing and row breaks match the output contract.

Reference program checked with GCC and Clang in C17 mode.

M7-04TraceCore~15 minTrace every product in a rectangular matrix multiplicationNot attempted

Give the dimensions of A, B and product. For EACH of the four output elements, list the three scalar products in evaluation order and the running sum after each product. Then give the exact output. Explain the distinct roles of r, c and k, and why product[r][c]=0 belongs inside the c loop but outside the k loop. Do not replace matrix multiplication with elementwise multiplication.

C
#include <stdio.h>
int main(void) {
    int a[2][3] = {{1, 2, 0}, {-1, 3, 2}};
    int b[3][2] = {{2, 1}, {0, 4}, {5, -2}};
    int product[2][2];
    for (int r = 0; r < 2; ++r) {
        for (int c = 0; c < 2; ++c) {
            product[r][c] = 0;
            for (int k = 0; k < 3; ++k) {
                product[r][c] += a[r][k] * b[k][c];
            }
        }
    }
    for (int r = 0; r < 2; ++r) {
        printf("%d %d\n", product[r][0], product[r][1]);
    }
    return 0;
}
Link to this question
Saves in this browser
Hint 1

Fixing r selects a row of A; fixing c selects a column of B. Only k changes during one dot product.

Hint 2

For product[1][1], evaluate (-1)*1, 3*4 and 2*(-2), adding each to a fresh accumulator.

Worked solution & self-marking checklist

A is 2x3, B is 3x2 and the product is 2x2, with rows {2,9} and {8,7}.

Reason it through

  1. For product[0][0], the terms are 1*2=2, 2*0=0, 0*5=0; running sums are 2,2,2.
  2. For product[0][1], the terms are 1*1=1, 2*4=8, 0*(-2)=0; running sums are 1,9,9.
  3. For product[1][0], the terms are (-1)*2=-2, 3*0=0, 2*5=10; running sums are -2,-2,8.
  4. For product[1][1], the terms are (-1)*1=-1, 3*4=12, 2*(-2)=-4; running sums are -1,11,7.
  5. r chooses an output row, c an output column, and k traverses the common dimension three. Resetting once per output cell starts its dot product at zero; resetting inside the k loop would erase previous terms.
Model C answer
#include <stdio.h>
int main(void) {
    int a[2][3] = {{1, 2, 0}, {-1, 3, 2}};
    int b[3][2] = {{2, 1}, {0, 4}, {5, -2}};
    int product[2][2];
    for (int r = 0; r < 2; ++r) {
        for (int c = 0; c < 2; ++c) {
            product[r][c] = 0;
            for (int k = 0; k < 3; ++k) {
                product[r][c] += a[r][k] * b[k][c];
            }
        }
    }
    for (int r = 0; r < 2; ++r) {
        printf("%d %d\n", product[r][0], product[r][1]);
    }
    return 0;
}

Expected output

2 9
8 7

Common mistakes

  • Do not use a[r][c]*b[r][c] as the matrix-product formula.
  • Do not carry a previous cell’s accumulator into the next cell.

Before calling this one solid

  • I showed all twelve scalar products and intermediate sums.
  • I stated all three matrix shapes.
  • I explained all loop indices and the accumulator-reset location.

Reference program checked with GCC and Clang in C17 mode.

M7-05Debug & repairStretch~22 minRepair a multiplication that only seems right for square matricesNot attempted

product is an uninitialized local array. Identify and repair three independent errors in the fragment, without executing it or predicting a reliable output. Explain why tests with equal dimensions may hide two of the errors. Write a complete corrected program: input gives rows, common and cols (all 1..3), then A’s rows*common entries and B’s common*cols entries in row-major order. Every entry lies in [-10,10]. Print the rows by cols product with spaces between values and a newline after each row. Justify that the largest possible dot-product magnitude fits in a C int under these limits.

C
/* A has logical shape rows x common; B has common x cols.
   All arrays have allocated type int [3][3]. */
for (int r = 0; r < rows; ++r) {
    for (int c = 0; c < common; ++c) {
        for (int k = 0; k < cols; ++k) {
            product[r][c] += a[r][k] * b[k][c];
        }
    }
}
Link to this question
Saves in this browser
Hint 1

The output-column loop is controlled by cols; the dot-product loop is controlled by common.

Hint 2

Each product[r][c] needs zero initialization before its additions. Test 2x1 times 1x3 to separate the loop roles.

Worked solution & self-marking checklist

Use c<cols, k<common, and initialize each accumulator to zero before its k loop.

Reason it through

  1. The original c loop incorrectly uses common. It may omit output columns or compute columns outside the logical output rectangle.
  2. The original k loop incorrectly uses cols. It may omit terms or read entries outside the initialized logical operand rectangles.
  3. The += operation reads an uninitialized product element. Set product[r][c]=0 once before accumulating that cell.
  4. When common equals cols, exchanging these bounds happens to produce the same counts, so a square-only test set misses the dimension errors. It still does not repair uninitialized reads.
  5. Each scalar product has absolute value at most 100, and there are at most three terms. A magnitude at most 300 fits even the minimum C-required int range.
Model C answer
#include <stdio.h>
int main(void) {
    int a[3][3], b[3][3], product[3][3];
    int rows, common, cols;
    if (scanf("%d%d%d", &rows, &common, &cols) != 3 ||
        rows < 1 || rows > 3 || common < 1 || common > 3 || cols < 1 || cols > 3) return 1;
    for (int r = 0; r < rows; ++r) {
        for (int k = 0; k < common; ++k) {
            if (scanf("%d", &a[r][k]) != 1 || a[r][k] < -10 || a[r][k] > 10) return 1;
        }
    }
    for (int k = 0; k < common; ++k) {
        for (int c = 0; c < cols; ++c) {
            if (scanf("%d", &b[k][c]) != 1 || b[k][c] < -10 || b[k][c] > 10) return 1;
        }
    }
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            product[r][c] = 0;
            for (int k = 0; k < common; ++k) product[r][c] += a[r][k] * b[k][c];
        }
    }
    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) printf("%s%d", c == 0 ? "" : " ", product[r][c]);
        putchar('\n');
    }
    return 0;
}

Common mistakes

  • Allocated capacity does not make unused input positions initialized matrix entries.
  • Do not clear the accumulator within the k loop or leave it initialized only for the first column.

Before calling this one solid

  • I repaired all three defects and explained why the broken output is unreliable.
  • I tested unequal common and output-column dimensions.
  • I proved the arithmetic bound and printed the right output shape.

Reference program checked with GCC and Clang in C17 mode.

M7-06TraceFoundation~10 minA changed terminator reveals stored charactersNot attempted

Draw all eight char elements after initialization, give the exact output, and explain how one assignment changes strlen from its original value. Distinguish sizeof text from strlen(text), and explain why both calls to %s are safe here. What does strcmp guarantee when strings are equal, and why should portable code test its sign rather than assume unequal results are exactly -1 or 1?

C
#include <stdio.h>
#include <string.h>
int main(void) {
    char text[8] = {'c', 'a', 't', '\0', 'x', '\0'};
    printf("before=%s length=%zu capacity=%zu\n", text, strlen(text), sizeof text);
    text[3] = 's';
    printf("after=%s length=%zu\n", text, strlen(text));
    int relation = strcmp(text, "catsx");
    printf("equal=%d\n", relation == 0);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The missing initializer elements become null characters. Find the first null character before and after text[3] changes.

Hint 2

sizeof the actual char array gives its capacity in bytes; strlen searches for the first terminator and counts preceding characters.

Worked solution & self-marking checklist

The first terminator initially occurs at index 3; replacing it exposes the stored x, and the terminator at index 5 ends the new string.

Reason it through

  1. The eight elements are 'c','a','t','\0','x','\0','\0','\0'. A char occupies one C byte, so sizeof text is exactly 8.
  2. The first strlen stops at index 3 and returns 3. %s similarly displays cat.
  3. After text[3]='s', indices 0..4 spell catsx and index 5 remains null, so strlen is 5 and %s displays catsx. Both strings have a terminator within the array.
  4. strcmp(text,"catsx") returns zero because the strings match. For unequal strings, only negative versus positive versus zero is specified; the magnitude of a nonzero result is not fixed.
Model C answer
#include <stdio.h>
#include <string.h>
int main(void) {
    char text[8] = {'c', 'a', 't', '\0', 'x', '\0'};
    printf("before=%s length=%zu capacity=%zu\n", text, strlen(text), sizeof text);
    text[3] = 's';
    printf("after=%s length=%zu\n", text, strlen(text));
    int relation = strcmp(text, "catsx");
    printf("equal=%d\n", relation == 0);
    return 0;
}

Expected output

before=cat length=3 capacity=8
after=catsx length=5
equal=1

Common mistakes

  • Do not count the terminator in strlen or confuse string length with eight-byte capacity.
  • Do not assume strcmp returns only the three exact values -1,0,1.

Before calling this one solid

  • I drew all eight initialized elements.
  • I explained both terminator positions and safe %s use.
  • I distinguished sizeof, strlen and the strcmp sign contract.

Reference program checked with GCC and Clang in C17 mode.

M7-07Debug & repairStretch~24 minRead a full line and detect exact-fit versus truncationNot attempted

The fragment is intended to read one full name, including spaces, into capacity eight and remove only an input newline. Diagnose why it cannot meet that contract; do not run it on unsafe input. Write a replacement full program for ordinary text without embedded null characters. Accept a first line with 0..7 text characters, terminated by newline or EOF, and print length|text followed by a newline. With no characters available at EOF, print NO INPUT. If the line has more than seven text characters, consume the rest of that line and print TOO LONG. Distinguish seven characters followed by newline from a genuinely longer line. Examples: Ada Lov is exactly seven characters; Ada Love is eight. No interactive prompts are printed.

C
char name[8];
scanf("%s", name);
name[strlen(name) - 1] = '\0';
printf("[%s]\n", name);
Link to this question
Saves in this browser
Hint 1

An unbounded %s can overflow and stops at whitespace; it does not save a newline that can safely be removed by deleting the last character.

Hint 2

fgets stores at most capacity-1 characters. If it stored no newline, read one more character: newline or EOF means exact fit, while another character means the line was too long.

Worked solution & self-marking checklist

Use bounded fgets, remove a newline only when found, and probe beyond a full buffer to distinguish an exact-fit line from truncation.

Reason it through

  1. The original %s is unbounded and reads only one whitespace-delimited token. It may fail without producing a string; deleting strlen(name)-1 is neither a reliable newline removal nor safe on failed input.
  2. After a successful fgets, strcspn finds the first newline or the existing terminator. Replace only an actual newline with a null character.
  3. If no newline was stored, getchar examines what follows. Newline or EOF completes an accepted line; any other character proves that at least eight text characters exist, so drain through newline or EOF and reject.
  4. An immediate EOF makes fgets return NULL and prints NO INPUT. An empty line is successful input and prints 0|. A seven-character final line without newline remains acceptable.
Model C answer
#include <stdio.h>
#include <string.h>
int main(void) {
    char name[8];
    if (fgets(name, sizeof name, stdin) == NULL) {
        puts("NO INPUT");
        return 0;
    }
    size_t end = strcspn(name, "\n");
    if (name[end] == '\n') {
        name[end] = '\0';
    } else {
        int ch = getchar();
        if (ch != '\n' && ch != EOF) {
            do { ch = getchar(); } while (ch != '\n' && ch != EOF);
            puts("TOO LONG");
            return 0;
        }
    }
    printf("%zu|%s\n", strlen(name), name);
    return 0;
}

Common mistakes

  • Do not delete the last stored character merely because no newline appears.
  • Do not classify every full buffer as too long: an exactly seven-character line fits the stated text capacity.

Before calling this one solid

  • I accept spaces, empty lines and exact seven-character lines.
  • I reject and consume overlong lines without overflow.
  • I check input failure before calling a string function.

Reference program checked with GCC and Clang in C17 mode.

M7-08Write CCore~18 minProve capacity before strcpy and strcatNot attempted

Write int join(char out[], size_t cap, const char left[], const char right[]). Inputs are valid null-terminated strings; out is a separate writable array that does not overlap either input, and cap is its actual capacity. Concatenate left and right with no separator only when both strings plus one terminator fit. Return 1 on success. On failure return 0 and, when cap>0, leave out as the empty string; with cap=0 do not access out. The function must also handle empty strings. Use strlen, strcpy and strcat only after the relevant capacity reasoning. Avoid adding two potentially large size_t lengths in the check. For a full driver, read two tokens of 1..15 characters using bounded input, join into char out[8], and print OK|result or NO ROOM. The driver’s stated input contract excludes longer tokens. Explain the exact-fit boundary.

Link to this question
Saves in this browser
Hint 1

If a characters have already been reserved, the remaining capacity is cap-a, and it must contain b characters plus a terminator.

Hint 2

Check cap==0 first, then a>=cap before evaluating cap-a. Reject b>=cap-a; this leaves room for the null character without forming a+b+1.

Worked solution & self-marking checklist

Require a<cap and b<cap-a; then copy left and append right into the proven capacity.

Reason it through

  1. Measure the two valid source strings. If cap is zero, return failure without accessing the destination.
  2. For positive capacity, initialize out[0] to the null character so every failure path leaves an empty output string.
  3. First reject a>=cap. Only if a<cap is cap-a meaningful as remaining capacity without unsigned underflow. Reject b>=cap-a to reserve one byte for the terminator.
  4. After both checks, strcpy and strcat operate on nonoverlapping valid strings with sufficient capacity. With capacity eight, seven total text characters fit exactly and eight do not.
  5. Empty sources require no special copy algorithm: strlen returns zero, and the same capacity condition correctly allows an empty result when cap>=1.
Model C answer
#include <stdio.h>
#include <string.h>
static int join(char out[], size_t cap, const char left[], const char right[]) {
    size_t a = strlen(left), b = strlen(right);
    if (cap == 0) return 0;
    out[0] = '\0';
    if (a >= cap || b >= cap - a) return 0;
    strcpy(out, left);
    strcat(out, right);
    return 1;
}
int main(void) {
    char left[16], right[16], out[8];
    if (scanf("%15s%15s", left, right) != 2) return 1;
    if (join(out, sizeof out, left, right)) printf("OK|%s\n", out);
    else puts("NO ROOM");
    return 0;
}

Common mistakes

  • Do not accept total text length equal to capacity: the terminator still needs one position.
  • Do not use strncpy as though it always creates a terminated string, or call strcat before proving destination capacity.

Before calling this one solid

  • I handle cap=0, empty sources and exact fit in the function contract.
  • I avoid size_t addition overflow and subtraction underflow in my check.
  • I call copying functions only after proving space for the terminator.

Reference program checked with GCC and Clang in C17 mode.

M7-09Write CCore~18 minSort an array of strings as text, not as numbersNot attempted

Write a selection-sort program for at most four product-code strings. Input is 0<=n<=4 followed by n tokens, each containing 1..9 decimal digits; these are identifiers, not numeric values. Store them in char code[4][10]. Sort by strcmp order and print codes: followed by the strings, each preceded by one space, then a newline. For the named code sample 4 / 42 7 105 42, explain the resulting order. Show how to swap complete rows legally, and justify every string-copy capacity. Decimal digits have their C-guaranteed increasing order; assume no wider alphabet ordering.

Link to this question
Saves in this browser
Hint 1

Use strcmp(x,y)<0 to compare string contents. A row is a char array, so whole-array assignment does not swap it.

Hint 2

A temporary char[10] plus three strcpy calls can exchange two valid rows, since each has at most nine text characters and a terminator.

Worked solution & self-marking checklist

Use selection sort on the string contents and copy rows through a correctly sized temporary array.

Reason it through

  1. The input width %9s reserves one of each row’s ten char positions for the terminator under the stated token-length contract.
  2. For each suffix, compare strings with strcmp and remember the index of the smallest text string. Do not compare the row addresses or convert the identifiers to integers.
  3. Swap by copying row i to temp, the selected row to row i, and temp to the selected row. All three arrays have capacity ten, so every valid stored string fits.
  4. The sample order is 105,42,42,7: character 1 precedes 4, which precedes 7. This is lexicographic string order, not the numeric ordering 7,42,42,105.
  5. When n=0 there are no input strings, sort passes or string accesses, and the sole output is codes: followed by a newline.
Model C answer
#include <stdio.h>
#include <string.h>
int main(void) {
    char code[4][10], temp[10];
    int n;
    if (scanf("%d", &n) != 1 || n < 0 || n > 4) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%9s", code[i]) != 1) return 1;
    }
    for (int i = 0; i + 1 < n; ++i) {
        int min = i;
        for (int j = i + 1; j < n; ++j) {
            if (strcmp(code[j], code[min]) < 0) min = j;
        }
        if (min != i) {
            strcpy(temp, code[i]);
            strcpy(code[i], code[min]);
            strcpy(code[min], temp);
        }
    }
    printf("codes:");
    for (int i = 0; i < n; ++i) printf(" %s", code[i]);
    putchar('\n');
    return 0;
}

Common mistakes

  • Do not write code[i]=code[min]; arrays cannot be assigned directly.
  • Do not assume an unbounded %s becomes safe merely because the rows have a declared capacity.

Before calling this one solid

  • I used bounded string input and strcmp content comparison.
  • I swapped complete terminated strings with proven capacities.
  • I explained numeric versus text order and the empty case.

Reference program checked with GCC and Clang in C17 mode.

M7-10Design & integrateStretch~22 minNormalize spaces without losing word boundariesNot attempted

Original practice scenario: normalize a short club notice. The input is one available text line of at most 63 text characters, with no embedded null character and no tabs; only the ordinary space character separates words. Remove leading and trailing spaces, replace every internal run of spaces by one space, and preserve all nonspace characters exactly. A word is a maximal nonspace run. Write a function that returns the word count and writes a terminated normalized string into a separate char[64]. Write a driver that reads the bounded line and prints words=N text=[normalized]. An empty or all-space line has zero words. Explain why the output cannot need more storage than the input text plus its terminator. You may rely on the stated maximum input length; do not silently claim this driver rejects longer lines.

Link to this question
Saves in this browser
Hint 1

Do not output a space immediately when you read one. Remember that a separator may be needed only if another word follows.

Hint 2

A pending-space flag after a written word lets you emit exactly one separator before the next nonspace character and discard trailing spaces.

Worked solution & self-marking checklist

Delay internal separators until the next word starts; this trims both ends, collapses runs and counts word starts in one pass.

Reason it through

  1. Start with an empty output, zero words and no pending separator. Leading spaces do not set a pending separator because no output word exists yet.
  2. After writing any text, a space sets pending_space. Further spaces leave it set without writing anything.
  3. On a nonspace character, count a new word if the output is empty or a separator is pending. Emit one pending separator, then the character, and clear the flag.
  4. At the end, ignore a pending separator and append a null character. An all-space line therefore becomes an empty string with zero words.
  5. Each output nonspace character comes from the input, and each emitted space represents at least one input space. Output length is at most input length, so a maximum 63-character result plus a terminator fits char[64]. The driver uses char[65] to also capture a possible newline after 63 text characters.
Model C answer
#include <stdio.h>
#include <string.h>
static int normalize(const char input[], char output[]) {
    size_t used = 0;
    int pending_space = 0, words = 0;
    for (size_t i = 0; input[i] != '\0'; ++i) {
        if (input[i] == ' ') {
            if (used > 0) pending_space = 1;
        } else {
            if (used == 0 || pending_space) ++words;
            if (pending_space) output[used++] = ' ';
            output[used++] = input[i];
            pending_space = 0;
        }
    }
    output[used] = '\0';
    return words;
}
int main(void) {
    char line[65], normalized[64];
    if (fgets(line, sizeof line, stdin) == NULL) return 1;
    line[strcspn(line, "\n")] = '\0';
    int words = normalize(line, normalized);
    printf("words=%d text=[%s]\n", words, normalized);
    return 0;
}

Common mistakes

  • Do not write a separator for every input space and try to repair multiple spaces afterward.
  • Do not forget the terminator for empty or all-space output.

Before calling this one solid

  • I handled leading, internal and trailing space runs.
  • I counted words rather than spaces and preserved nonspace characters.
  • I proved output capacity and stated the driver’s bounded-input assumption.

Reference program checked with GCC and Clang in C17 mode.

08

Structures & records

typedef, nested records, arrays, functions · 10 questions

M8-01TraceFoundation~10 minA copied record owns its embedded character arrayNot attempted

Give the exact output and draw the fields of a and b immediately after initialization and after both edits. Explain what typedef contributes, why a struct is useful for grouping a code, label and count, and why changing b.label does not change a.label. Contrast Bin b=a; with the later expression b=a;, and then with attempting a.label=b.label; as a direct assignment between arrays.

C
#include <stdio.h>
typedef struct {
    int code;
    char label[8];
    int units;
} Bin;
int main(void) {
    Bin a = {4, "pen", 3};
    Bin b = a;
    b.units += 2;
    b.label[0] = 'h';
    printf("a=%d %s %d\n", a.code, a.label, a.units);
    printf("b=%d %s %d\n", b.code, b.label, b.units);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

b is a distinct Bin object. Its label is an embedded array, not a separately shared string object.

Hint 2

C permits initialization and assignment of compatible structure values, including their array members as part of the structure value. Arrays on their own are not assignable.

Worked solution & self-marking checklist

Copying the Bin value copies all member values into a separate object. Only b becomes code 4, label hen, units 5.

Reason it through

  1. typedef introduces Bin as a type alias for the declared structure type; it does not allocate a record by itself.
  2. Initially a has code 4, label pen and units 3, and initialization copies those member values into b. A record keeps the related fields together as one value.
  3. b.units+=2 changes only b.units to 5. Replacing b.label[0] changes b’s own embedded array from pen to hen; a remains unchanged.
  4. Bin b=a initializes a new structure object; a later b=a assigns a compatible structure value to an existing object. Both are supported. The separate expression a.label=b.label is invalid because arrays themselves are not assignable; copy their characters with a capacity-safe operation instead.
Model C answer
#include <stdio.h>
typedef struct {
    int code;
    char label[8];
    int units;
} Bin;
int main(void) {
    Bin a = {4, "pen", 3};
    Bin b = a;
    b.units += 2;
    b.label[0] = 'h';
    printf("a=%d %s %d\n", a.code, a.label, a.units);
    printf("b=%d %s %d\n", b.code, b.label, b.units);
    return 0;
}

Expected output

a=4 pen 3
b=4 hen 5

Common mistakes

  • Do not treat the embedded label arrays as if both records must share one text buffer.
  • Do not generalize legal whole-struct assignment to legal stand-alone array assignment.

Before calling this one solid

  • I drew distinct a and b records and traced both edits.
  • I explained typedef and record grouping.
  • I distinguished struct initialization, struct assignment and forbidden array assignment.

Reference program checked with GCC and Clang in C17 mode.

M8-02Judge every claimCore~13 minJudge record declarations and operations independentlyNot attempted

Judge EACH independent claim true or false and explain it. A: typedef struct { int id; char name[12]; } Person; declares an alias Person, but no Person object. B: Two Person values can be compared for field-by-field equality using p==q. C: Assigning one Person value to another copies its embedded name array as part of the structure value. D: sizeof a structure always equals the sum of sizeof its members. E: A function taking Person p by value can change the caller’s p.id merely by assigning to its local p.id. F: Person group[5]; provides five records, each with its own twelve-char name array. You may assume p and q have the same structure type where they are mentioned; do not assume any fixed alignment or int byte size.

Link to this question
Saves in this browser
Hint 1

Whole-structure assignment is supported, but whole-structure equality is not a built-in C operation.

Hint 2

Member layout can include padding; a value parameter creates a separate local record value.

Worked solution & self-marking checklist

A true; B false; C true; D false; E false; F true.

Reason it through

  1. A is true: the typedef declaration creates a type alias, and a separate declaration such as Person p; is needed for an object.
  2. B is false: C does not define == for structure operands. Compare the relevant integer fields and compare terminated character-array contents with strcmp.
  3. C is true: compatible structure assignment copies member values, including embedded array contents as part of the structure. F is true: every array element is a distinct Person record with its own embedded array.
  4. D is false: implementations may insert internal and trailing padding to satisfy alignment. The actual size must be queried with sizeof; there is no universal fixed byte total.
  5. E is false: the structure parameter is a local value copy. Return the edited structure and assign it in the caller, or use a separately specified mutation interface.

Common mistakes

  • Do not judge these as a single-correct-choice question.
  • Do not infer portable structure size by adding assumed byte sizes for member types.

Before calling this one solid

  • I judged all six claims.
  • I distinguished assignment from equality and value copying from caller mutation.
  • I explained padding without inventing a fixed layout.
M8-03TraceCore~11 minTrace a nested record returned by a functionNot attempted

Trace the function parameter, original and moved as three record objects, and give the exact output. Explain both dots in moved.date.day. Identify which fields are copied and which are edited. If the call were move_one_day(original); with the result discarded, what would original contain afterward? This exercise deliberately uses day 12, so month rollover is outside its contract; do not describe the function as a complete calendar routine.

C
#include <stdio.h>
typedef struct {
    int day, month, year;
} Date;
typedef struct {
    int code;
    Date date;
    int seats;
} Booking;
static Booking move_one_day(Booking b) {
    ++b.date.day;
    b.seats -= 1;
    return b;
}
int main(void) {
    Booking original = {17, {12, 11, 2026}, 4};
    Booking moved = move_one_day(original);
    printf("original=%d %d/%d/%d seats=%d\n", original.code,
           original.date.day, original.date.month, original.date.year, original.seats);
    printf("moved=%d %d/%d/%d seats=%d\n", moved.code,
           moved.date.day, moved.date.month, moved.date.year, moved.seats);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

The function receives a copy of the entire Booking, including its Date member.

Hint 2

The returned value initializes moved. Nothing assigns that returned value back to original.

Worked solution & self-marking checklist

The local copy becomes November 13 with three seats; returning it creates moved, while original retains November 12 and four seats.

Reason it through

  1. The caller initializes original with code 17, nested date {12,11,2026} and seats 4. Passing it by value copies these fields into the parameter b.
  2. b.date.day accesses the day member inside the Date member date of b. It changes from 12 to 13; b.seats changes from 4 to 3.
  3. The code, month and year are copied unchanged. Returning b supplies a Booking value used to initialize moved.
  4. original is not edited. If the return value were discarded, original would still contain code 17, date 12/11/2026 and seats 4; the edits would disappear when the local parameter ceases to exist.
Model C answer
#include <stdio.h>
typedef struct {
    int day, month, year;
} Date;
typedef struct {
    int code;
    Date date;
    int seats;
} Booking;
static Booking move_one_day(Booking b) {
    ++b.date.day;
    b.seats -= 1;
    return b;
}
int main(void) {
    Booking original = {17, {12, 11, 2026}, 4};
    Booking moved = move_one_day(original);
    printf("original=%d %d/%d/%d seats=%d\n", original.code,
           original.date.day, original.date.month, original.date.year, original.seats);
    printf("moved=%d %d/%d/%d seats=%d\n", moved.code,
           moved.date.day, moved.date.month, moved.date.year, moved.seats);
    return 0;
}

Expected output

original=17 12/11/2026 seats=4
moved=17 13/11/2026 seats=3

Common mistakes

  • Do not assume returning a record also overwrites the argument object.
  • Do not claim that incrementing a day field handles arbitrary dates and month boundaries.

Before calling this one solid

  • I separated all three record objects.
  • I explained nested member access and copied versus edited fields.
  • I handled the discarded-return variant.

Reference program checked with GCC and Clang in C17 mode.

M8-04Write CCore~17 minScan records and return the earliest best recordNot attempted

Define a Student record with integer id and mark. Write a function returning the highest-mark Student from a nonempty array; ties must select the earliest input record. Also write a total-marks function. Your full program reads 0<=n<=6 and n id/mark pairs; ids are 1..999 and marks 0..100. Print EMPTY for n=0; otherwise print best=ID mark=M total=T. Never call the best-record function on an empty array; state that function’s precondition. Use const for array parameters that only read records. For the tie sample 4 / 11 70 / 12 92 / 13 92 / 14 40, explain why id 12 wins.

Link to this question
Saves in this browser
Hint 1

Initialize the best from the first record only after establishing that n is positive.

Hint 2

Replace the current best on strictly greater marks, leaving the first equal best untouched.

Worked solution & self-marking checklist

Initialize the nonempty scan with the first record and replace it only for a strictly higher mark.

Reason it through

  1. The record groups the identifier with its mark, so copying the best Student preserves the pair rather than returning a mark detached from its owner.
  2. best_student requires n>=1 and at least n valid records. Its initial a[0] read is therefore valid; main handles n=0 separately.
  3. With a strict greater-than comparison, id 12 becomes best at mark 92 and the later equal mark of id 13 does not replace it.
  4. A separate total scan adds all marks. The maximum total is 6*100=600, safely within the minimum required int range. const documents that neither scan edits the records.
Model C answer
#include <stdio.h>
typedef struct {
    int id;
    int mark;
} Student;
static Student best_student(const Student a[], int n) {
    Student best = a[0];
    for (int i = 1; i < n; ++i) {
        if (a[i].mark > best.mark) best = a[i];
    }
    return best;
}
static int total_marks(const Student a[], int n) {
    int total = 0;
    for (int i = 0; i < n; ++i) total += a[i].mark;
    return total;
}
int main(void) {
    Student a[6];
    int n;
    if (scanf("%d", &n) != 1 || n < 0 || n > 6) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%d%d", &a[i].id, &a[i].mark) != 2 ||
            a[i].id < 1 || a[i].id > 999 || a[i].mark < 0 || a[i].mark > 100) return 1;
    }
    if (n == 0) puts("EMPTY");
    else {
        Student best = best_student(a, n);
        printf("best=%d mark=%d total=%d\n", best.id, best.mark, total_marks(a, n));
    }
    return 0;
}

Common mistakes

  • Do not initialize the best by reading a[0] before checking for empty input.
  • Do not use >= when the tie contract requires the earliest record.

Before calling this one solid

  • I returned a complete Student value from the best function.
  • I stated and enforced the nonempty precondition.
  • I handled ties and the total correctly.

Reference program checked with GCC and Clang in C17 mode.

M8-05Debug & repairCore~13 minRepair restocking without changing the value-based interfaceNot attempted

The fragment compiles as part of a suitable program but fails to update the caller’s shelf record. Explain the cause with a caller/callee field snapshot. Repair it using a function that takes Item by value and returns the updated Item; do not introduce a pointer parameter for this exercise. Give both the new function declaration and the corrected call. Write a full driver reading id stock amount, where id is 1..999 and stock and amount are each 0..100. Print the id and resulting stock separated by a space and a newline. For input 8 3 4, show the caller before the call, parameter after its edit, and caller after assignment.

C
typedef struct { int id; int stock; } Item;
void restock(Item item, int amount) {
    item.stock += amount;
}
/* In main, shelf is an Item initialized from input. */
restock(shelf, amount);
/* The caller expects shelf.stock to have increased. */
Link to this question
Saves in this browser
Hint 1

The parameter item is a separate structure object whose fields initially have the same values as shelf.

Hint 2

The caller needs an explicit assignment such as shelf=restock(shelf,amount) to keep the returned value.

Worked solution & self-marking checklist

Return the modified structure and assign that value back to shelf in the caller.

Reason it through

  1. With input 8 3 4, shelf initially has {id=8,stock=3}; the parameter item receives a value copy of those fields.
  2. Editing item.stock changes the local parameter to {8,7}. In the original void function, that edit is lost when the function returns.
  3. Change the return type to Item and return item after editing. The function declaration is Item restock(Item item,int amount), with static permitted for file-local use.
  4. Assign the result using shelf=restock(shelf,amount). The caller then contains {8,7}. The bounds ensure stock+amount is at most 200.
Model C answer
#include <stdio.h>
typedef struct { int id; int stock; } Item;
static Item restock(Item item, int amount) {
    item.stock += amount;
    return item;
}
int main(void) {
    Item shelf;
    int amount;
    if (scanf("%d%d%d", &shelf.id, &shelf.stock, &amount) != 3 ||
        shelf.id < 1 || shelf.id > 999 || shelf.stock < 0 || shelf.stock > 100 ||
        amount < 0 || amount > 100) return 1;
    shelf = restock(shelf, amount);
    printf("%d %d\n", shelf.id, shelf.stock);
    return 0;
}

Common mistakes

  • Changing only the function’s return type is insufficient if the return statement or caller assignment is missing.
  • Do not claim that structs with identical values are the same object.

Before calling this one solid

  • I showed distinct caller and parameter records.
  • I supplied the return type, return statement and caller assignment.
  • My driver preserves id and handles zero restock.

Reference program checked with GCC and Clang in C17 mode.

M8-06Write CCore~19 minBuild nested records and pure quotation functionsNot attempted

Original practice scenario, not an identified course case: a parcel quote uses id, box dimensions and mass. Define Dimensions(length,width,height) nested in Parcel(id,box,grams). Each dimension is 1..20, mass is 1..5000 grams and id is 1..999. Write value-parameter functions for volume and price in cents. The price is 200 cents base plus 75 cents per started 500-gram band, plus 120 cents if volume is strictly greater than 1000. Write a full program reading id length width height grams and printing id=I volume=V price=P. Avoid floating-point rounding. Explain the band counts at 500 and 501 grams, the surcharge at volume exactly 1000, and why these bounds are safe for int.

Link to this question
Saves in this browser
Hint 1

For positive integer mass, ceiling(mass/500) can be computed as (mass+499)/500.

Hint 2

Nest a Dimensions field named box inside Parcel, then access p.box.length and the corresponding other members. Use >1000, not >=1000.

Worked solution & self-marking checklist

Use a nested dimensions record, multiply its three dimensions, and compute started weight bands with integer ceiling division.

Reason it through

  1. Dimensions groups the three related measurements; Parcel adds the identifier and mass to that nested value.
  2. volume returns length*width*height. Its maximum is 20*20*20=8000, within the minimum C int range.
  3. For positive grams, (grams+499)/500 gives one band at 500 grams and two at 501. grams+499 is at most 5499.
  4. Add the surcharge only when volume exceeds 1000. Exactly 1000 has no surcharge. At most ten weight bands are charged, so the maximum price is 200+750+120=1070 cents.
  5. The functions read copied Parcel values and return calculated integers; they do not mutate the caller’s record.
Model C answer
#include <stdio.h>
typedef struct {
    int length, width, height;
} Dimensions;
typedef struct {
    int id;
    Dimensions box;
    int grams;
} Parcel;
static int volume(Parcel p) {
    return p.box.length * p.box.width * p.box.height;
}
static int price_cents(Parcel p) {
    int bands = (p.grams + 499) / 500;
    return 200 + 75 * bands + (volume(p) > 1000 ? 120 : 0);
}
int main(void) {
    Parcel p;
    if (scanf("%d%d%d%d%d", &p.id, &p.box.length, &p.box.width, &p.box.height, &p.grams) != 5 ||
        p.id < 1 || p.id > 999 || p.box.length < 1 || p.box.length > 20 ||
        p.box.width < 1 || p.box.width > 20 || p.box.height < 1 || p.box.height > 20 ||
        p.grams < 1 || p.grams > 5000) return 1;
    printf("id=%d volume=%d price=%d\n", p.id, volume(p), price_cents(p));
    return 0;
}

Common mistakes

  • Integer grams/500 alone rounds down and undercharges masses not divisible by 500.
  • Do not turn the strictly-greater-than volume surcharge into a greater-than-or-equal test.

Before calling this one solid

  • I used typedef and a nested Dimensions member.
  • I implemented both requested functions with integer arithmetic.
  • I checked the 500/501 and 1000/over-1000 boundaries.

Reference program checked with GCC and Clang in C17 mode.

M8-07ExplainCore~13 minCompare record values without assuming their byte layoutNot attempted

For Packet, explain why neither a==b nor a guessed sizeof(Packet)==5 is a portable way to answer the programmer’s questions. Write a field-based equality function and give the exact output of the supplied correct program. Draw a possible layout symbolically using T=sizeof(char), I=sizeof(int), internal padding P and trailing padding Q; do not assert numerical P or Q. Explain why comparing all object bytes with memcmp is not a general substitute for comparing logical field values, even when both records’ fields are initialized.

C
#include <stdio.h>
typedef struct {
    char tag;
    int count;
} Packet;
static int same_packet(Packet a, Packet b) {
    return a.tag == b.tag && a.count == b.count;
}
int main(void) {
    Packet a = {'A', 2};
    Packet b = a;
    printf("equal=%d\n", same_packet(a, b));
    b.count = 3;
    printf("equal=%d\n", same_packet(a, b));
    printf("enough_storage=%d\n", sizeof(Packet) >= sizeof a.tag + sizeof a.count);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

C has no structure == operator. sizeof(char) is one C byte, but sizeof(int), alignment and padding remain implementation-dependent.

Hint 2

Two records can have equal member values while padding bytes do not provide a defined logical representation to compare as record equality.

Worked solution & self-marking checklist

Compare the actual fields. A structure may contain padding, so its size and raw-byte representation do not define logical record equality.

Reason it through

  1. The expression a==b is not defined for struct operands in C. same_packet instead compares tag and count using the supported member types.
  2. A symbolic layout is [tag:T][possible internal padding:P][count:I][possible trailing padding:Q], with total size T+P+I+Q. Here T=1 C byte; the other sizes are not fixed by the exercise.
  3. The copied record initially has equal field values, so equality prints 1. Changing only b.count to 3 makes field equality print 0.
  4. Structure size is at least the combined member sizes, so enough_storage prints 1. This does not imply padding must exist or that any particular numerical size is universal.
  5. memcmp compares object bytes, including any padding, rather than the specified logical fields. Padding values need not match simply because member values do; memberwise comparison expresses the actual equality requirement.
Model C answer
#include <stdio.h>
typedef struct {
    char tag;
    int count;
} Packet;
static int same_packet(Packet a, Packet b) {
    return a.tag == b.tag && a.count == b.count;
}
int main(void) {
    Packet a = {'A', 2};
    Packet b = a;
    printf("equal=%d\n", same_packet(a, b));
    b.count = 3;
    printf("equal=%d\n", same_packet(a, b));
    printf("enough_storage=%d\n", sizeof(Packet) >= sizeof a.tag + sizeof a.count);
    return 0;
}

Expected output

equal=1
equal=0
enough_storage=1

Common mistakes

  • Do not assume one-byte char plus four-byte int guarantees a five-byte structure.
  • Do not treat unspecified padding-byte contents as a meaningful record field.

Before calling this one solid

  • I gave valid memberwise equality and exact Boolean outputs.
  • I described possible internal and trailing padding symbolically.
  • I explained why bytewise comparison does not express general record equality.

Reference program checked with GCC and Clang in C17 mode.

M8-08Design & integrateStretch~25 minMake priority sorting stable for tied recordsNot attempted

Original practice scenario: a help desk serves higher-priority requests first; requests with equal priority must stay in input order. A Request has char id[9] and int priority. Input gives 0<=n<=6 and n unique id/priority pairs, where ids are tokens of 1..8 characters and priorities are 0..100. Write a stable descending-priority sort based on selecting the best remaining request. Select the first maximum, save that whole record, shift intervening records right by one, and insert the saved record at the current position. Print each id|priority on its own line, or EMPTY when n=0. Show every pass for A 3, B 2, C 3, D 2, E 4. Explain why choosing the first maximum but merely swapping does not guarantee stability; give a concrete counterexample.

Link to this question
Saves in this browser
Hint 1

The tied requests that are passed over must retain their relative order. Moving the winner forward by shifting preserves the intervening order.

Hint 2

For descending sorting, A:2 B:2 C:3 is a counterexample to an ordinary swap: bringing C forward sends A behind B.

Worked solution & self-marking checklist

Stable selection extracts the first maximum and inserts it by shifting, producing E,A,C,B,D for the stated sample.

Reason it through

  1. Pass 1 selects E:4 and shifts A,B,C,D right, yielding E:4,A:3,B:2,C:3,D:2.
  2. Pass 2 selects A:3 already in place, leaving that state unchanged. Pass 3 selects C:3 and shifts B right, yielding E:4,A:3,C:3,B:2,D:2.
  3. Pass 4 keeps B:2 before D:2. Strict > chooses the earliest remaining maximum, and shifting preserves the order of all records between the insertion point and the selected record.
  4. An ordinary first-maximum swap is still unstable: sorting A:2,B:2,C:3 descending first produces C:3,B:2,A:2, reversing the equal-priority A and B.
  5. Whole-struct assignments copy both the priority and embedded id array together. The shift must move from right to left so it does not overwrite a record before copying it.
Model C answer
#include <stdio.h>
typedef struct {
    char id[9];
    int priority;
} Request;
static void stable_priority_sort(Request a[], int n) {
    for (int i = 0; i + 1 < n; ++i) {
        int best = i;
        for (int j = i + 1; j < n; ++j) {
            if (a[j].priority > a[best].priority) best = j;
        }
        Request selected = a[best];
        for (int j = best; j > i; --j) a[j] = a[j - 1];
        a[i] = selected;
    }
}
int main(void) {
    Request a[6];
    int n;
    if (scanf("%d", &n) != 1 || n < 0 || n > 6) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%8s%d", a[i].id, &a[i].priority) != 2 ||
            a[i].priority < 0 || a[i].priority > 100) return 1;
    }
    stable_priority_sort(a, n);
    if (n == 0) puts("EMPTY");
    for (int i = 0; i < n; ++i) printf("%s|%d\n", a[i].id, a[i].priority);
    return 0;
}

Common mistakes

  • A strict comparison alone does not make ordinary selection-swap sorting stable.
  • Do not shift left-to-right when moving a block one position right, or fields and identities will be lost.

Before calling this one solid

  • I preserved equal-priority input order and whole-record identity.
  • I showed all four sample passes and a swap-instability counterexample.
  • I handled empty, already ordered and all-tied inputs.

Reference program checked with GCC and Clang in C17 mode.

M8-09Design & integrateStretch~25 minApplied record case: sell from a bounded inventoryNot attempted

This is an original invented practice case, not a reconstruction of either unspecified BITS case study. Model at most five inventory items using Stock(id,name,quantity,cents). Input gives n (0..5), then n rows id name quantity cents; ids are unique in 1..999, names are tokens of 1..11 characters, quantities are 0..20 and prices 0..999 cents. Next comes t (0..8), then t requests id units, with id in 1..999 and units 1..20. A sale succeeds only if the id exists and sufficient stock remains; failure changes no item. Write sell(items,n,id,units) returning a Sale record containing accepted and amount. Use linear search, preserve item order, update the actual array on success, and total revenue in long integer cents. Print OK ID AMOUNT or REJECT ID for each request, then REVENUE TOTAL, then every remaining item as id name quantity. Explain why a successful free item must be distinguished from a rejected sale.

Link to this question
Saves in this browser
Hint 1

Keep acceptance separate from amount: a zero-cent price still permits a successful stock reduction.

Hint 2

Return {0,0} for an unknown id or insufficient stock. After finding the matching unique id, either make the complete valid update or return failure without any change.

Worked solution & self-marking checklist

Search the record array, validate stock before changing it, and return a status-plus-amount record so free accepted sales remain distinguishable.

Reason it through

  1. Stock groups the identity, bounded name, quantity and price. The array parameter allows sell to update its existing elements; copying only one Stock into a local variable without writing it back would not update inventory.
  2. Find the unique id by linear scan. If absent or if quantity<units, return accepted=0,amount=0 without changing any quantity.
  3. On success subtract units, set accepted=1 and compute (long)units*cents. Casting before multiplication makes the calculation use long, including on an implementation with a small int range.
  4. A price of zero still yields accepted=1 and decrements stock; testing amount alone would incorrectly call this a failure.
  5. Only successful amounts contribute to revenue. The upper bound 8*20*999=159840 fits the minimum required range of long; remaining items print in their original array order.
Model C answer
#include <stdio.h>
typedef struct {
    int id;
    char name[12];
    int quantity;
    int cents;
} Stock;
typedef struct {
    int accepted;
    long amount;
} Sale;
static Sale sell(Stock items[], int n, int id, int units) {
    Sale result = {0, 0};
    for (int i = 0; i < n; ++i) {
        if (items[i].id == id) {
            if (items[i].quantity >= units) {
                items[i].quantity -= units;
                result.accepted = 1;
                result.amount = (long)units * items[i].cents;
            }
            return result;
        }
    }
    return result;
}
int main(void) {
    Stock items[5];
    int n, transactions;
    long revenue = 0;
    if (scanf("%d", &n) != 1 || n < 0 || n > 5) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%d%11s%d%d", &items[i].id, items[i].name,
                  &items[i].quantity, &items[i].cents) != 4 ||
            items[i].id < 1 || items[i].id > 999 || items[i].quantity < 0 ||
            items[i].quantity > 20 || items[i].cents < 0 || items[i].cents > 999) return 1;
    }
    if (scanf("%d", &transactions) != 1 || transactions < 0 || transactions > 8) return 1;
    for (int t = 0; t < transactions; ++t) {
        int id, units;
        if (scanf("%d%d", &id, &units) != 2 || id < 1 || id > 999 || units < 1 || units > 20) return 1;
        Sale result = sell(items, n, id, units);
        if (result.accepted) {
            revenue += result.amount;
            printf("OK %d %ld\n", id, result.amount);
        } else printf("REJECT %d\n", id);
    }
    printf("REVENUE %ld\n", revenue);
    for (int i = 0; i < n; ++i) printf("%d %s %d\n", items[i].id, items[i].name, items[i].quantity);
    return 0;
}

Common mistakes

  • Do not decrement stock before confirming there are enough units.
  • Do not treat zero charge as a rejection or multiply in int before converting a potentially larger result to long.

Before calling this one solid

  • I used both Stock and Sale records and the requested function.
  • Rejected requests leave inventory and revenue unchanged.
  • I handled repeated sales, unknown ids, zero prices and empty inventory.

Reference program checked with GCC and Clang in C17 mode.

M8-10Design & integrateStretch~25 minApplied record case: return a whole assessment reportNot attempted

This is a second original invented practice case; its rules are not claimed to be the BITS course’s hidden case-study rules or assessment policy. Define Marks(theory,practical), Learner(id,name,marks) and Report(passed,top_id,top_score,total_score). Input is 0<=n<=6 followed by n rows id name theory practical. Ids are unique 1..999; names are tokens of 1..11 characters; both marks are 0..100. A learner passes only if BOTH marks are at least 40. Weighted score is theory+2*practical. total_score includes every learner, but the top record is chosen only among passers, with earliest input winning ties. If no one passes, top_id and top_score are -1. Write read-only value-parameter functions for score and eligibility, plus analyze(const Learner a[],int n) returning Report. Print each learner as id name PASS-or-FAIL weighted-score, then passed=P total=T top=ID score=S. Explain why a failed learner with a high weighted score cannot become top.

Link to this question
Saves in this browser
Hint 1

Keep the aggregate total outside the pass-only branch, and the top-record update inside that branch.

Hint 2

Initialize both top fields to -1. Use strictly greater score to replace the top, so equal passing scores preserve the earliest input.

Worked solution & self-marking checklist

A returned Report combines independent totals and pass-only ranking while nested Marks keeps the two component marks attached to each learner.

Reason it through

  1. weighted computes theory+2*practical, while passes checks theory>=40 && practical>=40. These functions express different rules: a large weighted score does not substitute for both pass thresholds.
  2. Initialize passed=0,total_score=0,top_id=-1,top_score=-1. For every learner, add the weighted score to total_score regardless of eligibility.
  3. Only after passes succeeds, increment passed and consider updating top. A failed record is excluded even if its weighted score exceeds every passing score.
  4. Replace the top only for a strictly larger score. Any first passing score is nonnegative and exceeds -1; later ties leave the earliest input selected.
  5. With n=0 or with all learners failing, no top update occurs, so both sentinel fields remain -1. At most six scores of 300 are summed, so total_score<=1800 fits int.
Model C answer
#include <stdio.h>
typedef struct {
    int theory, practical;
} Marks;
typedef struct {
    int id;
    char name[12];
    Marks marks;
} Learner;
typedef struct {
    int passed;
    int top_id;
    int top_score;
    int total_score;
} Report;
static int weighted(Learner a) {
    return a.marks.theory + 2 * a.marks.practical;
}
static int passes(Learner a) {
    return a.marks.theory >= 40 && a.marks.practical >= 40;
}
static Report analyze(const Learner a[], int n) {
    Report report = {0, -1, -1, 0};
    for (int i = 0; i < n; ++i) {
        int score = weighted(a[i]);
        report.total_score += score;
        if (passes(a[i])) {
            ++report.passed;
            if (score > report.top_score) {
                report.top_score = score;
                report.top_id = a[i].id;
            }
        }
    }
    return report;
}
int main(void) {
    Learner a[6];
    int n;
    if (scanf("%d", &n) != 1 || n < 0 || n > 6) return 1;
    for (int i = 0; i < n; ++i) {
        if (scanf("%d%11s%d%d", &a[i].id, a[i].name, &a[i].marks.theory, &a[i].marks.practical) != 4 ||
            a[i].id < 1 || a[i].id > 999 || a[i].marks.theory < 0 || a[i].marks.theory > 100 ||
            a[i].marks.practical < 0 || a[i].marks.practical > 100) return 1;
    }
    Report report = analyze(a, n);
    for (int i = 0; i < n; ++i) {
        printf("%d %s %s %d\n", a[i].id, a[i].name, passes(a[i]) ? "PASS" : "FAIL", weighted(a[i]));
    }
    printf("passed=%d total=%d top=%d score=%d\n", report.passed,
           report.total_score, report.top_id, report.top_score);
    return 0;
}

Common mistakes

  • Do not use || between component pass conditions or rank failed learners as top.
  • Do not exclude failed learners from the total or update equal-score ties with >=.

Before calling this one solid

  • I used nested Marks and returned a complete Report.
  • I separated all-learner totals from pass-only ranking.
  • I handled threshold marks, tied passers, high-scoring failures and no-pass input.

Reference program checked with GCC and Clang in C17 mode.

09

Pointers

Addresses, arithmetic, array relationships, mutation · 10 questions

M9-01TraceFoundation~7 minTrace two aliases and a rebindingNot attempted

Trace the program one statement at a time without using invented machine addresses. Draw a diagram after q = p and another after p = &b. Give a, b, the target of p and the target of q after each mutation, then write the exact output. Explain why rebinding p does not rebind q.

C
#include <stdio.h>
int main(void) {
    int a = 4, b = 9;
    int *p = &a;
    int *q = p;
    *p += 3;
    p = &b;
    *q = *p - 2;
    *p += *q;
    printf("%d %d %d %d\n", a, b, *p, *q);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

A pointer variable holds an address value. Copying it makes two independent pointer variables with the same target.

Hint 2

After p = &b, q still targets a. The final addition reads the updated a through q.

Worked solution & self-marking checklist

The final objects are a = 7 and b = 16; p points to b and q points to a.

Reason it through

  1. Initially p -> a(4) and q -> a(4); *p += 3 changes a to 7.
  2. Rebinding gives p -> b(9), q -> a(7). No int object changes at that statement.
  3. *q = *p - 2 stores 9 - 2 = 7 into a. Then *p += *q changes b to 9 + 7 = 16.
  4. The printed dereferences read b through p and a through q, respectively.
Model C answer
#include <stdio.h>
int main(void) {
    int a = 4, b = 9;
    int *p = &a;
    int *q = p;
    *p += 3;
    p = &b;
    *q = *p - 2;
    *p += *q;
    printf("%d %d %d %d\n", a, b, *p, *q);
    return 0;
}

Expected output

7 16 16 7

Common mistakes

  • Confusing a pointer variable with its target.
  • Assuming that changing p also changes the address stored in q.

Before calling this one solid

  • Both diagrams distinguish pointer variables from int objects.
  • Every mutation is attributed to the correct target.
  • Exact output and the reason q remains unchanged are both supplied.

Reference program checked with GCC and Clang in C17 mode.

M9-02TraceCore~9 minExplain C value passing with a caller snapshotNot attempted

Draw caller and callee objects during edit(x, &y). Trace all four body statements, give the final output and explain both why x does not change and why y does change. Is the pointer parameter itself passed by reference? Would returning target at the end create a usable pointer?

C
#include <stdio.h>
static void edit(int value, int *target) {
    value += 10;
    *target += value;
    target = &value;
    *target = 0;
}
int main(void) {
    int x = 3, y = 5;
    edit(x, &y);
    printf("%d %d\n", x, y);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

Create separate boxes for caller x, caller y, callee value and callee target.

Hint 2

The address of y is copied into target. Later &value refers to a callee object whose lifetime ends on return.

Worked solution & self-marking checklist

C passes every argument by value. Copying an address permits mutation of the pointed-to caller object.

Reason it through

  1. The call creates value(3) and target -> caller y(5), while caller x remains a separate object.
  2. value becomes 13; *target += value changes caller y to 18.
  3. target = &value rebinds only the local pointer. *target = 0 now changes local value, not y.
  4. On return x = 3 and y = 18. Returning the final target would return a pointer to an expired automatic object; it must not be dereferenced.
Model C answer
#include <stdio.h>
static void edit(int value, int *target) {
    value += 10;
    *target += value;
    target = &value;
    *target = 0;
}
int main(void) {
    int x = 3, y = 5;
    edit(x, &y);
    printf("%d %d\n", x, y);
    return 0;
}

Expected output

3 18

Common mistakes

  • Calling C pointer arguments actual pass-by-reference.
  • Treating &value as lasting after the function returns.

Before calling this one solid

  • Four separate objects appear in the snapshot.
  • Explains both caller-visible and local-only effects.
  • Rejects use of a pointer to the expired parameter.

Reference program checked with GCC and Clang in C17 mode.

M9-03ExplainFoundation~8 minArray objects, adjusted parameters and portable sizeofNot attempted

Give the output and explain the types of a in main, p in main and a in inspect. Explain why sizeof a / sizeof a[0] counts elements in main but would not count elements inside inspect. Is an array assignable with a = p? State the relationship between a + 1 and &a[1] without assuming any pointer or int size.

C
#include <stdio.h>
static void inspect(int a[], size_t n) {
    a[1] = a[0] + (int)n;
}
int main(void) {
    int a[4] = {2, 4, 6, 8};
    int *p = a;
    size_t n = sizeof a / sizeof a[0];
    inspect(a, n);
    printf("%zu %d %d\n", n, *(p + 1), a[3]);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

An array expression often converts to a pointer, but the array object has not become a pointer variable.

Hint 2

The parameter spelling int a[] is adjusted to int *a; sizeof does not recover the caller length.

Worked solution & self-marking checklist

The array has four elements; the callee receives a copied pointer and a separately supplied length.

Reason it through

  1. In main, a has type int[4], while p has type int *. sizeof a measures all four ints.
  2. inspect receives an adjusted int * parameter. Mutating its valid target a[1] changes the caller array.
  3. n = 4 and the new a[1] is 2 + 4 = 6, so the output is 4 6 8.
  4. Array objects cannot be assigned a new pointer value. a + 1 and &a[1] point to the same second element; no byte-size assumption is needed.
Model C answer
#include <stdio.h>
static void inspect(int a[], size_t n) {
    a[1] = a[0] + (int)n;
}
int main(void) {
    int a[4] = {2, 4, 6, 8};
    int *p = a;
    size_t n = sizeof a / sizeof a[0];
    inspect(a, n);
    printf("%zu %d %d\n", n, *(p + 1), a[3]);
    return 0;
}

Expected output

4 6 8

Common mistakes

  • Writing a fixed pointer-size answer such as sizeof(p) = 8.
  • Using sizeof a inside the function to infer the caller array length.

Before calling this one solid

  • Distinguishes all three declarations accurately.
  • Explains the parameter adjustment and need for n.
  • Provides portable reasoning and exact output.

Reference program checked with GCC and Clang in C17 mode.

M9-04Judge every claimCore~10 minJudge every pointer-arithmetic claim independentlyNot attempted

Given int a[4] = {10,20,30,40}; int *p = a + 1; int *end = a + 4;, judge EVERY claim true or false and justify it independently. A: *(p + 2) is 40. B: end may be formed and compared with pointers into a. C: *end is a legal way to discover that traversal has finished. D: end - p is 3. E: a - 1 is legal to form provided it is never dereferenced. F: subtracting pointers to two unrelated arrays gives a portable element distance. G: incrementing p moves by one int element rather than necessarily one byte. H: an out-of-bounds dereference has a predictable garbage value. For every false claim, give a corrected rule. Do not run invalid expressions.

Link to this question
Saves in this browser
Hint 1

The allowed arithmetic range is from the first element through one past the same array. Formation and dereference have different limits.

Hint 2

Pointer subtraction is specified for positions within the same array, including its one-past position; the result is an element count.

Worked solution & self-marking checklist

A true; B true; C false; D true; E false; F false; G true; H false.

Reason it through

  1. A: p + 2 is a + 3, whose element is 40. B: end is the legal one-past pointer; comparison with positions in the same array is permitted.
  2. C: false. One-past is a traversal sentinel, never an element to read. Compare p != end before dereferencing. D: (a + 4) - (a + 1) = 3, of type ptrdiff_t.
  3. E: false. Forming a - 1 already exceeds the permitted arithmetic range, even without dereferencing it. F: false. Unrelated-array subtraction is not defined as a portable distance.
  4. G: true. Element type determines the stride. H: false. Undefined behavior supplies no reliable value or output; reject the operation rather than predicting a crash or garbage.

Common mistakes

  • Treating a legal sentinel as a readable element.
  • Thinking that avoiding dereference makes every pointer arithmetic expression valid.

Before calling this one solid

  • All eight claims have separate verdicts.
  • Each false claim has a corrected rule.
  • No observed output is assigned to undefined behavior.
M9-05Write CCore~12 minWrite a bounded in-place reversal using pointersNot attempted

Write void reverse(int *a, size_t n) using pointer traversal and a temporary int. It must reverse exactly n elements in place and do nothing for n = 0 or n = 1; for n = 0 allow a = NULL. For n > 0 the caller provides n live ints. Explain why your code never forms a pointer before the first element. Supply a driver reading n in 0..8 and then n representable ints, printing one space-separated line, including a blank line for zero elements.

Link to this question
Saves in this browser
Hint 1

Return before computing a + n - 1 when n < 2.

Hint 2

Swap the outer pair while left < right; move both pointers only after that successful comparison.

Worked solution & self-marking checklist

Guard short arrays, then exchange matching outer elements until the pointers meet or cross.

Reason it through

  1. The n < 2 guard avoids null-pointer arithmetic and unsigned n - 1 underflow in the empty case.
  2. For n >= 2 initialize left = a and right = a + n - 1, both within the same array.
  3. After swapping a pair, advance left and retreat right. The loop stops before another swap when they meet or cross.
  4. Each pair is visited once, requiring O(n) time and O(1) extra storage. No ownership is transferred.
Model C answer
#include <stdio.h>
static void reverse(int *a, size_t n) {
    if (n < 2) return;
    int *left = a;
    int *right = a + n - 1;
    while (left < right) {
        int t = *left;
        *left = *right;
        *right = t;
        ++left;
        --right;
    }
}
int main(void) {
    size_t n;
    int a[8];
    if (scanf("%zu", &n) != 1 || n > 8) return 1;
    for (size_t i = 0; i < n; ++i)
        if (scanf("%d", &a[i]) != 1) return 1;
    reverse(a, n);
    for (size_t i = 0; i < n; ++i)
        printf("%s%d", i ? " " : "", a[i]);
    putchar('\n');
    return 0;
}

Common mistakes

  • Computing a + n - 1 before checking n = 0.
  • Using while (left <= right) and decrementing right past the beginning for a one-element array.

Before calling this one solid

  • Empty and singleton arrays are valid.
  • All arithmetic and comparisons stay within one array.
  • Reverses even and odd lengths with the required formatting.

Reference program checked with GCC and Clang in C17 mode.

M9-06TraceCore~9 minTrace record copies and structure pointersNot attempted

Trace the two Record objects, the copy parameter and p. Write the exact output, rewrite target->score as an expression using * and ., and explain why ++p selects the second whole Record without assuming struct padding or field sizes. Which changes would disappear if award received both records by value?

C
#include <stdio.h>
typedef struct { int id; int score; } Record;
static void award(Record copy, Record *target) {
    copy.score += 20;
    target->score += copy.score / 10;
}
int main(void) {
    Record r[2] = {{11, 30}, {12, 50}};
    Record *p = r;
    award(r[0], &r[1]);
    ++p;
    p->score += r[0].score;
    printf("%d:%d %d:%d\n", r[0].id, r[0].score, p->id, p->score);
    return 0;
}
Link to this question
Saves in this browser
Hint 1

A struct argument passed by value creates a separate struct object, including its score field.

Hint 2

copy.score becomes 50; only target points at a caller record.

Worked solution & self-marking checklist

The first record remains at score 30, while the second reaches 85.

Reason it through

  1. award initializes a separate copy with {11,30}, then changes its score to 50. Caller r[0] remains unchanged.
  2. target -> r[1], so target->score += 50 / 10 changes r[1].score from 50 to 55. The equivalent member expression is (*target).score.
  3. ++p advances by one Record element, independently of its byte size. Adding r[0].score makes the second score 85.
  4. If the second record were also passed only by value, award would not change either caller record; the later addition would produce 80 instead.
Model C answer
#include <stdio.h>
typedef struct { int id; int score; } Record;
static void award(Record copy, Record *target) {
    copy.score += 20;
    target->score += copy.score / 10;
}
int main(void) {
    Record r[2] = {{11, 30}, {12, 50}};
    Record *p = r;
    award(r[0], &r[1]);
    ++p;
    p->score += r[0].score;
    printf("%d:%d %d:%d\n", r[0].id, r[0].score, p->id, p->score);
    return 0;
}

Expected output

11:30 12:85

Common mistakes

  • Writing *target.score, which has the wrong grouping.
  • Assuming ++p advances just one field or using an invented struct size.

Before calling this one solid

  • Tracks the local copy separately.
  • Uses correct -> and (*p).field equivalence.
  • Explains pointer stride and exact output.

Reference program checked with GCC and Clang in C17 mode.

M9-07Write CCore~12 minDesign a nullable result-parameter contractNot attempted

Write int minimum(const int *a, size_t n, int *out). Return 1 and store the minimum for a valid nonempty array and nonnull out. Return 0 for n = 0, a = NULL or out = NULL, without modifying *out when it exists. Other nonnull pointers must designate valid objects; NULL checks cannot prove that arbitrary addresses are valid. Explain why returning the minimum directly is insufficient if every int can be an element. Demonstrate empty, duplicate-minimum and singleton cases.

Link to this question
Saves in this browser
Hint 1

Keep success/failure separate from the value by using the return status plus an output parameter.

Hint 2

Check the empty/null cases before a[0], and store the answer only after computing it.

Worked solution & self-marking checklist

A status return distinguishes failure from every possible minimum value, with no sentinel collision.

Reason it through

  1. Reject empty or null cases before dereferencing anything. Short-circuit || makes that guard safe.
  2. Seed best with a[0], so the algorithm works for arrays whose elements are all positive or all negative.
  3. Examine indices 1 through n - 1 and write *out once, after success is known.
  4. const int * prevents modification through a; it does not make the caller array intrinsically immutable or validate its lifetime.
Model C answer
#include <stdio.h>
static int minimum(const int *a, size_t n, int *out) {
    if (n == 0 || a == NULL || out == NULL) return 0;
    int best = a[0];
    for (size_t i = 1; i < n; ++i)
        if (a[i] < best) best = a[i];
    *out = best;
    return 1;
}
int main(void) {
    size_t n;
    int a[8], answer = 123;
    if (scanf("%zu", &n) != 1 || n > 8) return 1;
    for (size_t i = 0; i < n; ++i)
        if (scanf("%d", &a[i]) != 1) return 1;
    if (minimum(n ? a : NULL, n, &answer)) printf("min=%d\n", answer);
    else printf("empty unchanged=%d\n", answer);
    printf("null-output=%d\n", minimum(n ? a : NULL, n, NULL));
    return 0;
}

Common mistakes

  • Using 0 or -1 as a universal failure sentinel for the minimum.
  • Assuming a nonnull dangling pointer becomes safe merely because the null check passes.

Before calling this one solid

  • All rejected calls preserve any valid output object.
  • All elements, including index 0, participate.
  • Status, const and pointer-validity contracts are explained.

Reference program checked with GCC and Clang in C17 mode.

M9-08Debug & repairFoundation~8 minRepair a swap that exchanges only local pointer copiesNot attempted

The function below is intended to exchange caller ints but fails. Explain its actual effect using a caller/callee diagram. Repair it so valid pointed-to ints are swapped; define null arguments to cause a no-op. Ensure swap(&x, &x) is safe. Explain why the temporary should be an int rather than a pointer.

C
void swap(int *a, int *b) {
    int *temp = a;
    a = b;
    b = temp;
}
/* Caller: int x = 2, y = 7; swap(&x, &y); */
Link to this question
Saves in this browser
Hint 1

The broken code only changes the address values in the two local parameters.

Hint 2

Save *a, then assign *a = *b and *b = the saved int.

Worked solution & self-marking checklist

The repair exchanges object values through valid pointers and treats null arguments as no-ops.

Reason it through

  1. Initially a -> caller x and b -> caller y. Exchanging a and b changes only local boxes; x and y stay 2 and 7.
  2. Guard null pointers before reading either target. The nonnull contract still requires live writable ints.
  3. An int temporary preserves the old *a while *a is overwritten.
  4. If a == b, all reads and writes refer to the same int, and the sequence preserves its value.
Model C answer
#include <stdio.h>
static void swap(int *a, int *b) {
    if (a == NULL || b == NULL) return;
    int temp = *a;
    *a = *b;
    *b = temp;
}
int main(void) {
    int x = 2, y = 7;
    swap(&x, &y);
    printf("%d %d\n", x, y);
    swap(&x, &x);
    swap(NULL, &y);
    printf("%d %d\n", x, y);
    return 0;
}

Expected output

7 2
7 2

Common mistakes

  • Saving a rather than *a.
  • Overwriting *a before preserving its old value.

Before calling this one solid

  • Explains the original behavior without calling it pass-by-reference.
  • Handles null and same-target calls as specified.
  • Uses a value temporary and produces both exact output lines.

Reference program checked with GCC and Clang in C17 mode.

M9-09ExplainCore~10 minDraw lifetimes and reject dangling return valuesNot attempted

For each function independently, say whether the returned pointer designates a live object after return, who owns that object and what conditions permit access: A: int *bad(void) { int x = 7; return &x; } B: int *middle(int *a, size_t n) { return n >= 2 ? &a[1] : NULL; } with a caller-provided live array for n > 0. C: const int *fixed(void) { static int x = 7; return &x; }. Draw a before/after-return diagram for each. Repair A in two ways within this module: return the int by value, and use a caller-owned output parameter. Do not predict a value from dereferencing A’s result.

Link to this question
Saves in this browser
Hint 1

A pointer can outlive its pointer variable or its target; those are separate lifetime questions.

Hint 2

B borrows a caller object. C uses static storage duration. A points to an object whose lifetime ends.

Worked solution & self-marking checklist

A yields a dangling pointer; B may yield a borrowed array-element pointer; C yields a pointer to a live static object.

Reason it through

  1. A before return: local x(7) with result -> x. After return: x no longer exists, so the pointer does not permit access; returning an address does not extend lifetime.
  2. B: caller array [a0,a1,...] survives the call. For n >= 2 the result -> caller a[1]; it stays usable only while the original array and element remain live. For smaller n the result is NULL.
  3. C: static x exists for the program lifetime; the function gives a borrowed const-qualified access path. The caller must not free it.
  4. Repairs for A: int good(void) { return 7; } or int good_out(int *out) { if (!out) return 0; *out = 7; return 1; }. The output variant requires a live writable caller int.

Common mistakes

  • Equating a nonnull address with a live object.
  • Freeing borrowed array or static storage.

Before calling this one solid

  • All three cases include lifetime and ownership.
  • No output is invented for a dangling access.
  • Both requested repairs have complete, usable contracts.
M9-10Write CCore~12 minReturn a borrowed pointer to the first matchNot attempted

Write const int *find_first(const int *a, size_t n, int key), returning a pointer to the first matching element or NULL. Empty input may use a = NULL; nonempty input provides n live ints. Write a driver reading n in 0..8, key and n representable ints. Print not found or index=<zero-based index> value=<value>. Explain why subtraction is legal only on the success branch, and why the caller must not free this returned pointer.

Link to this question
Saves in this browser
Hint 1

Return &a[i] as soon as the first equality succeeds.

Hint 2

The returned pointer borrows the caller array; found - a is an element offset only when found points into that same array.

Worked solution & self-marking checklist

Linear search returns a borrowed const pointer, with NULL as an unambiguous absent result.

Reason it through

  1. The loop condition i < n prevents any array access for n = 0, including when a is NULL.
  2. Forward iteration and immediate return ensure the first duplicate is selected.
  3. On success found and a designate positions in the same array, so subtracting yields a ptrdiff_t printed with %td.
  4. On failure no dereference or subtraction occurs. The array owner retains responsibility for its lifetime; an interior borrowed pointer is not a malloc result to free.
Model C answer
#include <stdio.h>
#include <stddef.h>
static const int *find_first(const int *a, size_t n, int key) {
    for (size_t i = 0; i < n; ++i)
        if (a[i] == key) return &a[i];
    return NULL;
}
int main(void) {
    size_t n;
    int a[8], key;
    if (scanf("%zu%d", &n, &key) != 2 || n > 8) return 1;
    for (size_t i = 0; i < n; ++i)
        if (scanf("%d", &a[i]) != 1) return 1;
    const int *found = find_first(n ? a : NULL, n, key);
    if (found == NULL) puts("not found");
    else printf("index=%td value=%d\n", found - a, *found);
    return 0;
}

Common mistakes

  • Subtracting NULL from the array base in the failure case.
  • Returning the address of a local copy of the matching value.

Before calling this one solid

  • Returns first match, including index zero.
  • Handles empty and not-found cases safely.
  • Explains borrowed ownership and uses the correct difference format.

Reference program checked with GCC and Clang in C17 mode.

10

Dynamic memory

Allocation, ownership, cleanup, dynamic 2-D storage · 10 questions

M10-01ExplainFoundation~10 minSeparate pointer storage from allocated-object lifetimeNot attempted

Explain the storage and lifetime of each object in void f(void) { int local = 4; int *p = malloc(3 * sizeof *p); /* assume success */ p[0] = local; }. Draw an ownership diagram during f and after it returns without free. Does the automatic pointer p imply that its allocation is automatic? Does returning p fix the leak by itself? Give a corrected contract and cleanup sequence. Use “automatic storage, conventionally the stack” and “allocated storage, conventionally the heap” rather than claiming the C standard mandates physical regions.

Link to this question
Saves in this browser
Hint 1

The pointer variable and the block it points to are distinct objects with distinct lifetimes.

Hint 2

Returning a pointer can transfer the ability to free the allocation, but an explicit ownership contract and eventual free are still necessary.

Worked solution & self-marking checklist

The automatic pointer dies at return; its allocation remains allocated until free and becomes leaked if no usable owner survives.

Reason it through

  1. During f: automatic local(4), automatic p -> allocated block of three ints; only p[0] has been initialized by the shown code.
  2. The allocated block does not become automatic because p is automatic. At return local and p end their lifetimes; the block remains allocated.
  3. Without another owner, the address is lost and the block leaks. A returned pointer can transfer ownership, but the caller must eventually free it exactly once.
  4. One repair keeps ownership local: check p after malloc, use only initialized elements, free(p), then return. Another returns p under a caller-owns-result contract; the caller checks NULL and frees it.

Common mistakes

  • Saying free(p) frees the pointer variable itself.
  • Reading the uninitialized second or third int because malloc was successful.

Before calling this one solid

  • The diagram separates two storage durations.
  • Correctly identifies the leak and uninitialized elements.
  • States ownership, failure handling and exactly-once cleanup.
M10-02Write CFoundation~15 minAllocate and summarize a runtime-sized arrayNot attempted

Read n in 0..100 followed by n integer tokens, all representable as int and required to be in -1000..1000. Allocate exactly n ints when n > 0, then report n, sum, minimum and maximum; print empty for n = 0. Check the multiplication size, allocation and each conversion. On bad element input print input error, release memory and fail. Explain why long can hold this sum even on a conforming implementation with a 16-bit int, and why no minimum exists for empty input.

Link to this question
Saves in this browser
Hint 1

Use sizeof *a for element storage and avoid depending on the result of malloc(0).

Hint 2

The largest absolute sum is 100000; long is required to support at least -2147483647..2147483647.

Worked solution & self-marking checklist

The program maintains one owning pointer and releases it on both success and failed element input.

Reason it through

  1. Validate n before allocation; n > SIZE_MAX / sizeof *a would make the byte multiplication unsafe.
  2. Represent the empty array by NULL without calling malloc(0). For n > 0, check allocation before any write.
  3. Read each element with a conversion check and the stated range check. The sum bound is 100 * 1000 = 100000, safe for long.
  4. Seed min and max from a[0] only for n > 0, print the result and free the single owned block.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
    size_t n;
    int *a = NULL;
    if (scanf("%zu", &n) != 1 || n > 100 || n > SIZE_MAX / sizeof *a) return 1;
    if (n) a = malloc(n * sizeof *a);
    if (n && a == NULL) { puts("memory error"); return 1; }
    long sum = 0;
    for (size_t i = 0; i < n; ++i) {
        if (scanf("%d", &a[i]) != 1 || a[i] < -1000 || a[i] > 1000) {
            free(a); puts("input error"); return 1;
        }
        sum += a[i];
    }
    if (!n) puts("empty");
    else {
        int min = a[0], max = a[0];
        for (size_t i = 1; i < n; ++i) {
            if (a[i] < min) min = a[i];
            if (a[i] > max) max = a[i];
        }
        printf("n=%zu sum=%ld min=%d max=%d\n", n, sum, min, max);
    }
    free(a);
    return 0;
}

Common mistakes

  • Initializing the minimum to zero.
  • Returning from a failed read after allocation without freeing.

Before calling this one solid

  • Handles empty, negative-only and mixed arrays.
  • Checks conversions and allocation before access.
  • Justifies arithmetic bounds and frees on every post-allocation exit.

Reference program checked with GCC and Clang in C17 mode.

M10-03Debug & repairCore~12 minRepair allocation size, bounds and deallocation baseNot attempted

The fragment below follows a valid size_t n read. Identify EVERY independent defect or portability assumption. Repair it as a full program that reads n in 0..20 and n representable ints, prints them in reverse order on one line, and frees correctly. Handle empty input, conversion failure, allocation failure and size multiplication overflow. Do not claim that sizeof a is always too small or that any invalid original run has a specified output.

C
int *a = malloc(n * sizeof a);
for (size_t i = 0; i <= n; ++i) scanf("%d", &a[i]);
free(a + 1);
Link to this question
Saves in this browser
Hint 1

sizeof a measures the pointer variable; sizeof *a measures one allocated element. Their relative sizes are implementation-dependent.

Hint 2

An n-element block has indices 0..n-1; free must receive NULL or the exact live allocation base.

Worked solution & self-marking checklist

The correct program allocates n element sizes, uses strict bounds and frees only the base pointer.

Reason it through

  1. n * sizeof a uses the pointer size rather than element size; it might allocate more or fewer bytes and is not a portable element-size expression.
  2. The inclusive loop processes n + 1 elements rather than n. It is out of bounds for an allocation correctly sized for n ints; whether the original mistaken byte count accidentally provides enough bytes is implementation-dependent and does not repair the intended bounds.
  3. Allocation success and each input conversion must be checked; n * sizeof *a must be representable as size_t.
  4. free(a + 1) is not the returned allocation base and is invalid. Preserve a, print from valid indices and free(a) once.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
    size_t n;
    if (scanf("%zu", &n) != 1 || n > 20) return 1;
    int *a = NULL;
    if (n > SIZE_MAX / sizeof *a) return 1;
    if (n) {
        a = malloc(n * sizeof *a);
        if (a == NULL) return 1;
    }
    for (size_t i = 0; i < n; ++i) {
        if (scanf("%d", &a[i]) != 1) { free(a); return 1; }
    }
    for (size_t i = n; i > 0; --i)
        printf("%s%d", i == n ? "" : " ", a[i - 1]);
    putchar('\n');
    free(a);
    return 0;
}

Common mistakes

  • “Fixing” the code with a fixed 4-byte or 8-byte multiplier.
  • Using an unsigned reverse loop i >= 0 that never terminates normally.

Before calling this one solid

  • Finds size, bounds, base-pointer and error-handling defects.
  • Explains pointer-size portability without a fixed assumption.
  • Corrected code covers zero and failed reads with no leak.

Reference program checked with GCC and Clang in C17 mode.

M10-04Write CCore~15 minCreate a heap-owned record with embedded textNot attempted

Define Account with id, a 16-character name array and a nonnegative int balance. Write make_account(id,name,balance) returning an owning pointer or NULL on invalid fields/allocation failure; name is a valid null-terminated caller string and must fit including its terminator. Copy the text into the embedded array. Write withdraw(Account *,int) returning 1 on success and 0 without mutation for null/negative/excess withdrawals. Demonstrate Mira’s account: id 17, opening 90, withdraw 35 then 70. Explain how many frees are required and whether the caller string must remain alive.

Link to this question
Saves in this browser
Hint 1

Allocate one whole Account using sizeof *a. Its embedded name bytes are part of that same allocation.

Hint 2

Reject amount > balance before subtraction, and reject names whose strlen is at least the array capacity.

Worked solution & self-marking checklist

One allocation owns the complete record and embedded string; one free releases it.

Reason it through

  1. Validate id, balance and name length before allocating. The name contract already guarantees a readable terminated string.
  2. Use one named capacity, NAME_CAPACITY = 16, for the embedded array and its length check. A maximum 15-character name leaves one byte for its null terminator.
  3. Allocate sizeof *a, check NULL, then initialize every field and copy the bounded text including its terminator.
  4. Withdraw 35 succeeds, leaving 55; withdraw 70 fails and preserves 55. The text is an independent copy, so the original string need not remain alive after construction.
  5. The caller owns the returned block and calls free(a) once; free(a->name) would be invalid because name is embedded storage.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { NAME_CAPACITY = 16 };
typedef struct { int id; char name[NAME_CAPACITY]; int balance; } Account;
static Account *make_account(int id, const char *name, int balance) {
    if (id <= 0 || balance < 0 || strlen(name) >= NAME_CAPACITY) return NULL;
    Account *a = malloc(sizeof *a);
    if (a == NULL) return NULL;
    a->id = id;
    strcpy(a->name, name);
    a->balance = balance;
    return a;
}
static int withdraw(Account *a, int amount) {
    if (a == NULL || amount < 0 || amount > a->balance) return 0;
    a->balance -= amount;
    return 1;
}
int main(void) {
    Account *a = make_account(17, "Mira", 90);
    if (a == NULL) { puts("create failed"); return 1; }
    int first = withdraw(a, 35);
    int second = withdraw(a, 70);
    printf("%d %s balance=%d results=%d,%d\n", a->id, a->name, a->balance, first, second);
    free(a);
    return 0;
}

Expected output

17 Mira balance=55 results=1,0

Common mistakes

  • Storing the address of a temporary caller name rather than copying the text.
  • Freeing the embedded array separately from the record.

Before calling this one solid

  • Initialization occurs only after successful allocation.
  • All invalid withdrawals preserve balance.
  • Explains the independent string copy and single ownership.

Reference program checked with GCC and Clang in C17 mode.

M10-05Debug & repairCore~10 minDiagnose dangling aliases and double freeNot attempted

Assuming allocation success only for the diagnosis, draw the objects after each line of the broken fragment. Explain the use-after-free and double-free separately. Does owner = NULL change alias or restore the released block? Rewrite as a complete program that prints 5 exactly once and releases storage exactly once. Include allocation-failure handling. Do not run the invalid original or predict its output.

C
int *owner = malloc(2 * sizeof *owner);
int *alias = owner;
owner[0] = 5;
free(owner);
owner = NULL;
printf("%d\n", alias[0]);
free(alias);
Link to this question
Saves in this browser
Hint 1

Both pointer variables copy the same allocation address; there is still only one allocation.

Hint 2

Move the last borrowed use before the owner’s free, and never free the borrowing alias.

Worked solution & self-marking checklist

Nulling one pointer does not update aliases. All borrows must end before the single owning free.

Reason it through

  1. After allocation: owner -> block[?,?]; alias -> same block. After the assignment the first int is 5.
  2. free(owner) ends the allocation lifetime. Both saved address values cease to permit access; owner = NULL changes only owner.
  3. alias[0] then accesses released storage. free(alias) attempts to release the same allocation again. Both operations are invalid, regardless of whether a particular run appears to work.
  4. The corrected program reads while the block is live, ends the alias borrow, frees via the owner once and nulls the owner if retained.
Model C answer
#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *owner = malloc(2 * sizeof *owner);
    if (owner == NULL) return 1;
    int *alias = owner;
    owner[0] = 5;
    printf("%d\n", alias[0]);
    alias = NULL;
    free(owner);
    owner = NULL;
    return 0;
}

Expected output

5

Common mistakes

  • Thinking NULL assignment propagates to other pointer variables.
  • Believing two pointers imply two allocations needing two frees.

Before calling this one solid

  • Identifies both invalid operations and their order.
  • Provides live/freed ownership diagrams.
  • Corrected program has exactly one successful-allocation free.

Reference program checked with GCC and Clang in C17 mode.

M10-06Write CCore~15 minRepresent a dynamic matrix in one contiguous blockNot attempted

Read rows and cols in 1..20, allocate one contiguous block of ints and read values in -1000..1000. Print each zero-based row sum as row r: sum. Derive the index formula rather than memorizing it. Guard both rows * cols and the multiplication by element size before allocation. Check conversion/allocation failures and free on every post-allocation exit. Draw the flat indices for a 2 by 3 matrix. Explain why this int * is not an int **.

Link to this question
Saves in this browser
Hint 1

Each complete preceding row contributes cols elements, so (r,c) maps to r * cols + c.

Hint 2

Check rows <= SIZE_MAX / cols before computing their product, then compare the product with SIZE_MAX / sizeof *a.

Worked solution & self-marking checklist

A flat block gives row-major indexing with a single owner and a single free.

Reason it through

  1. For 2 by 3, row 0 uses flat indices 0,1,2 and row 1 uses 3,4,5; each row contributes exactly cols positions.
  2. Check nonzero dimensions before dividing and check each size multiplication before evaluating an unsafe product.
  3. Read only cells with r < rows and c < cols. A row sum has absolute bound 20000, safe for long.
  4. The allocation contains ints, not an array of row pointers. Treating it as int ** would interpret integer bytes as pointer objects.
  5. All paths after allocation free the same base pointer exactly once.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
    size_t rows, cols;
    if (scanf("%zu%zu", &rows, &cols) != 2 || rows == 0 || cols == 0 || rows > 20 || cols > 20) return 1;
    int *a = NULL;
    if (rows > SIZE_MAX / cols || rows * cols > SIZE_MAX / sizeof *a) return 1;
    a = malloc(rows * cols * sizeof *a);
    if (a == NULL) return 1;
    for (size_t r = 0; r < rows; ++r)
        for (size_t c = 0; c < cols; ++c)
            if (scanf("%d", &a[r * cols + c]) != 1 || a[r * cols + c] < -1000 || a[r * cols + c] > 1000) {
                free(a); return 1;
            }
    for (size_t r = 0; r < rows; ++r) {
        long sum = 0;
        for (size_t c = 0; c < cols; ++c) sum += a[r * cols + c];
        printf("row %zu: %ld\n", r, sum);
    }
    free(a);
    return 0;
}

Common mistakes

  • Using r * rows + c, which fails on nonsquare matrices.
  • Casting the flat allocation to int ** and indexing it as row pointers.

Before calling this one solid

  • Correct nonsquare memory map and offset formula.
  • Both size products and all read results are checked.
  • One allocation is released on normal and input-error paths.

Reference program checked with GCC and Clang in C17 mode.

M10-07Write CStretch~22 minBuild row-pointer matrices with partial-failure cleanupNot attempted

Allocate an int ** matrix as a pointer table plus one independent int array per row. Read rows and cols in 1..10 plus fail_on: 0 means no deliberately forced failure; 1 means fail the table allocation; k > 1 means fail allocation attempt k, counting the table first. Use a simple allocator wrapper that returns NULL on that attempt and otherwise calls malloc. Fill a[r][c] = 10*r + c and print the sum on success. On failure, print exactly how many already-allocated rows you released. Draw ownership after the second row allocation and show cleanup order. Real malloc failure must follow the same safe path.

Link to this question
Saves in this browser
Hint 1

Keep made equal to the number of fully allocated rows, never the index of a failed row.

Hint 2

When row allocation fails, free rows 0 through made-1 and only then the pointer table. Do not read uninitialized table slots.

Worked solution & self-marking checklist

The table owns made initialized row pointers; tracking that count makes every partial state safely destructible.

Reason it through

  1. The table needs rows * sizeof *a bytes; each row needs cols * sizeof **a bytes. Check both multiplications.
  2. After two rows: owner a -> table [row0*,row1*,uninitialized...]; row0* -> cols ints; row1* -> cols ints. There are three allocations, with distinct bases.
  3. Increment made only after successful row creation. Failure leaves exactly made rows to free.
  4. Release initialized rows in reverse order, then free the table. Releasing only a leaks every row.
  5. For a 2 by 3 matrix the values are 0,1,2 and 10,11,12, summing to 36. Forced failures exercise the same cleanup as real allocation failures.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
static size_t calls;
static size_t fail_on;
static void *try_allocate(size_t bytes) {
    ++calls;
    if (calls == fail_on) return NULL;
    return malloc(bytes);
}
int main(void) {
    size_t rows, cols, made = 0;
    int **a = NULL;
    if (scanf("%zu%zu%zu", &rows, &cols, &fail_on) != 3 || rows == 0 || cols == 0 || rows > 10 || cols > 10) return 1;
    if (rows > SIZE_MAX / sizeof *a || cols > SIZE_MAX / sizeof **a) return 1;
    a = try_allocate(rows * sizeof *a);
    if (a == NULL) { puts("allocation failed; rows released=0"); return 1; }
    for (; made < rows; ++made) {
        a[made] = try_allocate(cols * sizeof **a);
        if (a[made] == NULL) break;
    }
    if (made != rows) {
        size_t completed = made;
        while (made) free(a[--made]);
        free(a);
        printf("allocation failed; rows released=%zu\n", completed);
        return 1;
    }
    long sum = 0;
    for (size_t r = 0; r < rows; ++r)
        for (size_t c = 0; c < cols; ++c) {
            a[r][c] = (int)(10 * r + c);
            sum += a[r][c];
        }
    printf("sum=%ld\n", sum);
    while (made) free(a[--made]);
    free(a);
    return 0;
}

Common mistakes

  • Freeing the table before reading its row pointers for cleanup.
  • Looping over all rows when only made slots contain valid pointer values.

Before calling this one solid

  • Has a clear allocation-attempt numbering contract.
  • Table, first-row and later-row failures all clean safely.
  • Draws distinct allocations and justifies both size expressions.

Reference program checked with GCC and Clang in C17 mode.

M10-08Judge every claimCore~12 minJudge every memory-management claim independentlyNot attempted

Judge EVERY statement true or false, explain each and repair false statements. A: free(NULL) is valid and does nothing. B: malloc initializes each int to zero. C: successful malloc(n * sizeof *p) proves that the multiplication did not overflow. D: if p points to an allocation, free(p + 1) is valid whenever the allocation has at least two elements. E: setting p = NULL after free(p) clears all aliases. F: allocating a struct with an embedded char name[20] needs only one matching free, unless it also owns other separately allocated fields. G: overwriting the only pointer to a live allocation can cause a leak. H: every nonnull pointer may be passed to free. I: after free, a pointer can safely be overwritten with NULL, but its old target cannot be read. J: a successful zero-size malloc call must return a dereferenceable object. Include an ownership example for G.

Link to this question
Saves in this browser
Hint 1

A deallocation rule concerns the exact live allocation base, not merely an address somewhere inside storage.

Hint 2

A pointer table, embedded array and separately allocated child block have different ownership structures.

Worked solution & self-marking checklist

A true; B false; C false; D false; E false; F true; G true; H false; I true; J false.

Reason it through

  1. A: true, free(NULL) is specified as a no-op. B: false, malloc provides uninitialized storage; initialize elements before reading them.
  2. C: false, overflow may occur before malloc receives the byte count. Check n <= SIZE_MAX / sizeof *p first. D: false, an interior address is not the returned allocation base.
  3. E: false, only p changes; aliases are still unusable after release. F: true, embedded array bytes belong to the struct allocation; separately owned child blocks require their own frees.
  4. G: true: p -> block A; assigning p = malloc(...) can lose A’s only address, even if the new allocation fails. Preserve ownership or free A when its use ends. H: false; nonnull stack, static, interior, expired and already-freed addresses are not valid free arguments.
  5. I: true, assigning NULL need not read the old pointer value and does not access its former target. J: false, zero-size allocation has implementation-defined permitted outcomes; do not dereference its result, and use an explicit empty representation.

Common mistakes

  • Judging a bundle of claims as a single mostly-true statement.
  • Using a cast or a nonnull test as proof that free is valid.

Before calling this one solid

  • All ten claims receive separate verdicts.
  • Every false claim is repaired with a precise rule.
  • G includes an explicit lost-owner diagram.
M10-09Write CStretch~20 minReturn an owned filtered array through output parametersNot attempted

Write int positives(const int *src, size_t n, int **out, size_t *count). The caller supplies live out and count objects and n valid source ints (src may be NULL only for n = 0). Count values > 0, allocate exactly that many ints and preserve their order. Return 1 on success, including an empty result represented by *out = NULL and *count = 0. On allocation/size failure return 0 with both outputs reset to that same empty state. The output must own an independent copy; src is borrowed and unchanged. Explain why int ** is needed here. Driver: n in 0..12, then n representable ints; print count=k followed by retained values.

Link to this question
Saves in this browser
Hint 1

Count first, allocate second, copy third. Empty success needs no allocation.

Hint 2

To change the caller’s pointer variable, pass its address; the int ** argument is itself still passed by value.

Worked solution & self-marking checklist

Two passes produce an exactly sized owned result with a clear empty and failure contract.

Reason it through

  1. Initialize *out = NULL and *count = 0 before doing work, under the stated valid-output-objects contract.
  2. Count positive entries without changing src. If zero, return success without pointer arithmetic or malloc(0).
  3. Guard count * sizeof **out, allocate and check. On failure reset count to zero while out remains NULL.
  4. Copy positives in original order, then publish p through *out. The caller now owns p and must free it once.
  5. int ** points to the caller’s int * object, so writing *out changes that object; no special pass-by-reference mechanism is introduced.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
static int positives(const int *src, size_t n, int **out, size_t *count) {
    *out = NULL;
    *count = 0;
    for (size_t i = 0; i < n; ++i) if (src[i] > 0) ++*count;
    if (*count == 0) return 1;
    if (*count > SIZE_MAX / sizeof **out) { *count = 0; return 0; }
    int *p = malloc(*count * sizeof *p);
    if (p == NULL) { *count = 0; return 0; }
    size_t j = 0;
    for (size_t i = 0; i < n; ++i) if (src[i] > 0) p[j++] = src[i];
    *out = p;
    return 1;
}
int main(void) {
    size_t n, count;
    int a[12], *result;
    if (scanf("%zu", &n) != 1 || n > 12) return 1;
    for (size_t i = 0; i < n; ++i)
        if (scanf("%d", &a[i]) != 1) return 1;
    if (!positives(n ? a : NULL, n, &result, &count)) return 1;
    printf("count=%zu", count);
    for (size_t i = 0; i < count; ++i) printf(" %d", result[i]);
    putchar('\n');
    free(result);
    return 0;
}

Common mistakes

  • Returning a pointer into src while promising an independent owned array.
  • Treating an empty successful result as necessarily an allocation failure.

Before calling this one solid

  • Preserves order and leaves src unchanged.
  • Empty success and failure have the promised output state.
  • Explains ownership transfer, int ** and caller cleanup.

Reference program checked with GCC and Clang in C17 mode.

M10-10Design & integrateStretch~18 minChoose and draw a dynamic matrix ownership designNot attempted

A program needs a rectangular rows by cols matrix, indexed at runtime, and later a different program needs ragged rows of different lengths. Compare (A) one flat int block indexed by r*cols+c and (B) a separately allocated pointer table with one allocated row per table entry. For each draw a 2 by 3 ownership diagram, count allocations and frees, give size expressions, describe partial-failure cleanup and say whether it naturally represents ragged rows. Then write a cleanup fragment for B given made successfully allocated rows. Assume rows and cols are positive and checked for multiplication overflow; no VLAs, realloc or advanced data structures are required.

Link to this question
Saves in this browser
Hint 1

Count the pointer table as an allocation in design B. A table is not the same object as the row data.

Hint 2

A flat rectangular block is contiguous; independently allocated rows need not be adjacent.

Worked solution & self-marking checklist

A rectangular flat block has one owner; a row-pointer design has one table owner and made child owners.

Reason it through

  1. A diagram: base -> [a00 a01 a02 a10 a11 a12]. Allocate rows*cols*sizeof *base after overflow checks; exactly one free(base). Natural row lengths are uniform. Ragged storage would require extra offset/length bookkeeping.
  2. B diagram: table -> [row0*,row1*]; row0* -> [a00 a01 a02], row1* -> [a10 a11 a12]. For two rows there are three allocations and three matching frees.
  3. B sizes: rows*sizeof *table for pointers; cols*sizeof **table for each rectangular row. Ragged rows instead use length[r]*sizeof **table with per-row bounds and zero-length policy.
  4. On partial failure, only table[0..made-1] are known allocated. Free those rows first, then the table; never inspect uninitialized entries.
  5. Cleanup fragment: while (made > 0) { --made; free(table[made]); } free(table);. This also handles made = 0; table itself must be NULL or a live allocation base.

Common mistakes

  • Assuming independent rows are contiguous because their pointers share a table.
  • Freeing only the pointer table or freeing it before accessing its entries.

Before calling this one solid

  • Accurate diagrams, allocation counts and size expressions for both designs.
  • Explains ragged-row suitability and indexing contracts.
  • Cleanup handles every partial state without reading uninitialized slots.
11

Files & integrated cases

Modes, reads, writes, errors, comprehensive programs · 10 questions

M11-01Debug & repairFoundation~12 minReplace the feof loop with conversion-driven readingNot attempted

Repair the fragment to read numbers.txt, a text file intended to contain at most 100 integers in -1000..1000 separated by whitespace. All numeric tokens presented to %d are representable as int; nonnumeric tokens must be rejected. Print count=k sum=s on success, open error if opening fails, or invalid data or I/O error for a bad token, out-of-range value, excess count, read error or close error. Explain the stale-value bug on a normal end-of-file and why a nonnumeric token can leave the broken loop stuck. Empty files are valid. Do not execute the broken fragment.

C
FILE *in = fopen("numbers.txt", "r");
int x = 0, sum = 0;
while (!feof(in)) {
    fscanf(in, "%d", &x);
    sum += x;
}
printf("%d\n", sum);
Link to this question
Saves in this browser
Hint 1

feof becomes set only after a read attempts to pass the end; it does not predict the next conversion.

Hint 2

Use the conversion result as the loop condition and distinguish 0 (matching failure) from EOF (no conversion because input ended or failed).

Worked solution & self-marking checklist

Read only while fscanf returns one successful conversion; then check whether termination was clean EOF.

Reason it through

  1. Check fopen before using the stream. fopen can return NULL, which is not a usable FILE *.
  2. The original loop may add the previous x again after the final conversion fails. A bad token may cause repeated return 0 without consuming it, leaving feof false.
  3. The repaired loop adds only a successfully read, validated value and keeps the bounded sum in long.
  4. On termination, accept only converted == EOF with no read error. A deliberate range/count break leaves converted == 1 and is rejected.
  5. Close the stream on every path after opening and treat fclose failure as failure too.
Model C answer
#include <stdio.h>
int main(void) {
    FILE *in = fopen("numbers.txt", "r");
    if (in == NULL) { puts("open error"); return 1; }
    size_t count = 0;
    long sum = 0;
    int x, converted;
    while ((converted = fscanf(in, "%d", &x)) == 1) {
        if (count == 100 || x < -1000 || x > 1000) break;
        ++count;
        sum += x;
    }
    int ok = converted == EOF && !ferror(in);
    if (fclose(in) == EOF) ok = 0;
    if (!ok) { puts("invalid data or I/O error"); return 1; }
    printf("count=%zu sum=%ld\n", count, sum);
    return 0;
}

Common mistakes

  • Using EOF as a numeric value read into x.
  • Checking only feof and forgetting conversion failures or ferror.

Before calling this one solid

  • Processes each successful integer once.
  • Distinguishes empty EOF, bad data and open failure.
  • Checks limits, closes once and justifies sum bounds.

Reference program checked with GCC and Clang in C17 mode.

M11-02TraceFoundation~10 minTrace append, read and truncating write modesNot attempted

Initially log.txt contains exactly start followed by a newline. Trace this full program. Give stdout and the exact file contents after each close. Explain what changes when log.txt is initially absent. Why would opening the first stream with w instead of a change the first line read? Every line in the stated initial file fits in line[64]; assume all file operations succeed for the trace, but retain the reference error checks.

C
#include <stdio.h>
int main(void) {
    FILE *f = fopen("log.txt", "a");
    if (f == NULL) return 1;
    int ok = fputs("next\n", f) != EOF;
    if (fclose(f) == EOF) ok = 0;
    if (!ok) return 1;
    f = fopen("log.txt", "r");
    if (f == NULL) return 1;
    char line[64];
    ok = fgets(line, sizeof line, f) != NULL;
    if (fclose(f) == EOF) ok = 0;
    if (!ok) return 1;
    printf("first=%s", line);
    f = fopen("log.txt", "w");
    if (f == NULL) return 1;
    ok = fputs("reset\n", f) != EOF;
    if (fclose(f) == EOF) ok = 0;
    if (!ok) return 1;
    puts("replaced");
    return 0;
}
Link to this question
Saves in this browser
Hint 1

Append mode preserves existing contents and writes at the end; write mode truncates on successful opening.

Hint 2

The later w open removes both the old first line and the appended line before reset is written.

Worked solution & self-marking checklist

With the stated initial file, stdout is first=start then replaced; the final file contains only reset followed by a newline.

Reason it through

  1. After the append close, log.txt is exactly "start\nnext\n". The r stream then reads "start\n" without changing the file.
  2. After the read close the contents are unchanged and printf emits "first=start\n".
  3. Opening with w truncates the file; after the final close it contains exactly "reset\n". puts emits "replaced\n".
  4. If the file is absent initially, a creates it with "next\n" and the first printed line is first=next. If the first mode were w, even an existing start line would be lost.
  5. Each stream is closed before reopening; every write result and close result is checked.
Model C answer
#include <stdio.h>
int main(void) {
    FILE *f = fopen("log.txt", "a");
    if (f == NULL) return 1;
    int ok = fputs("next\n", f) != EOF;
    if (fclose(f) == EOF) ok = 0;
    if (!ok) return 1;
    f = fopen("log.txt", "r");
    if (f == NULL) return 1;
    char line[64];
    ok = fgets(line, sizeof line, f) != NULL;
    if (fclose(f) == EOF) ok = 0;
    if (!ok) return 1;
    printf("first=%s", line);
    f = fopen("log.txt", "w");
    if (f == NULL) return 1;
    ok = fputs("reset\n", f) != EOF;
    if (fclose(f) == EOF) ok = 0;
    if (!ok) return 1;
    puts("replaced");
    return 0;
}

Expected output

first=start
replaced

Common mistakes

  • Assuming w preserves old contents until the first write.
  • Expecting a mode to start writes at the beginning of an existing file.

Before calling this one solid

  • Gives exact intermediate and final contents.
  • Correctly handles the initially absent variant.
  • Explains a, r and w plus close checks.

Reference program checked with GCC and Clang in C17 mode.

M11-03Write CCore~15 minCopy a file with an int character and checked lifecycleNot attempted

Write a program copying source.txt to the distinct path copy.txt byte for byte, using fgetc/fputc. Use binary modes so the C program does not request text translation. Store each fgetc result in int; explain why char is unsuitable for representing all byte values plus EOF. Report copied=k only after successful reads, writes and both closes. Handle absent input and failed output opening. The output may be partial if a later write fails; no atomic-replacement feature is required. Include empty and multiline file tests.

Link to this question
Saves in this browser
Hint 1

fgetc returns either an unsigned-char value converted to int, or EOF. Test the int before any narrowing.

Hint 2

A loop ending at EOF can mean end-of-file or read failure; inspect ferror, and remember that buffered output can fail at fclose.

Worked solution & self-marking checklist

The byte-copy loop distinguishes the EOF sentinel, checks each write and reports success only after closing both streams.

Reason it through

  1. Open the input first; if output creation fails, close the already-open input before returning. The paths must be distinct to avoid truncating the source.
  2. Use int ch and loop while the fgetc result differs from EOF. A char can lose the distinction between a valid byte and EOF on some implementations.
  3. Check fputc before incrementing count, and guard the size_t counter against overflow.
  4. After reading, check ferror(in). Close both streams regardless of one close failure and combine their statuses.
  5. For source "A\nB\n", the exact destination is "A\nB\n" and copied=4 on the stated byte fixture. Empty input produces an empty destination and copied=0.
Model C answer
#include <stdio.h>
#include <stdint.h>
int main(void) {
    FILE *in = fopen("source.txt", "rb");
    if (in == NULL) { puts("input open error"); return 1; }
    FILE *out = fopen("copy.txt", "wb");
    if (out == NULL) { fclose(in); puts("output open error"); return 1; }
    size_t count = 0;
    int ch, ok = 1;
    while ((ch = fgetc(in)) != EOF) {
        if (count == SIZE_MAX || fputc(ch, out) == EOF) { ok = 0; break; }
        ++count;
    }
    if (ferror(in)) ok = 0;
    if (fclose(in) == EOF) ok = 0;
    if (fclose(out) == EOF) ok = 0;
    if (!ok) { puts("copy error"); return 1; }
    printf("copied=%zu\n", count);
    return 0;
}

Common mistakes

  • Using char ch and comparing it with EOF after truncation.
  • Printing success before a buffered output close has succeeded.

Before calling this one solid

  • Preserves every source byte in the test fixtures.
  • Checks open, read, write and both close results.
  • Explains the int sentinel and partial-output contract.

Reference program checked with GCC and Clang in C17 mode.

M11-04Write CCore~15 minRead complete record pairs and reject partial conversionsNot attempted

scores.txt contains zero to 100 whitespace-separated pairs id score, with id in 1..9999 and score in 0..100; all numeric lexemes passed to %d are representable as int. IDs need not be unique. Write a reader reporting records=k passed=p sum=s, where a score of 40 or more passes. Reject a malformed token, an incomplete final pair, excess records or invalid field with invalid records. Explain the difference between fscanf returning 2, 1, 0 and EOF. Whitespace defines records here: a pair may cross a line boundary; this is not a per-line parser.

Link to this question
Saves in this browser
Hint 1

Only a return of 2 proves that both record fields were assigned.

Hint 2

EOF after exactly one successful conversion returns 1, so a final lone id must be rejected.

Worked solution & self-marking checklist

The loop processes only complete validated pairs and accepts clean EOF only between records.

Reason it through

  1. Open in r mode and reject an absent file before reading. Each successful pair produces got == 2.
  2. Validate both fields and the record-count limit before updating aggregates; the bounded sum is at most 10000.
  3. got == 1 means only id was converted; got == 0 means the next token could not start even the first conversion; neither is a complete record.
  4. EOF is returned when no conversion occurred because input ended or failed. Accept it only with no stream error, after checking fclose too.
  5. For pairs 1 40, 2 39 and 3 100, the result is three records, two passes and sum 179. Empty files are valid with all aggregates zero.
Model C answer
#include <stdio.h>
int main(void) {
    FILE *in = fopen("scores.txt", "r");
    if (in == NULL) { puts("open error"); return 1; }
    int id, score, got;
    size_t records = 0, passed = 0;
    long sum = 0;
    while ((got = fscanf(in, "%d%d", &id, &score)) == 2) {
        if (records == 100 || id < 1 || id > 9999 || score < 0 || score > 100) break;
        ++records;
        sum += score;
        if (score >= 40) ++passed;
    }
    int ok = got == EOF && !ferror(in);
    if (fclose(in) == EOF) ok = 0;
    if (!ok) { puts("invalid records"); return 1; }
    printf("records=%zu passed=%zu sum=%ld\n", records, passed, sum);
    return 0;
}

Common mistakes

  • Checking fscanf(...) != EOF and accidentally processing a partial record.
  • Assuming a newline forces fscanf to finish a record.

Before calling this one solid

  • Explains all four conversion outcomes.
  • Rejects partial/malformed/domain-invalid records.
  • Handles empty input, the threshold and cleanup correctly.

Reference program checked with GCC and Clang in C17 mode.

M11-05Write CFoundation~12 minAppend a validated record without erasing prior recordsNot attempted

Write a program reading one attendance record from stdin as id name present. Numeric input tokens are representable as int; id must be 1..9999 and present must be 0 or 1. A valid name is a single token of 1..15 ASCII letters; input name tokens obey this lexical/length contract. Validate numeric fields and conversions before opening attendance.txt. Append exactly "id name present\n", creating the file if absent; print appended only after fprintf and fclose succeed. For initial file "1 Ana 1\n" and input "2 Bo 0\n", give exact final contents. Explain why this simple file format cannot represent a name containing a space.

Link to this question
Saves in this browser
Hint 1

A 16-byte name array needs %15s so there is room for the null terminator. The stated lexical contract supplies the length bound.

Hint 2

Use a mode, and do not open until conversion and field validation succeed.

Worked solution & self-marking checklist

Append mode preserves earlier records, and a bounded string conversion prevents overflow under the stated input contract.

Reason it through

  1. Read three fields with matching addresses and a bounded %15s conversion; reject failed conversions or invalid numeric fields before any file mutation.
  2. Open with a so existing records remain and new output is appended. A successful absent-file open creates it.
  3. Check fprintf for a negative result and fclose for EOF, because buffered writes can fail during closing.
  4. The final file for the stated example is exactly "1 Ana 1\n2 Bo 0\n". The separating whitespace means a multiword name needs a different encoding or parser.
  5. If existing contents lack a final newline, a does not insert one automatically; the file-format precondition is that existing records are complete newline-terminated lines.
Model C answer
#include <stdio.h>
int main(void) {
    int id, present;
    char name[16];
    if (scanf("%d%15s%d", &id, name, &present) != 3 || id < 1 || id > 9999 || (present != 0 && present != 1)) {
        puts("invalid input"); return 1;
    }
    FILE *out = fopen("attendance.txt", "a");
    if (out == NULL) { puts("open error"); return 1; }
    int ok = fprintf(out, "%d %s %d\n", id, name, present) >= 0;
    if (fclose(out) == EOF) ok = 0;
    if (!ok) { puts("write error"); return 1; }
    puts("appended");
    return 0;
}

Common mistakes

  • Using w and losing earlier records.
  • Forgetting that %s consumes only one whitespace-delimited token or claiming it validates arbitrary-length input.

Before calling this one solid

  • Correct append behavior on existing and absent files.
  • Conversion and domain validation precede opening.
  • Exact output bytes, string capacity and close checks are explained.

Reference program checked with GCC and Clang in C17 mode.

M11-06Write CCore~20 minLoad a counted dynamic array and reject extra tokensNot attempted

values.txt starts with n in 0..100 followed by exactly n integers in -1000..1000 and optional trailing whitespace. For this scanf exercise, the count token is representable as size_t and every numeric value token passed to %d is representable as int; arbitrary huge numeric-token parsing is addressed in the capstones. Allocate n ints, check every read and reject any extra non-whitespace character after the required data. Use a separate sum_values function borrowing the array. Print n=k sum=s, or an error and nonzero exit. Show the resource state after opening, after allocating and during a failed third-element read.

Link to this question
Saves in this browser
Hint 1

Initialize the owning pointer to NULL and the FILE * explicitly so one cleanup path can release whatever was acquired.

Hint 2

After n values, a whitespace-skipping %c conversion detects any extra token; then inspect ferror.

Worked solution & self-marking checklist

A counted file can drive exact allocation, but count, every element and end-of-data must all be checked.

Reason it through

  1. Resource states: after open, in owns an open stream and a = NULL; after allocation, in is open and a owns n ints; during a later failed read, both must be released.
  2. Validate n and its byte multiplication before allocating. For n = 0 use a = NULL and no allocation.
  3. Read precisely n values, validate their range and reject an extra non-whitespace character. This catches both too few and too many values.
  4. Check read errors and close status before reporting success. Set in = NULL after closing so the failure path does not close it twice.
  5. sum_values borrows the live block, does not free it and performs zero iterations for n = 0. The caller releases a on success and failure.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
static long sum_values(const int *a, size_t n) {
    long sum = 0;
    for (size_t i = 0; i < n; ++i) sum += a[i];
    return sum;
}
int main(void) {
    FILE *in = fopen("values.txt", "r");
    if (in == NULL) { puts("open error"); return 1; }
    int *a = NULL;
    size_t n;
    const char *error = "invalid data";
    if (fscanf(in, "%zu", &n) != 1 || n > 100 || n > SIZE_MAX / sizeof *a) goto fail;
    if (n) {
        a = malloc(n * sizeof *a);
        if (a == NULL) { error = "memory error"; goto fail; }
    }
    for (size_t i = 0; i < n; ++i)
        if (fscanf(in, "%d", &a[i]) != 1 || a[i] < -1000 || a[i] > 1000) goto fail;
    char extra;
    if (fscanf(in, " %c", &extra) == 1 || ferror(in)) goto fail;
    if (fclose(in) == EOF) { in = NULL; goto fail; }
    in = NULL;
    printf("n=%zu sum=%ld\n", n, sum_values(a, n));
    free(a);
    return 0;
fail:
    if (in != NULL) fclose(in);
    free(a);
    puts(error);
    return 1;
}

Common mistakes

  • Trusting the header while using uninitialized elements after a short file.
  • Closing in, then reaching cleanup with the old nonnull stream pointer and closing it again.

Before calling this one solid

  • Rejects missing, malformed and surplus data.
  • Shows all requested resource states.
  • One owning pointer, one stream lifecycle and a correct borrowed function interface.

Reference program checked with GCC and Clang in C17 mode.

M11-07Judge every claimCore~12 minJudge every file-state and EOF claim independentlyNot attempted

Judge EVERY statement true or false, justify each and correct false statements. A: r mode creates a missing file. B: a successful w open truncates an existing file. C: a mode sends writes to the current end of the file. D: feof predicts whether the next read will succeed. E: fscanf(f,"%d%d",&a,&b) returning 1 proves a complete pair was read. F: fgetc should be assigned to int before comparing with EOF. G: a loop ending because fgetc returned EOF must distinguish end-of-file from read error with ferror. H: if fprintf succeeded, fclose cannot report a later output failure. I: r+ opens an existing file for reading and writing without automatically truncating it. J: in a general update stream, switching from output to input requires an intervening fflush or positioning operation; switching from input to output requires positioning unless the input operation encountered EOF. K: fflush(stdin) is a portable ISO C way to discard unread input. Treat each claim independently.

Link to this question
Saves in this browser
Hint 1

Separate stream modes, conversion results, end indicators and buffered output: each answers a different question.

Hint 2

For update streams the two directions have different synchronization rules; input flushing is not a general ISO C discard operation.

Worked solution & self-marking checklist

A false; B true; C true; D false; E false; F true; G true; H false; I true; J true; K false.

Reason it through

  1. A: false, r fails if the file cannot be opened for reading; it does not create it. B: true, a successful w open truncates or creates. C: true, append writes occur at the then-current end.
  2. D: false, feof reports an end indicator set by an attempted read, not a prediction. E: false, return 1 means only one assignment was completed.
  3. F: true, int preserves the valid byte results and EOF sentinel. G: true, EOF can signal input failure as well as exhaustion, so inspect ferror.
  4. H: false, buffered output can fail during fclose. I: true, r+ needs an existing readable/writable file and does not itself truncate it.
  5. J: true, obey the ISO C update-stream sequencing rules as stated; using separate open/close phases is often easier for beginners. K: false, ISO C does not define fflush as a general input-discard operation; consume the required characters explicitly instead.

Common mistakes

  • Using EOF, feof and a zero conversion count as interchangeable states.
  • Assuming all file errors must appear at fopen or fprintf.

Before calling this one solid

  • All eleven claims have independent verdicts.
  • Correctly explains both update-stream directions.
  • Repairs every false claim with a concrete portable rule.
M11-08Debug & repairCore~15 minRepair a loader with leaks and a freed return valueNot attempted

Diagnose every resource/lifetime error in load_first below, including failed open, failed allocation, failed conversion and the success path. Replace it with int load_first(const char *path, int **out): the caller supplies a valid out pointer; on success it receives ownership of one allocated int, and on any failure *out remains NULL. Read only the first integer; trailing input is intentionally ignored. Numeric tokens supplied to %d are representable as int. Check stream errors and close results. Write a driver that prints value=k or load failed and frees a successful result. Never run the invalid original.

C
int *load_first(void) {
    FILE *f = fopen("config.txt", "r");
    int *p = malloc(sizeof *p);
    if (fscanf(f, "%d", p) != 1) return NULL;
    fclose(f);
    free(p);
    return p;
}
Link to this question
Saves in this browser
Hint 1

The original does not check either acquired resource, leaks on the early return, and frees the very object it returns.

Hint 2

Set *out = NULL first; publish the allocated pointer only after reading and closing succeed.

Worked solution & self-marking checklist

Ownership transfers only after complete success; all prior failure paths close the stream and release the block.

Reason it through

  1. A failed fopen makes f unusable, and a failed malloc makes p unusable as the conversion destination. Both need checks before fscanf.
  2. A conversion failure in the original returns without closing f or freeing any successful allocation.
  3. On original success, free(p) ends the int lifetime; returning p then gives no usable object. fclose alone would not free p.
  4. The corrected function keeps p locally owned until read, ferror and fclose checks succeed, freeing it on any failure.
  5. On success *out = p transfers ownership to the caller. The caller prints before free and releases exactly once.
Model C answer
#include <stdio.h>
#include <stdlib.h>
static int load_first(const char *path, int **out) {
    *out = NULL;
    FILE *f = fopen(path, "r");
    if (f == NULL) return 0;
    int *p = malloc(sizeof *p);
    if (p == NULL) { fclose(f); return 0; }
    int ok = fscanf(f, "%d", p) == 1;
    if (ferror(f)) ok = 0;
    if (fclose(f) == EOF) ok = 0;
    if (!ok) { free(p); return 0; }
    *out = p;
    return 1;
}
int main(void) {
    int *value;
    if (!load_first("config.txt", &value)) { puts("load failed"); return 1; }
    printf("value=%d\n", *value);
    free(value);
    return 0;
}

Common mistakes

  • Publishing *out before the rest of the operation succeeds, then leaving a dangling output on failure.
  • Believing fclose releases unrelated malloc storage.

Before calling this one solid

  • All four original failure/success situations are diagnosed.
  • Failure preserves NULL output and releases every acquired resource.
  • Caller uses and frees a live successful result.

Reference program checked with GCC and Clang in C17 mode.

M11-09Design & integrateStretch~35 minCapstone: validate, sort and report an inventory fileNot attempted

This is an invented practice case, not a reconstruction of an unspecified course case. Build a complete C17 inventory-report program in five stages. Stage 1: choose a record representation and document ownership. inventory.txt contains a count n in 0..1000, followed by exactly n whitespace-separated triples id quantity unit_cents; IDs are unique and in 1..1000000, quantities 0..10000 and prices 0..1000000. Reject missing, extra, malformed or out-of-range tokens, including numeric overflow. A token longer than 63 bytes is invalid. Stage 2: load an exactly sized dynamic record array, with size/allocation checks; n = 0 is valid. Stage 3: write a borrowing item_value function and selection-sort records by ascending ID, without parallel-array mismatches. Use integer cents and justify a safe aggregate type. Stage 4: only after full validation and successful input close, open inventory-report.csv in w mode. Write the header id,quantity,unit_cents,value_cents and one comma-separated record per line. Print OK items=n total_cents=t after successful output close. Stage 5: on input, memory or output failure print ERROR input, ERROR memory or ERROR output, return nonzero, and release all owned resources. Invalid input must preserve any existing report; an output write failure may leave a partial report. A bounded token reader with strtoll/ERANGE is supplied in the model so arbitrary integer overflow need not be guessed with scanf. Before revealing it, outline that helper’s three-result contract. Trace the ownership and resources at each stage. Test normal unsorted data, zero records, duplicate IDs, a truncated record, a huge integer token and missing input. For the three records (20,2,150), (5,0,999), (11,3,200), supply exact stdout and report contents.

Link to this question
Saves in this browser
Hint 1

Keep the input open stream and one owning Item * separate. Do not open the output until validation, extra-token checking and input close have succeeded.

Hint 2

Parse into long long before narrowing to bounded fields; selection sort swaps entire Item structs. Each record value is at most 10^10 cents and the total at most 10^13 cents.

Worked solution & self-marking checklist

Validate completely, sort whole records, then write a checked CSV report; one array owner is released on every exit.

Reason it through

  1. Representation: Item contains long id, int quantity and long unit_cents. The main function owns the dynamic Item block; item_value and sort_items borrow it. Numeric field bounds fit even the minimum standard ranges of int and long.
  2. read_integer returns 1 for a complete valid decimal integer token, 0 for clean EOF and -1 for malformed, oversized or overflowing tokens/read errors. It keeps fgetc in int, uses unsigned-char values for isspace, checks strtoll with errno and the end pointer, and rejects embedded NULs.
  3. Validate count before converting to size_t, guard n * sizeof *items and allocate only for n > 0. Validate each full record and uniqueness before proceeding; a failure leaves the array locally owned for cleanup.
  4. item_value converts quantity to long long before multiplication. Maximum per-record value is 10000 * 1000000 = 10000000000, and the maximum aggregate is 1000 times that, safely within the required long long range.
  5. Check clean end-of-data and fclose before opening the report. Selection sort chooses the least remaining ID and swaps the whole struct, preserving field association.
  6. For the sample, stdout is "OK items=3 total_cents=900\n". The exact report is "id,quantity,unit_cents,value_cents\n5,0,999,0\n11,3,200,600\n20,2,150,300\n". Empty input writes the header alone and reports a zero total.
  7. Resource path: input stream -> input stream plus owned array -> owned array after input close -> array plus output stream -> array after output close -> no resources after free. On a primary failure, cleanup closes any remaining stream once and frees the array; cleanup-close failures do not replace the original error category.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>

typedef struct { long id; int quantity; long unit_cents; } Item;

/* 1 = valid integer token, 0 = clean EOF, -1 = malformed token/I/O error. */
static int read_integer(FILE *f, long long *out) {
    char token[64];
    size_t used = 0;
    int ch, bad = 0;
    do { ch = fgetc(f); } while (ch != EOF && isspace((unsigned char)ch));
    if (ch == EOF) return ferror(f) ? -1 : 0;
    do {
        if (ch == 0) bad = 1;
        if (used + 1 < sizeof token) token[used++] = (char)ch;
        else bad = 1;
        ch = fgetc(f);
    } while (ch != EOF && !isspace((unsigned char)ch));
    if (bad || ferror(f)) return -1;
    token[used] = '\0';
    errno = 0;
    char *end;
    long long value = strtoll(token, &end, 10);
    if (errno == ERANGE || end == token || *end != '\0') return -1;
    *out = value;
    return 1;
}

static long long item_value(const Item *item) {
    return (long long)item->quantity * item->unit_cents;
}
static void sort_items(Item *items, size_t n) {
    for (size_t i = 0; i < n; ++i) {
        size_t least = i;
        for (size_t j = i + 1; j < n; ++j)
            if (items[j].id < items[least].id) least = j;
        if (least != i) {
            Item temp = items[i];
            items[i] = items[least];
            items[least] = temp;
        }
    }
}
int main(void) {
    FILE *in = fopen("inventory.txt", "r"), *out = NULL;
    Item *items = NULL;
    size_t n = 0;
    long long x, total = 0;
    int status = 1;
    const char *error = "ERROR input";
    if (in == NULL) { puts(error); return 1; }
    if (read_integer(in, &x) != 1 || x < 0 || x > 1000) goto done;
    n = (size_t)x;
    if (n > SIZE_MAX / sizeof *items) { error = "ERROR memory"; goto done; }
    if (n) {
        items = malloc(n * sizeof *items);
        if (items == NULL) { error = "ERROR memory"; goto done; }
    }
    for (size_t i = 0; i < n; ++i) {
        if (read_integer(in, &x) != 1 || x < 1 || x > 1000000) goto done;
        items[i].id = (long)x;
        for (size_t j = 0; j < i; ++j)
            if (items[j].id == items[i].id) goto done;
        if (read_integer(in, &x) != 1 || x < 0 || x > 10000) goto done;
        items[i].quantity = (int)x;
        if (read_integer(in, &x) != 1 || x < 0 || x > 1000000) goto done;
        items[i].unit_cents = (long)x;
        total += item_value(&items[i]);
    }
    if (read_integer(in, &x) != 0) goto done;
    if (fclose(in) == EOF) { in = NULL; goto done; }
    in = NULL;
    sort_items(items, n);
    error = "ERROR output";
    out = fopen("inventory-report.csv", "w");
    if (out == NULL) goto done;
    int ok = fprintf(out, "id,quantity,unit_cents,value_cents\n") >= 0;
    for (size_t i = 0; i < n && ok; ++i)
        if (fprintf(out, "%ld,%d,%ld,%lld\n", items[i].id, items[i].quantity,
                    items[i].unit_cents, item_value(&items[i])) < 0) ok = 0;
    if (fclose(out) == EOF) ok = 0;
    out = NULL;
    if (!ok) goto done;
    printf("OK items=%zu total_cents=%lld\n", n, total);
    status = 0;
done:
    if (in != NULL) fclose(in);
    if (out != NULL) fclose(out);
    free(items);
    if (status) puts(error);
    return status;
}

Expected output

OK items=3 total_cents=900

Common mistakes

  • Opening the report with w before validating input, thereby destroying an existing report on invalid data.
  • Multiplying in int before widening, using floating prices, or sorting only IDs while leaving other fields behind.
  • Using an unchecked %d conversion to claim arbitrary oversized numeric tokens are safely rejected.

Before calling this one solid

  • All five stages and exact format/validation rules are implemented.
  • A documented single owner, borrowed function parameters and cleanup for every acquired resource.
  • Guards allocation size and proves arithmetic bounds before narrowing or multiplying.
  • Tests normal, empty, duplicate, truncated, overflow-token and missing-file cases.
  • Checks input and output closes before declaring success and preserves the report on invalid input.

Reference program checked with GCC and Clang in C17 mode.

M11-10Design & integrateStretch~35 minCapstone: own per-student mark arrays and generate resultsNot attempted

This is an invented five-part practice case, not an assertion about the course’s unnamed comprehensive case. Part 1: marks.txt starts with n in 0..100 and subjects in 1..10, then exactly n records: a unique id in 1..1000000 followed by subjects marks, each in 0..100. Tokens are whitespace separated decimal integers; reject missing/extra/malformed/overflowing tokens and tokens longer than 63 bytes. Choose Student { long id; int *marks; }, with one allocated Student array and a separately allocated marks array per student; do not replace this ownership exercise with a fixed matrix. Part 2: build a loader whose every partial state can be destroyed safely, including failure allocating a later row. Explain how initializing every child pointer to NULL supports cleanup. Part 3: write borrowing functions for total and “all marks at least 40.” A high total cannot compensate for one failed subject. Select the highest total; ties choose the smaller ID, even if the tied record occurs later. Part 4: after complete validation and successful input close, write results.csv with header id,total,status, preserving input order and using PASS or RETAKE. Print OK students=n subjects=m best_id=id best_total=t, or OK students=0 subjects=m best=none for no students. Part 5: handle input/memory/output failures with ERROR input, ERROR memory or ERROR output and nonzero status; close every opened stream and free all allocated rows and the table. Invalid input must preserve an existing results.csv; failed output may leave a partial file. Use the bounded integer-token helper from the model or an equivalent overflow-aware parser. For n=3, subjects=3 and records (9,80,80,80), (7,100,100,40), (12,100,100,39), state exact stdout/results, show the tie decision and draw ownership after the second row. Test empty input, threshold 40, equal totals, a late invalid score, duplicate IDs, truncated rows and a missing file.

Link to this question
Saves in this browser
Hint 1

Initialize all n marks pointers immediately after allocating the Student array, before reading any record. Then cleanup may free all n pointers: unused ones are NULL.

Hint 2

Keep validity, pass status and best-total selection separate. The third sample has total 239 but RETAKE because 39 is below 40.

Worked solution & self-marking checklist

A table with NULL-initialized child pointers permits safe cleanup after any partial row allocation or parse failure.

Reason it through

  1. Ownership after row 2: main -> Student table [id9,marks0*; id7,marks1*; marks2=NULL]; marks0* -> [80,80,80], marks1* -> [100,100,40]. There are three live allocations, with more children to follow. Functions receive borrowed pointers only.
  2. The overflow-aware token reader separates valid tokens, clean EOF and malformed/overflow/read failure. Validate n and subjects before narrowing and size multiplication; initialize all child pointers before a failure can reach the destructor.
  3. Each successfully allocated row belongs to its Student entry. destroy_students frees each child, including NULL safely, before freeing the table. If the table allocation itself failed, it skips child access.
  4. Totals are at most 10 * 100 = 1000, safe for long. PASS requires every grade >= 40; student 12 has RETAKE despite total 239.
  5. Students 9 and 7 tie at 240. Explicitly compare IDs on equal totals, selecting 7. A zero-student case never reads a nonexistent best entry.
  6. For the sample, stdout is "OK students=3 subjects=3 best_id=7 best_total=240\n". The exact report is "id,total,status\n9,240,PASS\n7,240,PASS\n12,239,RETAKE\n". For n=0 the report contains only its header.
  7. Do not open results.csv until input validation and close succeed. Check every output write and the output close, then destroy the rows/table on success or failure. A secondary cleanup-close error does not replace the primary failure category.
Model C answer
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>

typedef struct { long id; int *marks; } Student;

/* 1 = valid integer token, 0 = clean EOF, -1 = malformed token/I/O error. */
static int read_integer(FILE *f, long long *out) {
    char token[64];
    size_t used = 0;
    int ch, bad = 0;
    do { ch = fgetc(f); } while (ch != EOF && isspace((unsigned char)ch));
    if (ch == EOF) return ferror(f) ? -1 : 0;
    do {
        if (ch == 0) bad = 1;
        if (used + 1 < sizeof token) token[used++] = (char)ch;
        else bad = 1;
        ch = fgetc(f);
    } while (ch != EOF && !isspace((unsigned char)ch));
    if (bad || ferror(f)) return -1;
    token[used] = '\0';
    errno = 0;
    char *end;
    long long value = strtoll(token, &end, 10);
    if (errno == ERANGE || end == token || *end != '\0') return -1;
    *out = value;
    return 1;
}

static long student_total(const Student *s, size_t subjects) {
    long total = 0;
    for (size_t j = 0; j < subjects; ++j) total += s->marks[j];
    return total;
}
static int student_passes(const Student *s, size_t subjects) {
    for (size_t j = 0; j < subjects; ++j)
        if (s->marks[j] < 40) return 0;
    return 1;
}
static void destroy_students(Student *students, size_t n) {
    if (students != NULL)
        for (size_t i = 0; i < n; ++i) free(students[i].marks);
    free(students);
}
int main(void) {
    FILE *in = fopen("marks.txt", "r"), *out = NULL;
    Student *students = NULL;
    size_t n = 0, subjects = 0;
    long long x;
    int status = 1;
    const char *error = "ERROR input";
    if (in == NULL) { puts(error); return 1; }
    if (read_integer(in, &x) != 1 || x < 0 || x > 100) goto done;
    n = (size_t)x;
    if (read_integer(in, &x) != 1 || x < 1 || x > 10) goto done;
    subjects = (size_t)x;
    if (n > SIZE_MAX / sizeof *students) { error = "ERROR memory"; goto done; }
    if (n) {
        students = malloc(n * sizeof *students);
        if (students == NULL) { error = "ERROR memory"; goto done; }
        for (size_t i = 0; i < n; ++i) students[i].marks = NULL;
    }
    for (size_t i = 0; i < n; ++i) {
        if (read_integer(in, &x) != 1 || x < 1 || x > 1000000) goto done;
        students[i].id = (long)x;
        for (size_t j = 0; j < i; ++j)
            if (students[j].id == students[i].id) goto done;
        if (subjects > SIZE_MAX / sizeof *students[i].marks) { error = "ERROR memory"; goto done; }
        students[i].marks = malloc(subjects * sizeof *students[i].marks);
        if (students[i].marks == NULL) { error = "ERROR memory"; goto done; }
        for (size_t j = 0; j < subjects; ++j) {
            if (read_integer(in, &x) != 1 || x < 0 || x > 100) goto done;
            students[i].marks[j] = (int)x;
        }
    }
    if (read_integer(in, &x) != 0) goto done;
    if (fclose(in) == EOF) { in = NULL; goto done; }
    in = NULL;
    error = "ERROR output";
    out = fopen("results.csv", "w");
    if (out == NULL) goto done;
    int ok = fprintf(out, "id,total,status\n") >= 0;
    for (size_t i = 0; i < n && ok; ++i)
        if (fprintf(out, "%ld,%ld,%s\n", students[i].id,
                    student_total(&students[i], subjects),
                    student_passes(&students[i], subjects) ? "PASS" : "RETAKE") < 0) ok = 0;
    if (fclose(out) == EOF) ok = 0;
    out = NULL;
    if (!ok) goto done;
    if (!n) printf("OK students=0 subjects=%zu best=none\n", subjects);
    else {
        size_t best = 0;
        for (size_t i = 1; i < n; ++i) {
            long current = student_total(&students[i], subjects);
            long previous = student_total(&students[best], subjects);
            if (current > previous || (current == previous && students[i].id < students[best].id)) best = i;
        }
        printf("OK students=%zu subjects=%zu best_id=%ld best_total=%ld\n",
               n, subjects, students[best].id, student_total(&students[best], subjects));
    }
    status = 0;
done:
    if (in != NULL) fclose(in);
    if (out != NULL) fclose(out);
    destroy_students(students, n);
    if (status) puts(error);
    return status;
}

Expected output

OK students=3 subjects=3 best_id=7 best_total=240

Common mistakes

  • Freeing only the Student table while leaking every marks row.
  • Iterating over uninitialized child pointers after a partial allocation failure.
  • Choosing a best record solely by first occurrence, or defining PASS from average/total instead of every subject.

Before calling this one solid

  • All five parts, exact file format and tie/threshold semantics are satisfied.
  • A diagram shows table ownership and separate row allocations.
  • Every partial state has safe child-before-table cleanup and checked allocation sizes.
  • Validates count, dimensions, IDs, grades, duplicates, EOF and overflowing tokens.
  • Tests cover sample tie, empty set, threshold, partial data, duplicates and preserved output on invalid input.

Reference program checked with GCC and Clang in C17 mode.

Recall sheet

The rules worth reconstructing.

Use this after an attempt, then close it and explain the rule yourself. Baseline: standard C17 for the reference programs. Concrete questions state their own inputs and assumptions; no universal machine layout or exam weighting is assumed.

Types, formats & input

Match the conversion to the actual object. An input function needs addresses of writable objects; output normally needs values.

  • printf("%d", n) for an int; scanf("%d", &n) reads one. Check that scanf returns 1.
  • printf("%f", x) receives a double. For input, %f needs float *; %lf needs double *.
  • %c reads the next character, including whitespace. A leading space in " %c" skips preceding whitespace.
  • %zu prints a size_t, such as the result of sizeof.
  • Bound a word read: char word[20]; scanf("%19s", word). For a line with spaces, use fgets(word, sizeof word, stdin), check its return and handle a possible newline or overlong line.
Expressions: what order is guaranteed?
  • 5 / 2 is integer division. Convert an operand before division for 2.5: 5 / 2.0.
  • Precedence groups an expression; it does not generally fix the order in which operands or function arguments are evaluated.
  • && and || evaluate left first and may skip the right operand. Test the pointer or bound before an access.
  • = assigns; == compares. A nonzero condition is true; relational/logical operators produce 0 or 1.
  • i++ + ++i modifies the same scalar without the required sequencing: undefined behavior. Do not invent an output from a compiler run.
  • Unknown pointer sizes, signed overflow, and out-of-bounds access are not safe puzzles with a universal numerical answer. State the relevant rule.
Loops, search & sorting
  • For n elements, valid indices run from 0 through n - 1. A traversal typically uses i < n.
  • Trace initialization → condition → body → update. In a for loop, continue still goes to the update; in a while loop an update skipped by continue can prevent progress.
  • break exits the nearest enclosing loop or switch; continue applies to the nearest loop.
  • Linear search: specify first match versus any match, and distinguish index 0 from not found.
  • Selection sort: after pass i, the smallest remaining element occupies position i. Show each selected minimum and swap. The standard nested-loop variant makes n(n−1)/2 comparisons.
  • Test empty/one-element input when the interface permits it, duplicates, already sorted values and a missing target.
Functions, scope & storage duration
  • C passes argument values. A function can change a caller’s object through a pointer value that points to it.
  • A declaration gives the function interface; a definition includes its body. Match parameter and return types.
  • Scope answers where a name is visible. Storage duration answers how long its object exists. These are different questions.
  • An ordinary automatic local has a fresh lifetime on each relevant call/block execution. A static local retains its value between calls; its name still has block scope.
  • File-scope objects have static storage duration. Uninitialized static-duration objects receive zero initialization; an uninitialized automatic int must not be read as though it held a known value.
  • Do not return a pointer to an automatic local. Draw caller, callee and heap objects separately in a memory snapshot.
Arrays, pointers & strings
  • An array object is a contiguous sequence of elements. In most expressions its name converts to a pointer to the first element; the array and pointer objects are not identical types of object.
  • sizeof a / sizeof a[0] counts elements only where a is the actual array, not an adjusted function parameter.
  • p + 1 advances by one pointed-to element. Pointer arithmetic is bounded by the same array (including forming its one-past pointer); do not dereference one-past.
  • A C string needs a terminating '\0'. char s[] = "cat"; has four elements. strlen counts characters before the terminator; it does not give the buffer capacity.
  • Use strcmp to compare string contents. Pointer equality does not compare their text.
  • String literals must not be modified. A writable array initialized from a literal is a different case.
Matrices & records
  • A built-in 2-D array is row-major: the rightmost index varies fastest. For int a[R][C], element offset is r*C + c.
  • Matrix addition needs equal dimensions. Multiplication of r×k and k×c produces r×c; initialize each output sum, then accumulate across the shared dimension.
  • A true 2-D array and int ** have different representations and cannot be interchanged by wishful casting.
  • Use record.member for an object and ptr->member for a valid pointer to one.
  • Structure assignment copies its members, including array members. An ordinary array cannot itself be assigned with =.
  • A pointer member is copied as a pointer value, not as a new allocation. Structure size can include padding; do not assume it equals the sum of visible field sizes.
Allocation, ownership & 2-D cleanup
  • Include <stdlib.h>. Prefer int *p = malloc(n * sizeof *p); so the element size matches the pointer type. Establish that the size product is representable.
  • Check allocation failure before access. Allocated storage is initially uninitialized when obtained with malloc.
  • Every successful allocation needs one responsible owner and one eventual matching free. An alias does not become a second owner.
  • After free(p), do not dereference the old pointer or free it again. Assigning p = NULL helps that variable; it does not update other aliases.
  • A flat matrix can use one allocation and p[r*cols+c]. A row-pointer matrix has a table allocation plus row allocations; free each successful row, then the table.
  • If allocation of row j fails, release rows 0 through j-1 and the table. Explain cleanup on success and failure.
Files: results before EOF flags
  • Check FILE *fp = fopen(path, mode) before use. "r" reads an existing file; "w" creates/truncates; "a" appends.
  • Drive a loop with the read result, not while (!feof(fp)). A failed read is what discovers the end.
  • Store fgetc in an int so its result can be compared with EOF. After the loop, distinguish an input error with ferror.
  • For two conversions, fscanf(fp, "%d %d", &a, &b) == 2 means a complete record was obtained. Malformed input can return fewer conversions without reaching EOF.
  • Use bounded text fields. State what happens on a partial or invalid record; do not silently reuse stale variables.
  • Check important writes and close results. Close a file once; do not use its stream after fclose.
The written-answer method
  1. State inputs, output contract, preconditions and any necessary assumptions.
  2. For a trace, draw a table with iteration/call, relevant variables, array or pointed-to object state, and output so far.
  3. For code, choose types and representations, then write clear loops and function interfaces.
  4. Explain the decisive invariant or ownership rule. “It works” is not a reason.
  5. Check a normal case and a boundary/failure case. Finish with the exact output, result, or corrected behavior.

For independent claims, judge every statement separately and give its reason or counterexample. Do not stop once one true statement is found.

Compile, run & inspect your assumptions

Attempt on paper or in the answer box first. Then save a program as answer.c and compile it:

Terminal
cc -std=c17 -Wall -Wextra -pedantic answer.c -o answer
./answer

Read compiler diagnostics before changing random lines. Compare results against your trace. A clean compilation or one successful run does not prove absence of undefined behavior. The reference download contains complete checked programs and the test inputs used for them.

Study for answers you can produce.

Start with the diagnostic if you cannot tell which concepts have faded. Follow the six-hour route for a balanced session, or use topic filters to repair a specific gap. A question marked solid should be one you can solve and explain again with the answer closed. Include short breaks between blocks.

Each solution contains reasoning, a model answer where appropriate, common mistakes and a checklist. Times are estimates for study. The two 75-minute sets are original exercises; they do not claim to match the question mix, difficulty or marking of the BITS examination. The complete syllabus remains available on the main guide.

Coverage follows the enrolled module headings already documented in the programming syllabus. All questions here are newly written. Unspecified official case studies are not reconstructed or represented as past papers.

C language reference · WG14 N1570 (C11 draft)GCC warning optionsEnrolled compre practice · Coursera sign-in