These are the notes for C Coding Questions, episode 19, placement practice for people who finished the SyntaxPilot C course. Matrix questions: add and multiply two matrices (and know when you can't), transpose a matrix, and print a matrix in spiral order. Plus the trap every matrix question hides: passing a 2D array to a function.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was compiled with gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, Linux x86-64, 32-bit int), the SyntaxPilot compiler's C command with warnings on, and every output below is real. In the input lines below, ⏎ means pressing Enter (each line of a matrix is typed on its own line).
Real-life pictures
| In real life | In C |
|---|---|
| a cinema ticket: seat D7 is row D, seat 7 | a matrix a[i][j]: row i, column j |
| a chai-stall bill: cups × price of chai + samosas × price of a samosa | matrix multiplication: row times column, added up |
| a marks register (a row per student) turned sideways (a row per subject) | transpose: t[j][i] = a[i][j] |
| a guard's rounds of a parking lot: the outer ring, then the next ring inside | spiral order: four walls that close in |
The idea: a matrix is a 2D array
A matrix is a grid of numbers with rows (going across) and columns (going down). An r × c matrix (say "r by c") has r rows and c columns; these two numbers are its dimensions or size. A matrix with as many rows as columns (n × n) is square.
In C a matrix is a two-dimensional (2D) array: int a[3][4] has 3 rows of 4 ints. a[i][j] is the element in row i, column j, both counted from 0.
#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("a[0][2] = %d, a[1][0] = %d\n", a[0][2], a[1][0]);
for (int i = 0; i < 2; i++) { /* i picks the row */
for (int j = 0; j < 3; j++) /* j picks the column */
printf("%4d", a[i][j]);
printf("\n");
}
return 0;
}
Output:
a[0][2] = 3, a[1][0] = 4
1 2 3
4 5 6
The questions read sizes at run time, so the programs keep every matrix in a 10 × 10 box (int a[10][10]) and use only its top-left r × c corner. %5d prints a number right-aligned in 5 characters so the columns line up.
Q1: Add and multiply two matrices
Problem. Read r1 c1 and matrix A, then r2 c2 and matrix B. Print A + B and A × B, or "not possible".
Think out loud.
- Input: two sizes and two matrices, repeated for several tests. Output: the sum and the product.
- A =
1 2 / 3 4, B =5 6 / 7 8→ A + B =6 8 / 10 12, A × B =19 22 / 43 50. - Edge cases: sizes that don't fit together, matrices that aren't square, the same arrays reused for the next test.
Addition adds the numbers in the same seat: s[i][j] = a[i][j] + b[i][j]. It needs the same size.
read_matrix fills r rows and c columns with scanf; the parameter int m[10][10] means "rows of 10 ints", matching our 10 × 10 boxes.
The obvious attempt: multiply seat by seat
#include <stdio.h>
void read_matrix(int m[10][10], int r, int c) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &m[i][j]);
}
int main() {
int a[10][10] = {0}, b[10][10] = {0};
int r1, c1, r2, c2;
while (scanf("%d %d", &r1, &c1) == 2) {
read_matrix(a, r1, c1);
scanf("%d %d", &r2, &c2);
read_matrix(b, r2, c2);
printf("A x B:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++)
printf("%5d", a[i][j] * b[i][j]);
printf("\n");
}
}
return 0;
}
Input 2 2⏎ 1 2⏎ 3 4⏎ 2 2⏎ 5 6⏎ 7 8⏎:
Output:
A x B:
5 12
21 32
We wanted 19 22 / 43 50. Every number is wrong.
Why. Matrix multiplication is not seat by seat. The element in row i, column j of the product is row i of A times column j of B: multiply the pairs and add them up. For row 0, column 0: row 0 of A is 1 2, column 0 of B is 5 7, so 1×5 + 2×7 = 19.
Multiplying two lists pair by pair and adding is called a dot product:
p[i][j] = a[i][0]*b[0][j] + a[i][1]*b[1][j] + ... = sum over k of a[i][k] * b[k][j]
This works only if a row of A and a column of B have the same length: the columns of A must equal the rows of B, c1 == r2. The product of an r1 × c1 and a c1 × c2 matrix is r1 × c2 (a 2 × 3 times a 3 × 2 is 2 × 2).
Fix one: row times column (three loops)
i picks the row, j the column, and k walks along both, adding into sum, which starts at 0 for every seat.
#include <stdio.h>
void read_matrix(int m[10][10], int r, int c) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &m[i][j]);
}
int main() {
int a[10][10] = {0}, b[10][10] = {0};
int r1, c1, r2, c2;
while (scanf("%d %d", &r1, &c1) == 2) {
read_matrix(a, r1, c1);
scanf("%d %d", &r2, &c2);
read_matrix(b, r2, c2);
printf("A x B:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
int sum = 0;
for (int k = 0; k < c1; k++)
sum += a[i][k] * b[k][j];
printf("%5d", sum);
}
printf("\n");
}
}
return 0;
}
Input 2 2⏎ 1 2⏎ 3 4⏎ 2 2⏎ 5 6⏎ 7 8⏎ 2 3⏎ 1 2 3⏎ 4 5 6⏎ 3 2⏎ 7 8⏎ 9 10⏎ 11 12⏎ 2 3⏎ 1 2 3⏎ 4 5 6⏎ 2 3⏎ 1 1 1⏎ 2 2 2⏎:
Output:
A x B:
19 22
43 50
A x B:
58 64
139 154
A x B:
38 41 5
80 86 14
The first two products are right. The third test printed an answer for a product that doesn't exist: 2 × 3 times 2 × 3. k went up to 2, and row 2 of B was never typed in that test: it still held 11 12 0 from the previous test (b[2][0] = 11, b[2][1] = 12). So 1×1 + 2×2 + 3×11 = 38. A wrong answer with no error at all.
The fix: check the sizes first
#include <stdio.h>
void read_matrix(int m[10][10], int r, int c) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &m[i][j]);
}
int main() {
int a[10][10], b[10][10];
int r1, c1, r2, c2;
while (scanf("%d %d", &r1, &c1) == 2) {
read_matrix(a, r1, c1);
scanf("%d %d", &r2, &c2);
read_matrix(b, r2, c2);
printf("A + B:");
if (r1 != r2 || c1 != c2) printf(" not possible\n");
else for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++)
printf("%5d", a[i][j] + b[i][j]);
printf(i == r1 - 1 ? "\n" : "\n ");
}
printf("A x B:");
if (c1 != r2) printf(" not possible (%d columns, %d rows)\n", c1, r2);
else for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
int sum = 0;
for (int k = 0; k < c1; k++)
sum += a[i][k] * b[k][j];
printf("%5d", sum);
}
printf(i == r1 - 1 ? "\n" : "\n ");
}
}
return 0;
}
Input 2 2⏎ 1 2⏎ 3 4⏎ 2 2⏎ 5 6⏎ 7 8⏎ 2 3⏎ 1 2 3⏎ 4 5 6⏎ 3 2⏎ 7 8⏎ 9 10⏎ 11 12⏎ 2 3⏎ 1 2 3⏎ 4 5 6⏎ 2 3⏎ 1 1 1⏎ 2 2 2⏎:
Output:
A + B: 6 8
10 12
A x B: 19 22
43 50
A + B: not possible
A x B: 58 64
139 154
A + B: 2 3 4
6 7 8
A x B: not possible (3 columns, 2 rows)
printf(i == r1 - 1 ? "\n" : "\n ") ends the last row with a newline and every other row with a newline plus 6 spaces, so the next row starts under the first number ("A + B:" is 6 characters). Every test passes. (A real program would also check that r and c are between 1 and 10 before reading, so a bad size can't write outside the 10 × 10 box; see practice question 4.)
Complexity.
- Addition: one visit per seat, O(r × c) time.
- Multiplication:
r1 × c2seats,c1steps each: O(r1 × c1 × c2); for two n × n matrices O(n³). n = 100 → 1,000,000 multiply-adds. - Space: O(1) extra (we print each value as we make it). Storing the product would need O(r1 × c2).
Big O describes how the work grows with the input size, ignoring constant factors: O(n³) means doubling n makes it about 8 times slower.
The column-size trap: passing a matrix to a function
In memory a 2D array is one long line: row 0, then row 1, then row 2 (this is called row-major order). To find m[i][j], C computes "skip i whole rows, then j more", so it must know the row length, the column size. That's why a matrix parameter must state it: int m[10][10] (or int m[][10]) means rows of 10 ints.
Pass a matrix whose rows have a different length, and C skips the wrong amount:
#include <stdio.h>
void print_matrix(int m[10][10], int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf("%4d", m[i][j]);
printf("\n");
}
}
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print_matrix(a, 3, 3);
return 0;
}
Compiler output:
main.c: In function ‘main’:
main.c:13:18: warning: passing argument 1 of ‘print_matrix’ from incompatible pointer type [-Wincompatible-pointer-types]
13 | print_matrix(a, 3, 3);
| ^
| |
| int (*)[3]
main.c:3:23: note: expected ‘int (*)[10]’ but argument is of type ‘int (*)[3]’
3 | void print_matrix(int m[10][10], int r, int c) {
| ~~~~^~~~~~~~~
main.c:13:5: warning: ‘print_matrix’ accessing 400 bytes in a region of size 36 [-Wstringop-overflow=]
13 | print_matrix(a, 3, 3);
| ^~~~~~~~~~~~~~~~~~~~~
main.c:13:5: note: referencing argument 1 of type ‘int[10][10]’
main.c:3:6: note: in a call to function ‘print_matrix’
3 | void print_matrix(int m[10][10], int r, int c) {
| ^~~~~~~~~~~~
Output:
1 2 3
1216257792-1645581920-1490127136
-1952014272 1-1952010080
Row 0 is right; after that it reads memory outside a (it jumps 10 ints for row 1, but a has only 9 ints in all). That is undefined behaviour (UB): the standard makes no promise, so the garbage differs from run to run, and the program could crash. The warning says exactly what's wrong: int (*)[3] (a pointer to rows of 3) is not int (*)[10] (a pointer to rows of 10). Newer gcc (14 and later) makes this an error.
Fix one: the same column size everywhere.
#include <stdio.h>
void print_matrix(int m[10][10], int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf("%4d", m[i][j]);
printf("\n");
}
}
int main() {
int a[10][10] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print_matrix(a, 3, 3);
return 0;
}
Output:
1 2 3
4 5 6
7 8 9
Fix two: a variable length array (VLA) parameter: pass the sizes first and use them in the parameter's type. Standard since C99 (optional in C11, supported by gcc and clang).
#include <stdio.h>
void print_matrix(int r, int c, int m[r][c]) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf("%4d", m[i][j]);
printf("\n");
}
}
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[2][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
print_matrix(3, 3, a);
print_matrix(2, 4, b);
return 0;
}
Output:
1 2 3
4 5 6
7 8 9
1 2 3 4
5 6 7 8
Q2: Transpose a matrix
Problem. The transpose of a matrix turns every row into a column: the element at row i, column j moves to row j, column i. For a square n × n matrix, do it in place (inside the same array, with no second matrix).
Think out loud.
1 2 3 / 4 5 6 / 7 8 9→1 4 7 / 2 5 8 / 3 6 9. The first row becomes the first column.- Edge cases: a 1 × 1 matrix; a matrix that isn't square (its shape changes: r × c becomes c × r).
The obvious attempt: swap a[i][j] and a[j][i] for every i and j
#include <stdio.h>
int main() {
int n, a[10][10];
while (scanf("%d", &n) == 1) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
int t = a[i][j];
a[i][j] = a[j][i];
a[j][i] = t;
}
printf("transpose:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%4d", a[i][j]);
printf("\n");
}
}
return 0;
}
Input 3⏎ 1 2 3⏎ 4 5 6⏎ 7 8 9⏎ 1⏎ 42⏎:
Output:
transpose:
1 2 3
4 5 6
7 8 9
transpose:
42
Unchanged! Why: at i = 0, j = 1 we swap a[0][1] and a[1][0] (the 2 and the 4 trade places). Later, at i = 1, j = 0, we swap the same two seats again, and they trade back. Every pair is swapped twice.
The fix: only above the diagonal
The main diagonal is the line of seats where i == j (top left to bottom right); those never move. Visit only the seats above it, where j > i, so each pair is swapped exactly once: j starts at i + 1.
#include <stdio.h>
int main() {
int n, a[10][10];
while (scanf("%d", &n) == 1) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
int t = a[i][j];
a[i][j] = a[j][i];
a[j][i] = t;
}
printf("transpose:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%4d", a[i][j]);
printf("\n");
}
}
return 0;
}
Input 3⏎ 1 2 3⏎ 4 5 6⏎ 7 8 9⏎ 1⏎ 42⏎:
Output:
transpose:
1 4 7
2 5 8
3 6 9
transpose:
42
Complexity: n(n − 1)/2 swaps → O(n²) time, O(1) space (one temporary t).
A matrix that isn't square: a new matrix
A 2 × 3 becomes a 3 × 2: a different shape, so it can't stay in the same seats. Write into a second matrix, t[j][i] = a[i][j], and print it with c rows and r columns.
#include <stdio.h>
int main() {
int r, c, a[10][10], t[10][10];
while (scanf("%d %d", &r, &c) == 2) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &a[i][j]);
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
t[j][i] = a[i][j];
printf("%d x %d becomes %d x %d:\n", r, c, c, r);
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++)
printf("%4d", t[i][j]);
printf("\n");
}
}
return 0;
}
Input 2 3⏎ 1 2 3⏎ 4 5 6⏎ 1 4⏎ 7 8 9 10⏎:
Output:
2 x 3 becomes 3 x 2:
1 4
2 5
3 6
1 x 4 becomes 4 x 1:
7
8
9
10
Complexity: O(r × c) time, O(r × c) space for t.
Q3: Print a matrix in spiral order
Problem. Start at the top-left, go right along the top row, down the right column, left along the bottom row, up the left column, then do the same for the next ring inside, until every element is printed exactly once.
Think out loud.
1 2 3 / 4 5 6 / 7 8 9→1 2 3 6 9 8 7 4 5.3 × 4with 1..12 →1 2 3 4 8 12 11 10 9 5 6 7.- Edge cases: not square (3 × 4), a single row, a single column. Every number exactly once.
The plan: four walls. A boundary is the edge of the part still left to print. Keep four of them: top = 0, bottom = r − 1, left = 0, right = c − 1. Each round:
- top row,
left → right, thentop++; - right column,
top → bottom, thenright--; - bottom row,
right → left, thenbottom--; - left column,
bottom → top, thenleft++;
and repeat while top <= bottom && left <= right.
The obvious attempt: the four steps exactly as planned
#include <stdio.h>
int main() {
int r, c, a[10][10];
while (scanf("%d %d", &r, &c) == 2) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &a[i][j]);
int top = 0, bottom = r - 1, left = 0, right = c - 1;
printf("%d x %d:", r, c);
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) printf(" %d", a[top][j]);
top++;
for (int i = top; i <= bottom; i++) printf(" %d", a[i][right]);
right--;
for (int j = right; j >= left; j--) printf(" %d", a[bottom][j]);
bottom--;
for (int i = bottom; i >= top; i--) printf(" %d", a[i][left]);
left++;
}
printf("\n");
}
return 0;
}
Input 3 3⏎ 1 2 3⏎ 4 5 6⏎ 7 8 9⏎ 3 4⏎ 1 2 3 4⏎ 5 6 7 8⏎ 9 10 11 12⏎ 1 4⏎ 1 2 3 4⏎ 4 1⏎ 1⏎ 2⏎ 3⏎ 4⏎:
Output:
3 x 3: 1 2 3 6 9 8 7 4 5
3 x 4: 1 2 3 4 8 12 11 10 9 5 6 7 6
1 x 4: 1 2 3 4 3 2 1
4 x 1: 1 2 3 4 3 2
The 3 × 3 is right, but the 3 × 4 prints 6 twice, the single row goes back (3 2 1), and the single column repeats 3 2.
Why. The while check runs only at the start of a round. In the single row, step 1 prints 1 2 3 4 and sets top = 1, while bottom = 0: the walls have crossed, nothing is left. But step 3 still runs, and bottom is still row 0, so it prints the same row backwards. The same happens to the inner ring of the 3 × 4 (only 6 7 is left: a single row) and to the single column with step 4.
The fix: check the walls again before steps 3 and 4
#include <stdio.h>
int main() {
int r, c, a[10][10];
while (scanf("%d %d", &r, &c) == 2) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &a[i][j]);
int top = 0, bottom = r - 1, left = 0, right = c - 1;
printf("%d x %d:", r, c);
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) printf(" %d", a[top][j]);
top++;
for (int i = top; i <= bottom; i++) printf(" %d", a[i][right]);
right--;
if (top <= bottom) {
for (int j = right; j >= left; j--) printf(" %d", a[bottom][j]);
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) printf(" %d", a[i][left]);
left++;
}
}
printf("\n");
}
return 0;
}
Input 3 3⏎ 1 2 3⏎ 4 5 6⏎ 7 8 9⏎ 3 4⏎ 1 2 3 4⏎ 5 6 7 8⏎ 9 10 11 12⏎ 1 4⏎ 1 2 3 4⏎ 4 1⏎ 1⏎ 2⏎ 3⏎ 4⏎:
Output:
3 x 3: 1 2 3 6 9 8 7 4 5
3 x 4: 1 2 3 4 8 12 11 10 9 5 6 7
1 x 4: 1 2 3 4
4 x 1: 1 2 3 4
Steps 1 and 2 don't need a check: the while condition guarantees a row is left for step 1, and after step 1 the loop in step 2 simply runs zero times if nothing is left. Complexity: each element printed once → O(r × c) time, O(1) space (four ints).
Complexity summary
| Task | Method | Time | Space |
|---|---|---|---|
| add r × c | seat by seat | O(r × c) | O(1) extra |
| multiply | seat by seat | O(r × c), wrong | O(1) |
| row times column, three loops | O(r1 × c1 × c2) = O(n³) for n × n | O(1) extra | |
| transpose n × n | swap for every (i, j) | O(n²), unchanged | O(1) |
| swap only j > i, in place | O(n²) | O(1) | |
| transpose r × c | into a new matrix | O(r × c) | O(r × c) |
| spiral | four walls, no mid-round checks | O(r × c), repeats | O(1) |
| four walls + two checks | O(r × c) | O(1) |
Adding, transposing and the spiral can't beat O(r × c): every number has to be read at least once. (Faster multiplication algorithms exist, like Strassen's, about O(n^2.81), but interviews expect the three loops.)
Common mistakes (and the real results)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
a[i][j] * b[i][j] |
no error: 5 12 21 32 |
not row times column | sum += a[i][k] * b[k][j] |
no c1 == r2 check |
no error: an "answer" for an impossible product | k reads rows that weren't typed |
if (c1 != r2) not possible |
int p[10][10]; p[i][j] += ... (local, never zeroed) |
no error: garbage totals | a local array starts with garbage | int sum = 0; per seat, or = {0} |
j < c1 instead of j < c2 in the product |
wrong shape | the product is r1 × c2 | j < c2 |
pass int a[3][3] to int m[10][10] |
warning: ... incompatible pointer type [-Wincompatible-pointer-types], garbage (UB) |
rows of 3 vs rows of 10 | same column size, or a VLA parameter |
in-place transpose with j from 0 |
no error: unchanged matrix | each pair swapped twice | j = i + 1 |
| in-place transpose of a 2 × 3 | wrong shape | a non-square matrix changes shape | a new t[c][r] |
| spiral without mid-round checks | no error: 6 twice, 3 2 1 again |
walls crossed inside a round | if (top <= bottom), if (left <= right) |
The un-zeroed product for real (the numbers are garbage, so yours may differ; it is wrong either way):
#include <stdio.h>
void read_matrix(int m[10][10], int r, int c) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &m[i][j]);
}
int main() {
int a[10][10], b[10][10], p[10][10];
int r1, c1, r2, c2;
scanf("%d %d", &r1, &c1);
read_matrix(a, r1, c1);
scanf("%d %d", &r2, &c2);
read_matrix(b, r2, c2);
for (int i = 0; i < r1; i++)
for (int j = 0; j < c2; j++)
for (int k = 0; k < c1; k++)
p[i][j] += a[i][k] * b[k][j];
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++)
printf("%5d", p[i][j]);
printf("\n");
}
return 0;
}
Input 2 2⏎ 1 2⏎ 3 4⏎ 2 2⏎ 5 6⏎ 7 8⏎:
Output:
2451 2454
2475 2482
No warning, and totals far from 19 22 43 50: p started with whatever was on the stack. Reading an uninitialised local is undefined behaviour, so another run or another compiler may print other numbers, or by luck the right ones, which hides the bug. (In a tiny program with fixed sizes gcc can see the problem and warns 'p' is used uninitialized [-Wuninitialized]; here, with sizes read at run time, it can't.) Always start every sum at 0.
Your turn: rotate a square matrix 90° clockwise (solution)
Problem. Rotate an n × n matrix a quarter turn to the right, in place. 1 2 3 / 4 5 6 / 7 8 9 → 7 4 1 / 8 5 2 / 9 6 3.
Idea. Two things you already know: transpose it (today, j from i + 1), then reverse every row (episode 8, two indexes moving toward each other). After the transpose, row 0 is 1 4 7; reversed, 7 4 1. O(n²) time, O(1) space. (Counter-clockwise: transpose, then reverse every column.)
Show the solution
#include <stdio.h>
int main() {
int n, a[10][10];
while (scanf("%d", &n) == 1) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (int i = 0; i < n; i++) /* 1. transpose */
for (int j = i + 1; j < n; j++) {
int t = a[i][j]; a[i][j] = a[j][i]; a[j][i] = t;
}
for (int i = 0; i < n; i++) /* 2. reverse each row */
for (int lo = 0, hi = n - 1; lo < hi; lo++, hi--) {
int t = a[i][lo]; a[i][lo] = a[i][hi]; a[i][hi] = t;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%4d", a[i][j]);
printf("\n");
}
printf("\n");
}
return 0;
}
Input 3⏎ 1 2 3⏎ 4 5 6⏎ 7 8 9⏎ 2⏎ 1 2⏎ 3 4⏎ 1⏎ 5⏎:
Output:
7 4 1
8 5 2
9 6 3
3 1
4 2
5
Practice questions (with solutions)
1. Is a matrix symmetric? A square matrix is symmetric if it equals its transpose: a[i][j] == a[j][i] for every pair.
Solution
Compare only above the diagonal (the same pairs as the transpose). O(n²) time, O(1) space, and it stops at the first mismatch.
#include <stdio.h>
int is_symmetric(int n, int a[n][n]) {
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (a[i][j] != a[j][i]) return 0;
return 1;
}
int main() {
int s[3][3] = {{1, 7, 3}, {7, 4, 5}, {3, 5, 6}};
int t[2][2] = {{1, 2}, {3, 4}};
printf("s: %s\n", is_symmetric(3, s) ? "symmetric" : "not symmetric");
printf("t: %s\n", is_symmetric(2, t) ? "symmetric" : "not symmetric");
return 0;
}
Output:
s: symmetric
t: not symmetric
2. Sum of both diagonals. The main diagonal is a[i][i]; the other one (the anti-diagonal) is a[i][n - 1 - i]. For odd n the centre is on both: count it once.
Solution
#include <stdio.h>
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int n = 3, sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i][i];
if (i != n - 1 - i) sum += a[i][n - 1 - i];
}
printf("diagonal sum = %d\n", sum); /* 1+5+9 + 3+7 */
return 0;
}
Output:
diagonal sum = 25
O(n) time: only 2n seats are visited.
3. Snake (zigzag) order. Print row 0 left to right, row 1 right to left, row 2 left to right, and so on.
Solution
#include <stdio.h>
int main() {
int a[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
for (int i = 0; i < 3; i++) {
if (i % 2 == 0)
for (int j = 0; j < 4; j++) printf("%d ", a[i][j]);
else
for (int j = 3; j >= 0; j--) printf("%d ", a[i][j]);
}
printf("\n");
return 0;
}
Output:
1 2 3 4 8 7 6 5 9 10 11 12
O(r × c) time, O(1) space.
4. Read a matrix safely. Reject sizes outside 1..10 before reading, so a bad size can never write outside the 10 × 10 box.
Solution
#include <stdio.h>
int read_matrix(int m[10][10], int *r, int *c) {
if (scanf("%d %d", r, c) != 2) return 0;
if (*r < 1 || *r > 10 || *c < 1 || *c > 10) {
printf("bad size %d x %d\n", *r, *c);
return 0;
}
for (int i = 0; i < *r; i++)
for (int j = 0; j < *c; j++)
if (scanf("%d", &m[i][j]) != 1) return 0;
return 1;
}
int main() {
int a[10][10], r, c;
while (read_matrix(a, &r, &c))
printf("read a %d x %d matrix, last element %d\n", r, c, a[r - 1][c - 1]);
return 0;
}
Input 2 2⏎ 1 2⏎ 3 4⏎ 11 3⏎:
Output:
read a 2 x 2 matrix, last element 4
bad size 11 x 3
int *r is a pointer, so the function can hand the size back to main (pointers are the next episode).
Quick quiz
#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int sum = 0;
for (int k = 0; k < 3; k++)
sum += a[0][k] * a[1][k];
printf("%d\n", sum);
return 0;
}
(A) 21 (B) 32 (C) 15 (D) Compile error
Answer
(B) 32. It is the dot product of row 0 and row 1: 1×4 + 2×5 + 3×6 = 4 + 10 + 18 = 32, exactly how one seat of a matrix product is made.
#include <stdio.h>
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int sum = 0;
for (int k = 0; k < 3; k++)
sum += a[0][k] * a[1][k];
printf("%d\n", sum);
return 0;
}
Output:
32
Interview questions
- When can two matrices be multiplied, and what's the result's size? When the columns of the first equal the rows of the second: (r1 × c1)(c1 × c2) = r1 × c2.
- Time complexity of multiplying two n × n matrices the usual way? O(n³): n² seats, n multiply-adds each.
- Is matrix multiplication commutative (A × B = B × A)? No; often B × A isn't even possible, and when both are, they usually differ.
- Why must a 2D array parameter state the column size? The array is stored row after row; to find
m[i][j]C must skipiwhole rows, so it needs the row length. - Transpose in place: why does
jstart ati + 1? Visiting every (i, j) swaps each pair twice and undoes the transpose. - Can you transpose a non-square matrix in place in a 2D array? Not into the same shape: r × c becomes c × r, so use a new matrix (in-place versions on a flat array exist but are complex).
- Rotate a matrix 90° clockwise in place. Transpose, then reverse each row.
- In spiral order, which steps need an extra check, and why? Steps 3 and 4 (bottom row, left column): steps 1 and 2 can make the walls cross mid-round.
- What's row-major order? Storing a 2D array row after row in one line of memory, as C does.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Matrix | A grid of numbers in rows and columns | 1 2 / 3 4 |
| Row / column | A line across / a line down a matrix | row 0 = 1 2, column 0 = 1 3 |
| r × c (dimensions) | A matrix with r rows and c columns | a 2 × 3 has 6 elements |
| Square matrix | As many rows as columns | 3 × 3 |
| 2D array | C's array of arrays, used for a matrix | int a[3][4]; |
Element a[i][j] |
The value in row i, column j, from 0 |
a[1][0] = 4 |
| Matrix addition | Adding the elements in the same seat; needs the same size | s[i][j] = a[i][j] + b[i][j] |
| Matrix multiplication | Each result seat is a row of A times a column of B | 19 = 1×5 + 2×7 |
| Dot product | Multiply two lists pair by pair and add | (1,2)·(5,7) = 19 |
c1 == r2 |
The condition for A × B to exist | 2×3 × 3×2 is fine |
| Row-major order | A 2D array stored row after row in memory | C's layout |
| Incompatible pointer type | A pointer to rows of one length passed where another is expected | int (*)[3] vs int (*)[10] |
| VLA parameter | A parameter whose array size comes from other parameters | int m[r][c] |
| Transpose | Rows become columns: t[j][i] = a[i][j] |
1 2 3 / 4 5 6 → 1 4 / 2 5 / 3 6 |
| In place | Changing the data inside the same array, no second copy | the n × n transpose |
| Main diagonal | The seats where i == j |
1 5 9 in 1..9 |
| Anti-diagonal | The seats where j == n − 1 − i |
3 5 7 in 1..9 |
| Symmetric matrix | Equal to its own transpose | a[i][j] == a[j][i] |
| Spiral order | Outer ring clockwise, then the next ring inside | 1 2 3 6 9 8 7 4 5 |
| Boundary (wall) | The edge of the part still left to print | top, bottom, left, right |
%5d |
Print an int right-aligned in 5 characters | 19 |
| Big O | How the work grows with the input, ignoring constants | O(n³) |
| O(r × c) / O(n²) / O(n³) | Work grows like the number of seats / n squared / n cubed | spiral / transpose / multiply |
| Undefined behaviour (UB) | The C standard makes no promise about the result | reading outside an array |
| Garbage value | Whatever was left in memory; an uninitialised local holds it | int p[2][2]; |
Summary
- A matrix is a 2D array:
a[i][j]is rowi, columnj. Keep fixed 10 × 10 boxes and use ther × ccorner. - Add seat by seat (same size). Multiply row times column with three loops, a
sumthat starts at 0, and only whenc1 == r2; the result isr1 × c2, O(n³) for n × n. - A matrix parameter needs the same column size (or a VLA parameter); a mismatch is an incompatible-pointer-type warning and undefined behaviour.
- Transpose in place:
jstarts ati + 1; a non-square matrix goes into a newc × rmatrix. - Spiral: four walls (
top,bottom,left,right), and check them again before the bottom row and the left column. O(r × c) time, O(1) space.
Next episode: Pointer questions I: swap two numbers with pointers, pointer arithmetic output questions, walk an array with a pointer, and why a[i] is *(a + i).