Diagonals, transpose and functions
Square matrices and their two diagonals, lab experiment 11 (are the diagonals of a 10 × 10 array equal?), transpose, how a matrix sits in memory, passing a matrix to a function, common mistakes and how much work each operation takes.
Diagonals live in square matrices
A square matrix (מטריצה ריבועית) has the same number of rows and columns: N × N. Only a square matrix has diagonals from corner to corner.
int a[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};- The main diagonal (אלכסון ראשי) runs from the top-left corner to the bottom-right: 1, 5, 9.
- The secondary diagonal (אלכסון משני) runs from the top-right corner to the bottom-left: 3, 5, 7.
When N is odd, the centre cell (here 5) is on both.
The main diagonal: row == column
On the main diagonal the row index equals the column index: (0,0), (1,1), (2,2). So one loop is enough, and the same counter is used for both indexes:
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += a[i][i];
}
// 1 + 5 + 9 = 15Two nested loops with if (r == c) would also work, but they visit all 9 cells to use 3 of them.
The secondary diagonal: column = N − 1 − row
On the secondary diagonal the row goes down 0, 1, 2 while the column goes back 2, 1, 0. In an N × N matrix the column is N - 1 - i:
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += a[i][3 - 1 - i];
}
// 3 + 5 + 7 = 15The same rule written as a test on a cell (i, j): the cell is on the secondary diagonal when i + j == N - 1.
| Diagonal | Index rule | Cells for N = 5 |
|---|---|---|
| main | a[i][i], test i == j | (0,0) (1,1) (2,2) (3,3) (4,4) |
| secondary | a[i][N - 1 - i], test i + j == N - 1 | (0,4) (1,3) (2,2) (3,1) (4,0) |
Lab experiment 11: are the diagonals equal?
The required lab of this unit: given a 10 × 10 matrix of integers, decide whether the main diagonal is equal to the secondary diagonal position by position. For every row i, compare matrix[i][i] with matrix[i][9 - i]. If all ten pairs are equal, print EQUAL; otherwise print NOT EQUAL. (Equal sums are not enough: 1 + 2 and 2 + 1 have the same sum, but the pairs differ.)
The idea is a flag (דגל): a variable that starts at 1 ("equal so far") and becomes 0 at the first difference. After the first difference there is nothing left to check, so break leaves the loop.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define SIZE 10
int main(void)
{
int matrix[SIZE][SIZE];
int equal = 1;
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
scanf("%d", &matrix[r][c]);
}
}
for (int i = 0; i < SIZE; i++) {
if (matrix[i][i] != matrix[i][SIZE - 1 - i]) {
equal = 0;
break;
}
}
if (equal) {
printf("EQUAL\n");
} else {
printf("NOT EQUAL\n");
}
return 0;
}Two tests, one for each answer:
- 100 zeros: every pair is 0 and 0, so the output is
EQUAL. - 100 zeros, but the tenth number (that is
matrix[0][9]) is 5: the first pair is 0 and 5, so the output isNOT EQUAL.
EQUALNOT EQUALTranspose: rows become columns
The transpose (מטריצה משוחלפת) of a matrix turns every row into a column. A 2 × 3 matrix becomes 3 × 2:
a (2 × 3) b (3 × 2)
1 2 3 1 4
4 5 6 2 5
3 6The rule: b[c][r] = a[r][c]. The destination has the sizes reversed.
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[3][2];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
b[c][r] = a[r][c];
}
}Each visit copies one cell to its mirrored place. No element is lost. If b were declared int b[2][3], the copy b[2][0] would be out of bounds.
How a matrix sits in memory
We draw a matrix as a grid, but memory is one long line of boxes. C stores row 0 first, then row 1 right after it, and so on: row-major order (סדר לפי שורות). The last index changes fastest, the same order in which our nested loops visit the cells.
For int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; memory holds:
| box | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| value | 1 | 2 | 3 | 4 | 5 | 6 |
| element | a[0][0] | a[0][1] | a[0][2] | a[1][0] | a[1][1] | a[1][2] |
So the element after a[0][2] is a[1][0]. To find a[r][c], the computer skips r whole rows of COLS boxes and then c more: box r * COLS + c. For a[1][2] that is 1 × 3 + 2 = 5.
Passing a matrix to a function
A function that works on a matrix must know the number of columns: it is written in the parameter. The number of rows comes as a normal argument.
#include <stdio.h>
#define COLS 3
int sumMatrix(int rows, const int a[][COLS])
{
int sum = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < COLS; c++) {
sum += a[r][c];
}
}
return sum;
}
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int total = sumMatrix(2, a);
printf("Total: %d\n", total);
return 0;
}Total: 21Why the columns are needed: to reach a[r][c] the function computes r * COLS + c, as in the memory table above. Without COLS it cannot know where row 1 starts. const promises that the function only reads the elements and does not change them.
Common mistakes
| Mistake | Correct |
|---|---|
<= in a loop bound | r < ROWS, c < COLS |
| Row and column swapped | always a[row][column] |
Forgetting & in scanf | scanf("%d", &a[r][c]); |
Starting max at 0 | start with the first element, a[0][0] |
| Diagonals of a non-square matrix | the diagonal formulas are for N × N only |
How much work: time complexity
Time complexity (סיבוכיות זמן) describes how the number of steps grows with the size of the data. For a matrix with R rows and C columns:
| Operation | Cells visited | Complexity |
|---|---|---|
| read one cell | 1 | O(1) |
| sum one row | C | O(C) |
| sum one column | R | O(R) |
| scan all cells | R × C | O(R × C) |
| main diagonal of N × N | N | O(N) |
Doubling a square matrix from 5 × 5 to 10 × 10 doubles the work on a diagonal (5 to 10 cells) but makes a full scan four times longer (25 to 100 cells). Unit 10 uses the same idea to compare sorting methods.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| square matrix | מטריצה ריבועית | N rows and N columns |
| main diagonal | אלכסון ראשי | a[i][i]: row equals column |
| secondary diagonal | אלכסון משני | a[i][N-1-i]: row + column = N − 1 |
| flag | דגל | a variable that is 1 or 0: found or not |
| transpose | מטריצה משוחלפת | rows become columns: b[c][r] = a[r][c] |
| row-major order | סדר לפי שורות | memory holds row 0, then row 1, … |
| parameter | פרמטר | a matrix parameter needs the columns: a[][COLS] |
| time complexity | סיבוכיות זמן | how the work grows with the size |
Practice
More questions with answers: Practice: 30 short questions (questions 8-12, 15, 18-20, 24, 28) and Practice: programs and challenges (questions 6, 7, 9, 10, 12, 20-25 and the challenges 31-40).