Rows, columns and nested loops
Declare and initialize a matrix, reach any cell with a row index and a column index, stay inside the bounds, and visit every cell with two nested loops: read with scanf and print in neat columns.
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.
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.
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 99A useful habit: point to the cell first, then say the expression, always row first and column second.
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:
| r | c | prints |
|---|---|---|
| 0 | 0 | 1 |
| 0 | 1 | 2 |
| 0 | 2 | 3 |
| 0 | 3 | inner loop ends, printf("\n") |
| 1 | 0 | 4 |
| 1 | 1 | 5 |
| 1 | 2 | 6 |
| 1 | 3 | inner loop ends, printf("\n") |
| 2 | outer 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.
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 12Output:
12 15 14 13
20 18 19 21
10 11 9 12The 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).
Key words
| English | Hebrew | Meaning |
|---|---|---|
| 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).