CS U111 · Lab-eval ladder · Stage 3

Arrays, one and two dimensions: from "read N values" to spirals and 60-digit numbers

Twenty-one programs in four rungs, all in the lab-eval format: read the input silently, print only the answer, five tests per problem. Rung A walks an array; Rung A+ drills the input shapes an arrays eval would use; Rung B is five eval-sized problems that genuinely need the array; Rung C is the old lab-sheet-plus-twist set, for after B. Every solution was compiled with clang -Wall -Wextra -std=c11 (no warnings), and every expected output is what that solution printed.

Start here

What this stage covers: Lab Sheet 6: 1D arrays (read, traverse, search, sort, count frequencies) and 2D arrays (read a matrix, walk rows and columns). Rung C also passes arrays to functions, joining this stage to Stage 2.

A fact about the evals: no arrays lab evaluation has been released yet. The instructor's 28 real evals (on the real lab evals page) cover if/else, loops and functions. So Rung B here is calibrated against those: its format is modelled on the real evals; its difficulty is our estimate. What will almost certainly carry over is the shape: N then N values, 5–15 lines of logic, and tests at N = 1, N = 0, negatives and ties.

A fact about the gap: arrays are the first topic in this course that school maths doesn't preview, so classmates with a JEE background start this stage from the same place as you. Almost every array program is one of a handful of loops: walk forwards, walk backwards, compare neighbours, count into a table, nested row/column walk. This page drills exactly those.

What the rungs mean: A · warm-up (3–8 lines each), A+ · the eval input shapes (5–10 lines), B · eval level (5–15 lines, 15–20 min each, like a real eval), C · optional, longer than any eval seen so far.

Time: A about 30 min, A+ about 25 min, B about 90 min: roughly 2½ hours for the part that matters most. Rung C is another 4 hours or so, only if time allows. If you're short of time: A1, A+1, A+3, then B1–B5.

How to use it: attempt each problem in a blank file before opening anything. If you can't start, open only "Stuck? First move". Open the full solution last, after your own version passes the tests.

Optional Rung 0: if a[i] itself still feels shaky, first spend 30–40 minutes on the arrays ladder: 17 one-idea programs, each a few lines long.

How these are marked

Every program on this page reads its input silently and prints only the answer, exactly as VPL expects: no prompts asking for input, no debug prints. Each card has 5 tests, and VPL takes 14 % off for each one failed. Check one test with Copy input → run your program → paste your output → Check. Or press Download test script, save it next to your .c file and run sh s3-b1-tests.sh b1.c in Terminal to run all five at once (it compiles with cc -Wall -Wextra). Like VPL, it ignores spaces, line breaks and letter case, but every word and number must match. The full explanation is in Stage 0, "how VPL runs your program".

Need the teaching first? The arrays lesson explains everything from scratch (with step-through animations of the sorts); the arrays notes are the revision map with the pattern cookbook.

Syntax you need for this stage

FormWhat it means
int a[100];100 ints, indices 0 to 99. Declare the maximum the question allows, then use only the first n.
int freq[7] = {0};All seven elements start at 0. Without = {0} a local array holds garbage.
for (i = 0; i < n; i++) scanf("%d", &a[i]);Read n values. Keep the &: a[i] is a single int, just like x.
for (i = n - 1; i >= 0; i--)Walk backwards. The last valid index is n - 1, not n.
a[i - 1], a[i + 1]Neighbours. Choose the loop bounds so both stay inside 0…n−1 (start at 1, or stop at n - 1).
freq[x]++;The value is used as the index: "one more x seen".
t = a[i]; a[i] = a[j]; a[j] = t;Swap two elements. Three lines, one temporary.
int m[10][10]; · m[i][j]A matrix: row i, column j, both from 0.
for (i…) for (j…)Outer loop over rows, inner over columns: walks the matrix row by row. Swap the roles to walk column by column.
void printArray(int a[], int n)Passing an array to a function: pass its count too. Unlike an int, the function works on the caller's array itself, so it can fill it (C7's readArray does).
sizeof(a) / sizeof(a[0])Number of elements, but only where a was declared (see the trap in C7).

Rung A · Warm-up

About 30 minutes, 5–10 each. Every array program starts the same way: read N, then a loop that reads N values into a[0] … a[N-1]. These four train that opening plus the basic walks (forwards, backwards, neighbours, row by row). Type the opening from memory until it takes under a minute.

A1 · Sum, and where the maximum is

Rung A 5–10 min · Pattern: accumulate · running max by index · Lab 6 Problem 2, plus the position

Problem

Read N (1 ≤ N ≤ 100) and then N integers. Print their sum, the maximum, and the index (counting from 0) where the maximum first occurs.

Input N, then N integers (on one line or several).

Output Three integers separated by spaces: sum, maximum, index of the first maximum.

Test 1 · sample
5
4 8 2 9 1
24 9 3
Test 2
4
-3 -8 -1 -1
-13 -1 2
Test 3
1
42
42 42 0
Test 4
3
5 5 5
15 5 0
Test 5
4
1 2 3 10
16 10 3
Stuck? First move

Declare int a[100]; int n, i, sum = 0, maxIdx = 0;, read n, and write the reading loop. Then think "the max is at index 0 until something beats it": you store the index of the max, and a[maxIdx] gives the value.

Plan in plain words
  1. Read N and the N values.
  2. For each i: add a[i] to sum; if a[i] > a[maxIdx], set maxIdx ← i.
  3. Print sum, a[maxIdx], maxIdx.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, sum = 0, maxIdx = 0;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (i = 0; i < n; i++) {
        sum = sum + a[i];
        if (a[i] > a[maxIdx])       /* >, not >=: keeps the FIRST maximum */
            maxIdx = i;             /* remember WHERE the max is */
    }
    printf("%d %d %d\n", sum, a[maxIdx], maxIdx);
    return 0;
}
Classic trap

Starting the max at 0 (max = 0) instead of at the first element. On Test 2 (all negative) it would print 0, a number that isn't even in the array. And >= instead of > moves the index to the last tied maximum: Tests 2 and 4 catch that.

A2 · Print in reverse

Rung A 5 min · Pattern: backward walk · Lab 6 Problem 3: if you've done it, do this from memory and move on

Problem

Read N (1 ≤ N ≤ 100) and N integers; print them in reverse order, without a second array.

Input N, then N integers.

Output The N integers in reverse order, separated by spaces.

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

Same reading loop as A1. The printing loop starts at the last valid index, which is n - 1, and goes down while i >= 0.

Plan in plain words
  1. Read N and the values.
  2. For i from N − 1 down to 0: print a[i].
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (i = n - 1; i >= 0; i--)    /* last valid index is n-1 */
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Classic trap · out-of-bounds access

Starting at i = n, or summing with i <= n. a[n] is one past the end. C does not stop you: no compiler warning, no error message, just whatever happens to be in memory there. This program sums a 5-element array with i <= 5:

#include <stdio.h>

int main(void) {
    int a[5] = {1, 2, 3, 4, 5};
    int i, sum = 0;
    for (i = 0; i <= 5; i++)      /* BUG: i = 5 is not a valid index */
        sum = sum + a[i];
    printf("%d\n", sum);
    return 0;
}

clang -Wall -Wextra gave no warning. The real run on a Mac printed (the right answer is 15):

16

On another machine it could be a different number or a crash, which is why these bugs survive testing. To catch them while practising, compile with -fsanitize=address -g (gcc and clang both accept it): the same program then stops with stack-buffer-overflow and names line 7.

A3 · Warmer than yesterday

Rung A 5–10 min · Pattern: compare neighbours

Problem

Read N (1 ≤ N ≤ 100) daily temperatures. On the first line, print the day numbers (counting from day 1) that were strictly warmer than the day before, or NONE if there are none. On the second line, print how many there were.

Input N, then N integers.

Output Line 1: day numbers separated by spaces, or NONE. Line 2: the count.

Test 1 · sample
7
30 32 31 31 33 35 34
2 5 6
3
Test 2
4
40 38 35 30
NONE
0
Test 3
1
25
NONE
0
Test 4
3
31 31 31
NONE
0
Test 5
4
-5 -4 -3 -2
2 3 4
3
Stuck? First move

Each check compares t[i] with t[i - 1]. Day 1 (index 0) has no "day before", so the loop starts at i = 1. Index i is printed as day i + 1.

Plan in plain words
  1. Read N and the temperatures. count ← 0.
  2. For i = 1 to N − 1: if t[i] > t[i − 1], print i + 1 and add 1 to count.
  3. If count is 0, print NONE. Then a newline and the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int t[100];
    int n, i, count = 0;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &t[i]);

    for (i = 1; i < n; i++) {       /* start at 1: day 1 has no "before" */
        if (t[i] > t[i - 1]) {
            printf("%d ", i + 1);   /* index i is day i+1 */
            count++;
        }
    }
    if (count == 0)
        printf("NONE");
    printf("\n%d\n", count);
    return 0;
}
Classic trap

Starting the loop at i = 0: then t[i - 1] is t[-1], outside the array, and day 1 is compared with whatever garbage sits there. The output then depends on luck; Test 3 (one day only) must print NONE and 0 every time.

A4 · Row sums of a matrix

Rung A 10 min · Pattern: nested loop · reset per row

Problem

Read R C (1 to 10 each), then an R × C matrix row by row. Print each row's sum on its own line.

Input R C, then R rows of C integers.

Output R lines, one row sum each.

Test 1 · sample
2 3
1 2 3
4 5 6
6
15
Test 2
1 1
-9
-9
Test 3
3 1
4
0
-4
4
0
-4
Test 4
2 4
1 1 1 1
-2 5 0 7
4
10
Test 5
3 2
10 20
30 40
50 60
30
70
110
Stuck? First move

Declare int m[10][10];. Reading is two nested loops: for (i = 0; i < r; i++) for (j = 0; j < c; j++) scanf("%d", &m[i][j]);. Summing is the same two loops, with rowSum = 0; just inside the outer one.

Plan in plain words
  1. Read R, C, then the matrix.
  2. For each row: rowSum ← 0; for each column: add the element to rowSum. After the row: print rowSum and a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int m[10][10];
    int r, c, i, j, rowSum;

    scanf("%d %d", &r, &c);
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &m[i][j]);

    for (i = 0; i < r; i++) {
        rowSum = 0;                 /* reset for every row */
        for (j = 0; j < c; j++)
            rowSum = rowSum + m[i][j];
        printf("%d\n", rowSum);
    }
    return 0;
}
Classic trap

Setting rowSum = 0 once, before both loops. Row 2's sum then includes row 1's (Test 1 would print 21 instead of 15).

Rung A+ · Input patterns

About 25 minutes in all. These are tiny on purpose: their only point is the input shape an arrays eval would use. Three shapes: N then N values stored for a second pass (and N = 0 handled); a block of values followed by a block of queries; R C then a grid. scanf("%d", …) skips spaces and line breaks alike, so it doesn't matter whether the values arrive on one line or many.

A+1 · How many equal the last one?

Rung A+ 5–10 min · Pattern: read N into an array · second pass · guard N = 0

Problem

Read N (0 ≤ N ≤ 100) and then N integers. Print how many of them are equal to the last one (the last one counts itself). If N is 0, print 0.

Input N, then N integers.

Output One integer.

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

You can't know which value to count until you have read the last one, so one pass is not enough: first store all N values in a[100], then walk the array a second time comparing each a[i] with a[n - 1].

Plan in plain words
  1. Read N. If N is 0, print 0 and stop.
  2. Read the N values into a[0] … a[N−1].
  3. last ← a[N − 1]; count the i with a[i] = last; print the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, last, count = 0;

    scanf("%d", &n);
    if (n == 0) {                   /* no values: a[n-1] would be a[-1] */
        printf("0\n");
        return 0;
    }
    for (i = 0; i < n; i++)         /* pass 1: store everything */
        scanf("%d", &a[i]);

    last = a[n - 1];
    for (i = 0; i < n; i++)         /* pass 2: compare with the last */
        if (a[i] == last)
            count++;
    printf("%d\n", count);
    return 0;
}
Classic trap

Two ways to lose marks here. Looping i < n - 1 "because the last one is the target" forgets that the last one counts itself (every test except N = 0 fails). And reading a[n - 1] when N is 0 reads a[-1]: no error message, just garbage. Real evals always include an N = 0 test when the statement allows it.

A+2 · Look up positions

Rung A+ 10 min · Pattern: read N values · then Q queries · position p is a[p - 1]

Problem

Read N (1 ≤ N ≤ 100) and N integers. Then read Q (Q ≥ 1) and Q positions. For each position p, print the value at that position, counting the first value as position 1. If p is not between 1 and N, print INVALID instead.

Input N, then N integers, then Q, then Q positions.

Output Q lines: a value or INVALID.

Test 1 · sample
5
10 20 30 40 50
3
1 5 3
10
50
30
Test 2
1
-7
3
1 0 2
-7
INVALID
INVALID
Test 3
4
8 6 4 2
2
4 5
2
INVALID
Test 4
3
9 9 9
2
-1 2
INVALID
9
Test 5
6
1 2 3 4 5 6
4
6 1 7 3
6
1
INVALID
3
Stuck? First move

The input has two blocks, and the first must be stored before the second can be answered: read all N values into the array, then a separate loop for the Q queries. Position p lives at index p - 1.

Plan in plain words
  1. Read N and the N values into a[].
  2. Read Q. Repeat Q times: read p; if p < 1 or p > N print INVALID, else print a[p − 1].
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, q, p, i;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    scanf("%d", &q);
    for (i = 0; i < q; i++) {
        scanf("%d", &p);
        if (p < 1 || p > n)          /* check BEFORE touching the array */
            printf("INVALID\n");
        else
            printf("%d\n", a[p - 1]);   /* position p is index p-1 */
    }
    return 0;
}
Classic trap

Mixing up positions and indices: printing a[p] and checking p < n. Position 1 then gives the second value, and position N says INVALID. Test 3 asks for position 4 of 4, the exact boundary.

A+3 · Read a grid, print it column by column

Rung A+ 10 min · Pattern: R C then the grid · walk columns as the outer loop

Problem

Read R C (1 to 10 each), then an R × C grid row by row. Print the grid's columns as lines: line 1 is column 1 read top to bottom, line 2 is column 2, and so on (this is the transpose).

Input R C, then R rows of C integers.

Output C lines, each with R integers separated by spaces.

Test 1 · sample
2 3
1 2 3
4 5 6
1 4
2 5
3 6
Test 2
1 1
5
5
Test 3
1 4
7 8 9 10
7
8
9
10
Test 4
3 1
-1
-2
-3
-1 -2 -3
Test 5
3 3
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
Stuck? First move

Declare the largest grid allowed, int g[10][10];, and read it with the usual row-then-column loops. To print, swap which loop is outside: the outer loop runs over columns j (up to c), the inner over rows i (up to r), still printing g[i][j].

Plan in plain words
  1. Read R, C, then the grid row by row.
  2. For each column j: for each row i print g[i][j]; then a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int g[10][10];
    int r, c, i, j;

    scanf("%d %d", &r, &c);
    for (i = 0; i < r; i++)          /* read row by row, as the input arrives */
        for (j = 0; j < c; j++)
            scanf("%d", &g[i][j]);

    for (j = 0; j < c; j++) {        /* one output line per COLUMN */
        for (i = 0; i < r; i++)
            printf("%d ", g[i][j]);
        printf("\n");
    }
    return 0;
}
Classic trap

Swapping the loops but not their limits (j < r, i < c). On a square grid it still works, so it passes Tests 2 and 5 and fails Tests 1, 3 and 4. Always test a non-square grid and a single row.

Rung B · VPL level

15–20 minutes each, about 90 minutes in all. No arrays eval has been released yet, so these are built like the real loop evals (N, then N values, one short answer, 5 hidden-style tests): the format is modelled on the real evals; the difficulty is our estimate. Each one genuinely needs the array, because the answer depends on values you haven't read yet (the average, a later copy, the other end). Set a timer, write it from a blank file, and run all five tests before opening anything. The real evals themselves are on the real lab evals page.

B1 · Above the average

Rung B VPL format 15 min · Family: array, two passes · Pattern: sum in pass 1 · compare in pass 2 · no integer division

Problem

Read N (1 ≤ N ≤ 100) and then N integers (possibly negative). Print how many of them are strictly greater than the average of all N.

Input N, then N integers.

Output One integer.

Test 1 · sample
5
10 20 30 40 50
2
Test 2
1
7
0
Test 3
4
4 4 4 4
0
Test 4
2
-3 -2
1
Test 5
5
1 1 1 1 9
1
Stuck? First move

The average needs every value, and the comparison needs every value again afterwards: that is why this needs an array. Pass 1 reads and sums; pass 2 counts.

Plan in plain words
  1. Read N; read the values into a[] and add them to sum.
  2. For each i: if a[i] is above sum / N (exactly, not rounded), count it.
  3. Print the count.
Unpack this step: why a[i] * n > sum?

a[i] > sum / N with real division is the same as a[i] × N > sum: multiply both sides by N, which is positive, so the > stays. Multiplying keeps everything in whole numbers, so nothing is rounded. (a[i] > (double) sum / n also works.)

Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, sum = 0, count = 0;

    scanf("%d", &n);
    for (i = 0; i < n; i++) {        /* pass 1: store and sum */
        scanf("%d", &a[i]);
        sum = sum + a[i];
    }
    for (i = 0; i < n; i++)          /* pass 2: compare with the average */
        if (a[i] * n > sum)          /* a[i] > sum/n, without dividing */
            count++;
    printf("%d\n", count);
    return 0;
}
Classic trap

int avg = sum / n; then a[i] > avg. Integer division throws the fraction away, and for negatives C rounds towards zero: in Test 4 the average is −2.5, -5 / 2 is −2, and −2 > −2 is false, so the program prints 0 instead of 1. All the positive tests still pass, which is exactly how this bug costs 14 % without warning.

B2 · Values that appear exactly once

Rung B VPL format 15–20 min · Family: array, look at all others · Pattern: count each value across the whole array · NONE fallback

Problem

Read N (1 ≤ N ≤ 100) and then N integers. Print, in the order they were read, the values that appear exactly once in the input. If there are none, print NONE.

Input N, then N integers.

Output The values separated by spaces, or NONE.

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

Whether a value is unique depends on values both before and after it, so store everything first. Then, for each a[i], an inner loop over all j counts how many a[j] equal it. A count of exactly 1 (itself) means print it.

Plan in plain words
  1. Read N and the values.
  2. printed ← 0. For each i: count ← number of j (0 … N−1) with a[j] = a[i]. If count is 1, print a[i] and set printed ← 1.
  3. If printed is still 0, print NONE. Then a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, j, count, printed = 0;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (i = 0; i < n; i++) {
        count = 0;                   /* reset for every value */
        for (j = 0; j < n; j++)      /* look at ALL values, before and after */
            if (a[j] == a[i])
                count++;
        if (count == 1) {            /* only itself */
            printf("%d ", a[i]);
            printed = 1;
        }
    }
    if (printed == 0)
        printf("NONE");
    printf("\n");
    return 0;
}
Classic trap

Checking only the values before a[i] (j < i). That prints each distinct value once, which is a different question: on Test 1 it gives 4 5 6 7 instead of 5 7. "Exactly once" needs the whole array, which is why you stored it.

B3 · Is it a palindrome?

Rung B VPL format 15 min · Family: array, both ends at once · Pattern: compare a[i] with a[n - 1 - i] · flag

Problem

Read N (1 ≤ N ≤ 100) and then N integers. Print YES if the sequence reads the same forwards and backwards, otherwise NO.

Input N, then N integers.

Output YES or NO.

Test 1 · sample
5
1 2 3 2 1
YES
Test 2
4
1 2 2 1
YES
Test 3
1
42
YES
Test 4
4
5 5 5 4
NO
Test 5
3
-1 2 -1
YES
Stuck? First move

Pair the first with the last, the second with the second-last, and so on. Write the pairs for N = 5 on paper: index 0 with 4, 1 with 3. So i pairs with n - 1 - i, and you only need i up to the middle, i < n / 2.

Plan in plain words
  1. Read N and the values. ok ← 1.
  2. For i from 0 while i < N / 2: if a[i] ≠ a[N − 1 − i], ok ← 0.
  3. Print YES if ok is 1, else NO.
Unpack this step: why stop at n / 2?

Past the middle you would check the same pairs again from the other side. For odd N, the middle value pairs with itself: with N = 5, 5 / 2 is 2, so i = 0, 1 are checked and index 2 is left alone, which is correct.

Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, ok = 1;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (i = 0; i < n / 2; i++)          /* only up to the middle */
        if (a[i] != a[n - 1 - i])        /* partner of i is n-1-i */
            ok = 0;

    if (ok == 1)
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}
Classic trap

Writing the partner as a[n - i]. For i = 0 that is a[n], one past the end, so the first comparison is against garbage. It fails Tests 1, 2 and 5, with no error message. Check your partner formula on i = 0 before typing it.

B4 · The first value seen twice

Rung B VPL format 15–20 min · Family: array, look back · Pattern: for each j, search a[0..j−1] · stop at the first hit

Problem

Read N (1 ≤ N ≤ 100) and then N integers. Reading left to right, find the first value that has already appeared earlier. Print that value and its position at that moment (positions count from 1). If no value repeats, print NONE.

Input N, then N integers.

Output Two integers (value, position) separated by a space, or NONE.

Test 1 · sample
5
3 1 4 1 3
1 4
Test 2
4
1 2 3 4
NONE
Test 3
1
5
NONE
Test 4
2
7 7
7 2
Test 5
6
5 2 9 2 5 9
2 4
Stuck? First move

In the sample, 3 is the first value that occurs twice, but it isn't the answer: when you reach position 4 you see 1 again, and that happens before you see the second 3. So the outer loop walks j (the value you have just read), and the inner loop looks back at a[0] … a[j - 1].

Plan in plain words
  1. Read N and the values. found ← −1.
  2. For j = 1, 2, … while found is −1: for i = 0 to j − 1: if a[i] = a[j], found ← j.
  3. If found is −1, print NONE; else print a[found] and found + 1.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, j, found = -1;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (j = 1; j < n && found == -1; j++)   /* stop at the first hit */
        for (i = 0; i < j; i++)              /* look BACK only */
            if (a[i] == a[j])
                found = j;

    if (found == -1)
        printf("NONE\n");
    else
        printf("%d %d\n", a[found], found + 1);
    return 0;
}
Classic trap

Looping over i first and searching forwards for a later copy. That finds the first value that has a twin somewhere, which on Test 1 is 3 (answer 3 5), not 1 4. Read "first value that has already appeared" literally: the outer loop is the moment of reading.

B5 · The column with the largest sum

Rung B VPL format 15–20 min · Family: 2D array · Pattern: R C then grid · column walk · best-so-far that starts at the first column

Problem

Read R C (1 to 10 each), then an R × C grid of integers (possibly negative). Print the number of the column with the largest sum (columns count from 1; on a tie, the smallest column number) and that sum.

Input R C, then R rows of C integers.

Output Two integers separated by a space: column number, its sum.

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

A column sum walks down: the outer loop is over columns j (up to c), the inner over rows i (up to r). Column 1's sum is the first "best so far"; every later column replaces it only if strictly bigger.

Plan in plain words
  1. Read R, C, then the grid.
  2. For each column j: sum ← 0; add g[i][j] for every row i.
  3. If j is 0 or sum > bestSum: bestSum ← sum, best ← j.
  4. Print best + 1 and bestSum.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int g[10][10];
    int r, c, i, j, sum, best = 0, bestSum = 0;

    scanf("%d %d", &r, &c);
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &g[i][j]);

    for (j = 0; j < c; j++) {            /* one column at a time */
        sum = 0;
        for (i = 0; i < r; i++)          /* walk DOWN column j */
            sum = sum + g[i][j];
        if (j == 0 || sum > bestSum) {   /* column 1 is the first best */
            bestSum = sum;
            best = j;
        }
    }
    printf("%d %d\n", best + 1, bestSum);
    return 0;
}
Classic trap

Starting bestSum = 0 with no "first column" rule. When every column sum is negative (Tests 2 and 3), nothing beats 0 and the program prints 1 0: a sum that no column has. Also, >= instead of > picks the last tied column (Test 4).

Rung C · Beyond the eval (optional)

These are the old lab-sheet-plus-twist problems: longer than any eval we've seen. Do them after B, if time allows; they build fluency for the end-semester lab exam. C1–C5 are Lab Sheet 6 practice level (15–25 min each); C6–C9 are at the level of its challenge and bonus problems (25–40 min each) and need a hand trace on paper before typing.

C1 · Dice frequency and histogram

Rung C 15–20 min · Pattern: value as index · histogram · max over counts · Lab 6 §13 pattern

Problem

Read N (0 ≤ N ≤ 100) and then N die rolls. As each roll is read, a roll outside 1–6 prints INVALID and the roll, and is not counted. After all rolls, print six lines, one per face 1 to 6: the face, its count, then one * per occurrence written together with no spaces (nothing after the count when it is 0). Last line: the most frequent face (the smallest face on a tie), or NONE if there were no valid rolls.

Input N, then N integers.

Output Any INVALID x lines, then six histogram lines, then the most frequent face or NONE.

Test 1 · sample
10
3 6 2 6 9 1 6 3 0 3
INVALID 9
INVALID 0
1 1 *
2 1 *
3 3 ***
4 0
5 0
6 3 ***
3
Test 2
4
5 5 2 2
1 0
2 2 **
3 0
4 0
5 2 **
6 0
2
Test 3
2
7 0
INVALID 7
INVALID 0
1 0
2 0
3 0
4 0
5 0
6 0
NONE
Test 4
0
1 0
2 0
3 0
4 0
5 0
6 0
NONE
Test 5
1
6
1 0
2 0
3 0
4 0
5 0
6 1 *
6
Stuck? First move

You don't need to store the rolls at all, only their counts: int freq[7] = {0}; (size 7 so that freq[6] exists; index 0 is simply unused). Read each roll into a plain int roll, check it, and do freq[roll]++.

Plan in plain words
  1. Read N. Repeat N times: read roll; if outside 1..6 print INVALID and the roll, else freq[roll] ← freq[roll] + 1.
  2. mode ← 1. For face 1 to 6: print face, freq[face], then freq[face] stars; if freq[face] > freq[mode], mode ← face.
  3. If freq[mode] is 0, print NONE, else print mode.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int freq[7] = {0};          /* freq[1]..freq[6]; index 0 unused */
    int n, i, j, roll, mode;

    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        scanf("%d", &roll);
        if (roll < 1 || roll > 6)
            printf("INVALID %d\n", roll);
        else
            freq[roll]++;       /* the value IS the index */
    }

    mode = 1;
    for (i = 1; i <= 6; i++) {
        printf("%d %d ", i, freq[i]);
        for (j = 0; j < freq[i]; j++)
            printf("*");
        printf("\n");
        if (freq[i] > freq[mode])
            mode = i;
    }
    if (freq[mode] == 0)
        printf("NONE\n");
    else
        printf("%d\n", mode);
    return 0;
}
Classic trap

freq[roll]++ before checking the range. A roll of 9 writes to freq[9], past the end of the array: silent memory corruption, the same out-of-bounds bug as in A2.

C2 · Binary search that counts its probes

Rung C 20–25 min · Pattern: halve the range · sentinel loop · validate input · Lab 6 Problem 7, plus checks

Problem

Read N (1 ≤ N ≤ 100) and N values that should be in ascending order. If they aren't, print NOT SORTED and the first index whose value is smaller than the one before, and stop. Otherwise read targets until -1, and for each use binary search to print FOUND, the index and the number of probes, or NOT FOUND and the number of probes. A probe is one comparison with a[mid].

Input N, then N integers, then targets ending with -1.

Output NOT SORTED i, or one line per target: FOUND i k or NOT FOUND k.

Test 1 · sample
8
3 7 12 18 24 31 45 60
45 4 3 60 -1
FOUND 6 3
NOT FOUND 3
FOUND 0 3
FOUND 7 4
Test 2
1
10
10 11 -1
FOUND 0 1
NOT FOUND 1
Test 3
4
1 5 3 9
5 -1
NOT SORTED 2
Test 4
5
2 4 6 8 10
100 -1
NOT FOUND 3
Test 5
3
5 5 5
5 6 -1
FOUND 1 1
NOT FOUND 2
Stuck? First move

Do the two easy parts first: the sortedness check (compare neighbours, as in A3) and the outer "read target until −1" loop with nothing in it. Then the search needs three variables, lo = 0, hi = n - 1 and mid, and a loop while (lo <= hi).

Plan in plain words
  1. Read and check sortedness.
  2. Read target. While target ≠ −1:
  3. lo ← 0, hi ← N − 1, probes ← 0, found ← −1. While lo ≤ hi and nothing found: mid ← (lo + hi) / 2; probes + 1; if a[mid] = target, found ← mid; else if a[mid] < target, lo ← mid + 1; else hi ← mid − 1.
  4. Print the result; read the next target.
Unpack this step: why so few probes?

Each probe throws away half of what's left: 8 → 4 → 2 → 1. So 8 values need at most 4 probes, 100 values at most 7 (27 = 128 ≥ 100). A linear search could need 100.

Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, target, lo, hi, mid, probes, found;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (i = 1; i < n; i++) {
        if (a[i] < a[i - 1]) {
            printf("NOT SORTED %d\n", i);
            return 0;
        }
    }

    scanf("%d", &target);
    while (target != -1) {
        lo = 0;
        hi = n - 1;
        probes = 0;
        found = -1;
        while (lo <= hi && found == -1) {
            mid = (lo + hi) / 2;
            probes++;
            if (a[mid] == target)
                found = mid;
            else if (a[mid] < target)
                lo = mid + 1;       /* target is in the right half */
            else
                hi = mid - 1;       /* target is in the left half */
        }
        if (found == -1)
            printf("NOT FOUND %d\n", probes);
        else
            printf("FOUND %d %d\n", found, probes);
        scanf("%d", &target);
    }
    return 0;
}
Classic trap

lo = mid instead of lo = mid + 1. When lo and hi are neighbours, mid equals lo, nothing changes, and the loop runs forever (VPL reports a timeout). a[mid] has already been checked, so always step past it.

C3 · Bubble sort that stops early

Rung C 20 min · Pattern: nested loop · swap · flag · Lab 6 Problem 8, plus the early exit

Problem

Read N (1 ≤ N ≤ 100) and N integers. Sort them ascending with bubble sort. After every pass, print PASS, the pass number and the array. If a pass makes no swaps, print EARLY STOP and that pass number, and stop sorting. Finally print SORTED and the sorted array.

Input N, then N integers.

Output One line per pass, possibly an EARLY STOP k line, then the SORTED line.

Test 1 · sample
5
5 1 4 2 8
PASS 1 1 4 2 5 8
PASS 2 1 2 4 5 8
PASS 3 1 2 4 5 8
EARLY STOP 3
SORTED 1 2 4 5 8
Test 2
5
1 2 4 3 5
PASS 1 1 2 3 4 5
PASS 2 1 2 3 4 5
EARLY STOP 2
SORTED 1 2 3 4 5
Test 3
1
9
SORTED 9
Test 4
3
3 2 1
PASS 1 2 1 3
PASS 2 1 2 3
SORTED 1 2 3
Test 5
3
1 2 3
PASS 1 1 2 3
EARLY STOP 1
SORTED 1 2 3
Stuck? First move

Write the plain bubble sort first: outer loop for (pass = 1; pass < n; pass++), inner loop comparing a[i] with a[i + 1] and swapping if they're out of order. Then add one variable, swapped, set to 0 at the start of each pass and to 1 by any swap.

Plan in plain words
  1. For pass = 1 to N − 1: swapped ← 0.
  2. For i = 0 to N − pass − 1: if a[i] > a[i + 1], swap them, swapped ← 1.
  3. Print the pass line. If swapped is still 0: print EARLY STOP and leave the loop (break).
  4. Print the SORTED line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, pass, temp, swapped;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (pass = 1; pass < n; pass++) {
        swapped = 0;
        for (i = 0; i < n - pass; i++) {    /* the last pass-1 are already in place */
            if (a[i] > a[i + 1]) {
                temp = a[i];
                a[i] = a[i + 1];
                a[i + 1] = temp;
                swapped = 1;
            }
        }
        printf("PASS %d", pass);
        for (i = 0; i < n; i++)
            printf(" %d", a[i]);
        printf("\n");
        if (swapped == 0) {
            printf("EARLY STOP %d\n", pass);
            break;
        }
    }
    printf("SORTED");
    for (i = 0; i < n; i++)
        printf(" %d", a[i]);
    printf("\n");
    return 0;
}
Classic trap

Inner loop i < n instead of i < n - pass. On the last i, a[i + 1] is a[n], one past the end, and garbage gets swapped into your data.

C4 · Shop sales: row totals and column totals

Rung C 20 min · Pattern: walk rows · walk columns · track the best · Lab 6 §15

Problem

Read S D (shops and days, 1 to 10 each), then a sales table of non-negative integers with one row per shop and one column per day. Print every shop's total on line 1, every day's total on line 2, and on line 3 the best shop's number (shops count from 1; the first one on a tie) and its total.

Input S D, then S rows of D integers.

Output Line 1: S shop totals. Line 2: D day totals. Line 3: best shop, its total.

Test 1 · sample
3 4
10 20 30 40
5 5 5 5
50 0 0 0
100 20 50
65 25 35 45
1 100
Test 2
1 1
7
7
7
1 7
Test 3
2 2
3 4
4 3
7 7
7 7
1 7
Test 4
2 3
0 0 0
0 0 0
0 0
0 0 0
1 0
Test 5
2 5
1 2 3 4 5
9 9 9 9 9
15 45
10 11 12 13 14
2 45
Stuck? First move

Shop totals = add along each row: outer loop over i (shops), inner over j (days). Day totals = add down each column: the same two loops with the outer and inner swapped, still reading s[i][j].

Plan in plain words
  1. Read the sizes and the table.
  2. For each shop i: total ← sum of s[i][0..D−1]; print it; if it beats bestTotal, remember i and the total.
  3. Newline. For each day j: total ← sum of s[0..S−1][j]; print it.
  4. Newline. Print best + 1 and bestTotal.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int s[10][10];
    int shops, days, i, j, total, best, bestTotal;

    scanf("%d %d", &shops, &days);
    for (i = 0; i < shops; i++)
        for (j = 0; j < days; j++)
            scanf("%d", &s[i][j]);

    best = 0;
    bestTotal = -1;                         /* sales are never negative */
    for (i = 0; i < shops; i++) {           /* walk along row i */
        total = 0;
        for (j = 0; j < days; j++)
            total = total + s[i][j];
        printf("%d ", total);
        if (total > bestTotal) {
            bestTotal = total;
            best = i;
        }
    }
    printf("\n");
    for (j = 0; j < days; j++) {            /* walk down column j */
        total = 0;
        for (i = 0; i < shops; i++)
            total = total + s[i][j];
        printf("%d ", total);
    }
    printf("\n%d %d\n", best + 1, bestTotal);
    return 0;
}
Classic trap

Swapping the loops but forgetting to swap the limits: for (j = 0; j < shops; j++). On a square table it still works, so the bug only shows on rectangular input, which is why Tests 1 and 5 are not square.

C5 · Rotate a matrix 90° clockwise

Rung C 20–25 min · Pattern: read the matrix in a different order · builds on Lab 6 Problem 11 (transpose)

Problem

Read an R × C matrix (1 to 10 each) and print it rotated 90° clockwise: the result has C rows and R columns. No second matrix is needed.

Input R C, then R rows of C integers.

Output C lines, each with R integers separated by spaces.

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

Write the 2 × 3 example on paper and label every element with its [i][j]. The rotated first row is 4 1, which is m[1][0] then m[0][0]: column 0, read from the bottom up. So the outer loop is over columns j, and the inner loop runs i downwards from r - 1. (It is A+3 with the inner loop reversed.)

Plan in plain words
  1. Read the matrix.
  2. For each column j from 0 to C − 1: for i from R − 1 down to 0, print m[i][j]. Then a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int m[10][10];
    int r, c, i, j;

    scanf("%d %d", &r, &c);
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &m[i][j]);

    /* rotated has c rows and r columns.
       Its row j is column j of m, read from the bottom up. */
    for (j = 0; j < c; j++) {
        for (i = r - 1; i >= 0; i--)
            printf("%d ", m[i][j]);
        printf("\n");
    }
    return 0;
}
Classic trap

Reading the column top-down (i from 0 up). That prints the transpose, not the rotation: right on Tests 2 and 5, wrong on the other three.

C6 · Second largest in one pass

Rung C 25–30 min · Pattern: two trackers · duplicates · "does it exist?" flag · Lab 6's challenge asks this after sorting; here sorting isn't allowed

Problem

Read N (1 ≤ N ≤ 100) and N integers (possibly negative, possibly repeated). In a single pass, with no sorting and no second array, find the largest value and the second-largest distinct value. Print the largest, then the second largest, or NONE if every value is equal.

Input N, then N integers.

Output Two items separated by a space: the largest, then the second largest or NONE.

Test 1 · sample
7
75 92 84 92 68 75 88
92 88
Test 2
4
50 50 50 50
50 NONE
Test 3
3
-1 -5 -3
-1 -3
Test 4
3
10 9 10
10 9
Test 5
1
42
42 NONE
Stuck? First move

Keep two variables, first and second, plus a flag hasSecond = 0, because at the start there may be no second largest at all and no number can safely mean "nothing yet". Start first = a[0] and loop from i = 1. Each new value falls into one of three cases: bigger than first, equal to it, or smaller.

Plan in plain words
  1. first ← a[0]; hasSecond ← 0.
  2. For each later value v: if v > first, the old first becomes second (hasSecond ← 1) and first ← v.
  3. Else if v < first and (there is no second yet, or v > second): second ← v, hasSecond ← 1.
  4. If v equals first, do nothing: it's a duplicate of the max.
  5. Print first, then second or NONE.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int a[100];
    int n, i, first, second, hasSecond = 0;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    first = a[0];
    second = 0;                  /* meaningless until hasSecond is 1 */
    for (i = 1; i < n; i++) {
        if (a[i] > first) {
            second = first;      /* old champion drops to second */
            first = a[i];
            hasSecond = 1;
        } else if (a[i] < first && (hasSecond == 0 || a[i] > second)) {
            second = a[i];
            hasSecond = 1;
        }
        /* a[i] == first: a duplicate of the max, ignore it */
    }

    if (hasSecond)
        printf("%d %d\n", first, second);
    else
        printf("%d NONE\n", first);
    return 0;
}
Classic trap

Starting second = 0 and using it as "nothing yet", with no flag. For Test 3, -1 -5 -3, the answer is −3, but −5 and −3 are both less than 0, so second is never replaced. We compiled that version: it prints -1 0, a number that isn't in the input. The flag avoids guessing a "small enough" starting number.

C7 · Merge two sorted arrays

Rung C 25–35 min · Pattern: two pointers · leftovers · arrays into functions

Problem

Read array A (size 0 to 50, ascending) and array B (size 0 to 50, ascending). Produce one ascending array containing all values of both, in one pass over each (don't sort the result). Print its size on line 1, its values on line 2, and on line 3 how many elements of A also appear in B. Write readArray(int a[], int n) and printArray(int a[], int n) functions.

Input Size of A, then A's values, then size of B, then B's values.

Output Line 1: merged size. Line 2: merged values (empty if both arrays are empty). Line 3: the count.

Test 1 · sample
4
1 3 5 7
3
3 4 7
7
1 3 3 4 5 7 7
2
Test 2
0
3
2 2 9
3
2 2 9
0
Test 3
3
2 2 8
2
2 10
5
2 2 2 8 10
2
Test 4
0
0
0

0
Test 5
2
-5 6
0
2
-5 6
0
Stuck? First move

Use three indices: i for the next unused value in A, j for B, k for the next free slot in the merged array m[100]. At every step compare a[i] with b[j], copy the smaller into m[k], and advance that array's index and k.

Plan in plain words
  1. Read both arrays through readArray.
  2. While both A and B have values left: if a[i] ≤ b[j], copy a[i] (counting it if it equals b[j]) and advance i; else copy b[j] and advance j. Advance k either way.
  3. Copy whatever is left of A, then whatever is left of B (one of these loops does nothing).
  4. Print k, the merged array through printArray, then the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

void readArray(int a[], int n) {
    int i;
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
}

void printArray(int a[], int n) {
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
}

int main(void) {
    int a[50], b[50], m[100];
    int n1, n2, i = 0, j = 0, k = 0, common = 0;

    scanf("%d", &n1);
    readArray(a, n1);
    scanf("%d", &n2);
    readArray(b, n2);

    /* i walks A, j walks B, k is the next free slot in m */
    while (i < n1 && j < n2) {          /* both still have values */
        if (a[i] <= b[j]) {
            if (a[i] == b[j])
                common++;               /* a value that is in both */
            m[k] = a[i];
            i++;
        } else {
            m[k] = b[j];
            j++;
        }
        k++;
    }
    while (i < n1) {                    /* leftovers of A */
        m[k] = a[i];
        i++;
        k++;
    }
    while (j < n2) {                    /* leftovers of B */
        m[k] = b[j];
        j++;
        k++;
    }

    printf("%d\n", k);
    printArray(m, k);
    printf("%d\n", common);
    return 0;
}

Notice that readArray fills the caller's a and b. An array argument is not copied the way an int is (pass-by-value from Stage 2), so changes made inside the function stay. With a size of 0, readArray reads nothing and the next number in the input is B's size, which is what Tests 2 and 4 check.

Classic trap · sizeof inside a function

Tempted to drop the n parameter and compute the size inside the function with sizeof(a) / sizeof(a[0])? Inside a function, the parameter a is only the array's starting address, so sizeof measures that address, not the array:

#include <stdio.h>

void show(int a[]) {
    printf("inside show: sizeof(a) = %zu\n", sizeof(a));
}

int main(void) {
    int a[10];
    printf("in main:     sizeof(a) = %zu\n", sizeof(a));
    printf("in main:     count = %zu\n", sizeof(a) / sizeof(a[0]));
    show(a);
    return 0;
}

clang warns (sizeof on array function parameter will return size of 'int *' instead of 'int[]'), and the real run shows 40 bytes in main but 8 inside the function:

in main:     sizeof(a) = 40
in main:     count = 10
inside show: sizeof(a) = 8

So inside the function the "count" would be 8 / 4 = 2, whatever the array's real size. Always pass the count as a parameter. (Also, sizeof gives the declared size, 50, not the n you read, even in main.)

C8 · Spiral print of a matrix

Rung C 30–40 min · Pattern: four shrinking boundaries · single-row/column edge cases

Problem

Read an R × C matrix (1 to 10 each) and print its elements on one line in clockwise spiral order, starting at the top-left: along the top row, down the right column, back along the bottom row, up the left column, then the same again one layer further in. It must work for any shape, including a single row or single column.

Input R C, then R rows of C integers.

Output All R × C values on one line, separated by spaces.

Test 1 · sample
3 4
1 2 3 4
5 6 7 8
9 10 11 12
1 2 3 4 8 12 11 10 9 5 6 7
Test 2
1 4
1 2 3 4
1 2 3 4
Test 3
4 1
1
2
3
4
1 2 3 4
Test 4
3 3
1 2 3
4 5 6
7 8 9
1 2 3 6 9 8 7 4 5
Test 5
1 1
7
7
Stuck? First move

Keep four variables for the part not yet printed: top = 0, bottom = r - 1, left = 0, right = c - 1. Each side printed removes one boundary: after the top row, top++; after the right column, right--; and so on. The outer loop runs while top <= bottom && left <= right.

Plan in plain words
  1. Top row: j from left to right, print m[top][j]; then top + 1.
  2. Right column: i from top to bottom, print m[i][right]; then right − 1.
  3. If a row is still left (top ≤ bottom): bottom row from right down to left; bottom − 1.
  4. If a column is still left (left ≤ right): left column from bottom up to top; left + 1.
  5. Repeat while top ≤ bottom and left ≤ right.
Unpack this step: why the two extra ifs?

For a single row (1 × 4), after the top row top becomes 1 > bottom = 0. Without the check, the "bottom row" loop would print row 0 again, backwards: 1 2 3 4 3 2 1. The checks stop a side from being printed twice.

Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

int main(void) {
    int m[10][10];
    int r, c, i, j;
    int top, bottom, left, right;

    scanf("%d %d", &r, &c);
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &m[i][j]);

    top = 0; bottom = r - 1; left = 0; right = c - 1;
    while (top <= bottom && left <= right) {
        for (j = left; j <= right; j++)         /* top row, left to right */
            printf("%d ", m[top][j]);
        top++;
        for (i = top; i <= bottom; i++)         /* right column, downwards */
            printf("%d ", m[i][right]);
        right--;
        if (top <= bottom) {                    /* a bottom row still exists */
            for (j = right; j >= left; j--)
                printf("%d ", m[bottom][j]);
            bottom--;
        }
        if (left <= right) {                    /* a left column still exists */
            for (i = bottom; i >= top; i--)
                printf("%d ", m[i][left]);
            left++;
        }
    }
    printf("\n");
    return 0;
}
Classic trap

Testing only on square matrices. A spiral that works on 3 × 3 often repeats elements on 1 × 4 or 3 × 4. Before you call a 2D program finished, run it on one non-square input and one single row: Tests 1–3 do exactly that.

C9 · Fibonacci numbers too big for long long

Rung C 35–40 min · Pattern: digits in an array · addition with carry · arrays into functions · same digit-array idea as the 2025 mid-sem "account number + 1" (worked here)

Problem

The Fibonacci numbers are F(1) = F(2) = 1 and F(n) = F(n−1) + F(n−2). F(93) is already too big for a long long. Read n. If 1 ≤ n ≤ 300, print F(n) exactly on line 1 and its number of digits on line 2; otherwise print INVALID. Store each big number as an array of digits and write a function that adds two such numbers with carry.

Input One integer n.

Output F(n), then its digit count, on two lines; or INVALID.

Test 1 · sample
10
55
2
Test 2
1
1
1
Test 3
100
354224848179261915075
21
Test 4
300
222232244629420445529739893461909967206666939096499764990979600
63
Test 5
301
INVALID
Stuck? First move

Store digits back to front: d[0] is the units digit, d[1] the tens, and so on, plus a count of digits. Then column addition walks forward from index 0, and a final carry just goes into the next index. Write int addBig(int a[], int na, int b[], int nb, int c[]) that returns the number of digits in c, and test it on 55 + 89 before anything else.

Plan in plain words
  1. addBig: carry ← 0. For each digit position i up to the longer length: sum ← carry + (a's digit i if it exists) + (b's digit i if it exists); c[i] ← sum % 10; carry ← sum / 10. If a carry remains, it becomes one more digit.
  2. main: prev ← 1, cur ← 1 (one digit each). Repeat for step 3 to n: next ← prev + cur; prev ← cur; cur ← next (copying digits with a small copy function).
  3. Print cur's digits from the last index down to 0, then the count.
Unpack this step: the carry

It is column addition from school: 8 + 7 = 15, write 5, carry 1 into the next column. In code: c[i] = sum % 10 keeps the 5 and carry = sum / 10 passes on the 1. A digit sum is at most 9 + 9 + 1 = 19, so the carry is always 0 or 1.

Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>

#define MAXD 100        /* F(300) has 63 digits, so 100 is plenty */

/* c = a + b. Digits are stored LAST digit first: d[0] is the units digit.
   Returns the number of digits in c. */
int addBig(int a[], int na, int b[], int nb, int c[]) {
    int i, carry = 0, sum, n;
    if (na > nb)
        n = na;
    else
        n = nb;
    for (i = 0; i < n; i++) {
        sum = carry;
        if (i < na)
            sum = sum + a[i];
        if (i < nb)
            sum = sum + b[i];
        c[i] = sum % 10;
        carry = sum / 10;
    }
    if (carry > 0) {
        c[n] = carry;
        n++;
    }
    return n;
}

void copyBig(int from[], int to[], int n) {
    int i;
    for (i = 0; i < n; i++)
        to[i] = from[i];
}

int main(void) {
    int prev[MAXD], cur[MAXD], next[MAXD];
    int nPrev = 1, nCur = 1, nNext, n, step, i;

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

    prev[0] = 1;            /* F(1) = 1 */
    cur[0] = 1;             /* F(2) = 1 */
    for (step = 3; step <= n; step++) {
        nNext = addBig(prev, nPrev, cur, nCur, next);
        copyBig(cur, prev, nCur);       /* shift along: prev = cur */
        nPrev = nCur;
        copyBig(next, cur, nNext);      /* cur = next */
        nCur = nNext;
    }

    for (i = nCur - 1; i >= 0; i--)     /* print from the front digit */
        printf("%d", cur[i]);
    printf("\n%d\n", nCur);
    return 0;
}

F(100) and F(300) in the tests were cross-checked against Python's exact integers.

Classic trap

Storing digits front to back (d[0] = the leading digit). Then the two numbers' units digits sit at different indices whenever their lengths differ, and a final carry needs every digit shifted right. Back to front makes both problems disappear; reverse only when printing. And printf("%d ", cur[i]) with a space would split the number into 63 separate tokens: VPL would mark it wrong.

Self-test before moving on

Ready for Stage 4 when…
  1. You can write A+1 and A+3 from a blank file in under 10 minutes each, including the N = 0 guard and a non-square grid.
  2. You can write B1, B4 and B5 from a blank file in under 20 minutes each, without opening a hint, and each passes all 5 tests (including the negative-average, look-back and all-negative ones) on the first full run.
  3. Your programs print nothing but the answer: no prompt, no debug line.
  4. Without looking, you can say why i <= n, a[n - i] and sizeof inside a function are all bugs.
  5. Optional: C6 or C8 in under 35 minutes after reading only "Stuck? First move".

Stage 4 is strings, which are arrays of characters: everything on this page carries over directly.

Practising with an AI? Ask it well

"Here is my C program for this array problem: [paste problem + code]. Don't fix it. List three inputs (including N = 1, N = 0 if allowed, and duplicates) that you think could break it, and I'll run them myself."

"Give me one new lab-evaluation-style array problem: input is N then N integers, no prompts, output one number or one uppercase word, solvable in 5–15 lines. Give the statement and five test cases only." Check its test outputs by running your own solution: AI-written expected outputs are sometimes wrong.