90 דק׳

אלכסונים, שחלוף ופונקציות

מטריצה ריבועית ושני האלכסונים שלה, ניסוי מעבדה 11 (האם האלכסונים של מערך 10 על 10 שווים?), שחלוף, איך מטריצה יושבת בזיכרון, העברת מטריצה לפונקציה, טעויות נפוצות וכמה עבודה דורשת כל פעולה.

למצגתלקריאה באתרבאנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

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 in indigo, the secondary diagonal in dark. The centre 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 = 15

Two 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 = 15

The same rule written as a test on a cell (i, j): the cell is on the secondary diagonal when i + j == N - 1.

DiagonalIndex ruleCells for N = 5
maina[i][i], test i == j(0,0) (1,1) (2,2) (3,3) (4,4)
secondarya[i][N - 1 - i], test i + j == N - 1(0,4) (1,3) (2,2) (3,1) (4,0)
Click a cell of the 5 × 5 matrix: the slide checks i == j and i + j == 4.לפתיחה במסך מלא

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 is NOT EQUAL.
EQUAL
NOT EQUAL
The loop compares the two diagonal cells of each row. Switch to test 2: the pair of row 3 differs and the loop stops there.לפתיחה במסך מלא

Transpose: 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 6

The 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.

Each step copies one cell: the cursor in a moves row by row, the cursor in b column by column.לפתיחה במסך מלא

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:

box012345
value123456
elementa[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.

The rows slide into one line: row 0, then row 1. a[1][0] is box 3.לפתיחה במסך מלא

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: 21

Why 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

MistakeCorrect
<= in a loop boundr < ROWS, c < COLS
Row and column swappedalways a[row][column]
Forgetting & in scanfscanf("%d", &a[r][c]);
Starting max at 0start with the first element, a[0][0]
Diagonals of a non-square matrixthe 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:

OperationCells visitedComplexity
read one cell1O(1)
sum one rowCO(C)
sum one columnRO(R)
scan all cellsR × CO(R × C)
main diagonal of N × NNO(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.

Click each operation and count the cells it visits.לפתיחה במסך מלא

Key words

EnglishHebrewMeaning
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).