90 דק׳

שורות, עמודות ולולאות מקוננות

הגדרה ואתחול של מטריצה, הגעה לכל תא עם אינדקס שורה ואינדקס עמודה, שמירה על הגבולות, ומעבר על כל התאים בשתי לולאות מקוננות: קלט ב־scanf והדפסה בעמודות מסודרות.

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

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

From one line to a grid

In unit 8 an array was one line of values: int readings[10];. Many kinds of data have two directions. A thermal chamber has 20 temperature sensors mounted in 4 rows and 5 columns. As one list of 20 values, every reading is there, but the position is lost: "value 12 is hot" does not tell the technician which sensor to replace. In a grid you can say "row 2, column 2" and walk to it.

A two-dimensional array (מערך דו־ממדי) stores values in rows (שורות) and columns (עמודות), like a table. It is also called a matrix (מטריצה). Rows go across, columns go down. Every cell holds one element, and all elements have the same type.

The same 20 readings as one list and as a grid. The hot sensor is value 12 in the list and row 2, column 2 in the grid.לפתיחה במסך מלא

Declaring a matrix

int a[3][4];

This declares a matrix of int with 3 rows and 4 columns: 3 × 4 = 12 elements. The first pair of brackets is the number of rows, the second is the number of columns. The general form is:

type name[ROWS][COLS];

The size is fixed when you declare it, as with one-dimensional arrays. Until you give the elements values, they hold garbage: whatever was in that memory before.

Indexes and bounds

Every element has two indexes (אינדקסים): first the row, then the column. Both start at 0.

  • Rows: 0 to ROWS − 1. In int a[3][4] that is 0, 1, 2.
  • Columns: 0 to COLS − 1. In int a[3][4] that is 0, 1, 2, 3.

So a[0][0] is the top-left element and a[2][3] is the bottom-right one, the last valid element. a[3][0] is out of bounds (חריגה מגבולות המערך): row 3 does not exist.

a[2][3] is the last valid element of a 3 × 4 matrix. a[3][0] is outside the array.לפתיחה במסך מלא

Initializing a matrix

You can give all the values in the declaration. Each inner pair of braces is one row, and inside a row the values go in column order:

int a[2][3] = {
    {10, 20, 30},
    {40, 50, 60}
};

Row 0 is 10 20 30, row 1 is 40 50 60. To start with zeros everywhere:

int zeros[2][3] = {0};

Elements you do not list become 0. So int a[2][3] = {{7}}; gives a[0][0] == 7 and every other element 0.

Reading and changing one element

Write the name, then the row index, then the column index: a[row][column].

int value = a[1][2];   // row 1, column 2: 60
a[0][1] = 99;          // row 0, column 1: 20 becomes 99

A useful habit: point to the cell first, then say the expression, always row first and column second.

Click any cell: the slide writes its expression and its value. Start with grid[1][2], which prints 5.לפתיחה במסך מלא

Visiting every cell: nested loops

To do something with every element you need two loops, one inside the other: a nested loop (לולאה מקוננת). The outer loop picks a row; the inner loop walks across the columns of that row.

#include <stdio.h>
 
int main(void)
{
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
 
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 3; c++) {
            printf("%d ", a[r][c]);
        }
        printf("\n");
    }
    return 0;
}
1 2 3 
4 5 6 

What the computer does:

rcprints
001
012
023
03inner loop ends, printf("\n")
104
115
126
13inner loop ends, printf("\n")
2outer loop ends

The inner loop runs completely, from c = 0 to the end, for every single round of the outer loop. The printf("\n") is in the outer loop, after the inner loop, so it runs once per row.

Step through the program: the current line, the cell being read, the counters r and c, and the output.לפתיחה במסך מלא

The visit order

The cells are visited row by row: (0,0) (0,1) (0,2), then (1,0) (1,1) (1,2). The column index changes fastest. The body of the inner loop runs rows × columns times: for for (r = 0; r < 3; r++) for (c = 0; c < 4; c++) that is 3 × 4 = 12 times.

The question sets call the counters i (row) and j (column) instead of r and c. The names do not matter; the order does: the row loop outside, the column loop inside.

Reading a matrix with scanf

The same two loops fill a matrix from the keyboard. scanf needs the address of the cell, so write & before a[r][c]:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int a[3][4];
 
    for (int r = 0; r < 3; r++) {
        for (int c = 0; c < 4; c++) {
            scanf("%d", &a[r][c]);
        }
    }
 
    for (int r = 0; r < 3; r++) {
        for (int c = 0; c < 4; c++) {
            printf("%3d", a[r][c]);
        }
        printf("\n");
    }
    return 0;
}

Input (one line or several, scanf does not mind):

12 15 14 13 20 18 19 21 10 11 9 12

Output:

 12 15 14 13
 20 18 19 21
 10 11  9 12

The values fill the matrix in the order they are typed: all of row 0, then row 1, then row 2. In Visual Studio the first line, #define _CRT_SECURE_NO_WARNINGS, stops warning C4996 about scanf.

Robust programs also check what scanf returns (the number of values it read). We leave that out here to keep the loops clear.

Printing in neat columns

%3d prints every number in three character places, with spaces in front of short numbers. Compare the last row above: 10 11 9 12. With "%d " the 9 is one character shorter and the columns drift:

12 15 14 13 
20 18 19 21 
10 11 9 12 

Choose the width from the largest number: for readings up to 1023 use %5d (four digits and a space).

The same matrix printed with "%d " and with "%3d".לפתיחה במסך מלא

Key words

EnglishHebrewMeaning
two-dimensional arrayמערך דו־ממדיvalues in rows and columns
matrixמטריצהanother name for a two-dimensional array
rowשורהgoes across; the first index
columnעמודהgoes down; the second index
indexאינדקסthe position, starting at 0
out of boundsחריגה מגבולות המערךan index that does not exist in the array
initializationאתחולvalues given in the declaration
nested loopלולאה מקוננתa loop inside another loop

Practice

More questions with answers: Practice: 30 short questions (questions 1-6 and 16-21 fit this lesson) and Practice: programs and challenges (questions 1-4, 8, 11 and 13).