סכומים, מקסימום וספירה
אותן שתי לולאות, משימות שונות: סכום כל התאים, סכום של שורה ושל עמודה, ממוצע לכל שורה, המקסימום ומיקומו, וספירה של התאים שעומדים בתנאי.
השיעור הזה כתוב באנגלית בלבד.
One traversal, many jobs
Most work on a matrix uses the nested loops of the last lesson. The two loops stay the same; only the line inside changes:
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
/* do something with a[r][c] */
}
}- Sum:
sum += a[r][c]; - Count:
if (a[r][c] % 2 == 0) count++; - Maximum:
if (a[r][c] > max) max = a[r][c];
These are the patterns from the loops unit (accumulator, counter, maximum), now on a grid. They are also the patterns of the lab exam.
The sum of every element
An accumulator (צובר) is a variable that collects a total. It starts at 0, and every visit adds one cell.
#include <stdio.h>
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int sum = 0;
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
sum += a[r][c];
}
}
printf("Sum: %d\n", sum);
return 0;
}Sum: 21sum goes 0, 1, 3, 6, 10, 15, 21. Without = 0 it would start from garbage.
The sum of one row
One row needs only one loop. The row index stays fixed; the column index changes.
int a[2][3] = {{2, 4, 6}, {1, 3, 5}};
int row = 1;
int sum = 0;
for (int c = 0; c < 3; c++) {
sum += a[row][c];
}
// row 1 is 1, 3, 5: sum is 9The sum of one column
The mirror image: the column index stays fixed; the row index changes.
int column = 0;
int sum = 0;
for (int r = 0; r < 2; r++) {
sum += a[r][column];
}
// column 0 is 2 and 1: sum is 3Row sums and column sums in one pass
With two one-dimensional arrays you can collect all row sums and all column sums in a single traversal. Every cell is added twice: to the sum of its row and to the sum of its column.
int a[3][4] = {
{12, 15, 14, 13},
{20, 18, 19, 21},
{10, 11, 9, 12}
};
int rowSum[3] = {0};
int colSum[4] = {0};
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
rowSum[r] += a[r][c];
colSum[c] += a[r][c];
}
}
// rowSum: 54 78 42
// colSum: 42 44 42 46Both lists add up to the same total, 174. A good check for your program.
An average for every row
A separate total for each row means the accumulator must start again for each row. Declare it inside the outer loop, before the inner loop:
#include <stdio.h>
#define ROWS 3
#define COLS 4
int main(void)
{
int readings[ROWS][COLS] = {
{12, 15, 14, 13},
{20, 18, 19, 21},
{10, 11, 9, 12}
};
for (int r = 0; r < ROWS; r++) {
int sum = 0;
for (int c = 0; c < COLS; c++) {
sum += readings[r][c];
}
printf("Row %d average: %.2f\n", r, (double)sum / COLS);
}
return 0;
}Row 0 average: 13.50
Row 1 average: 19.50
Row 2 average: 10.50| r | values visited | sum after the row | average |
|---|---|---|---|
| 0 | 12, 15, 14, 13 | 54 | 13.50 |
| 1 | 20, 18, 19, 21 | 78 | 19.50 |
| 2 | 10, 11, 9, 12 | 42 | 10.50 |
Two details: (double)sum keeps the fraction (an int division would give 13), and the division is by COLS, the number of values in one row.
The maximum and where it is
To find the largest value and its position, keep three variables: the value and its row and column. Start from a real cell, a[0][0], and update all three together:
#include <stdio.h>
int main(void)
{
int a[2][3] = {{5, 9, 2}, {7, 1, 6}};
int max = a[0][0], mr = 0, mc = 0;
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
if (a[r][c] > max) {
max = a[r][c];
mr = r;
mc = c;
}
}
}
printf("Max %d at (%d, %d)\n", max, mr, mc);
return 0;
}Max 9 at (0, 1)With two equal maxima, > keeps the first one found in row-by-row order; >= would keep the last one.
Counting the cells that pass a test
A counter (מונה) starts at 0 and grows by 1 for every cell that passes an if:
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int count = 0;
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
if (a[r][c] % 2 == 0) {
count++;
}
}
}
// count is 3: the values 2, 4 and 6Only the condition changes for other questions: readings above an alarm threshold (סף), if (a[r][c] > 900), or temperatures above 70, if (a[r][c] > 70). Remember that > is strict: 900 is not above 900.
Bug hunt
This fragment should print the total of each row of grid[ROWS][COLS]. It has four bugs:
int sum = 0;
for (int r = 0; r <= ROWS; r++) {
for (int c = 0; c <= COLS; c++) {
sum += grid[c][r];
}
printf("%d\n", sum);
}נסו לפתור לבד, ואז פתחו את הפתרון צעד אחר צעד.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| accumulator | צובר | a variable that collects a sum, starts at 0 |
| counter | מונה | counts the cells that pass a test |
| row sum | סכום שורה | the total of one row: the column index moves |
| column sum | סכום עמודה | the total of one column: the row index moves |
| average | ממוצע | the sum divided by the number of values |
| maximum | מקסימום (ערך מרבי) | the largest value; start from a real cell |
| threshold | סף | the limit in a test, such as an alarm level |
| reset | איפוס | setting an accumulator back to 0 |
Practice
More questions with answers: Practice: 30 short questions (questions 7, 13, 14, 22, 23, 25-27, 29, 30) and Practice: programs and challenges (questions 5 and 14-19, 26-30).