90 min

Totals, maximum and counting

The same two loops with different jobs: the sum of all cells, the sum of one row and of one column, an average for every row, the maximum and where it is, and counting the cells that pass a test.

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

sum goes 0, 1, 3, 6, 10, 15, 21. Without = 0 it would start from garbage.

Every visit adds one cell to sum: 0, 1, 3, 6, 10, 15, 21.Open full screen

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 9

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

Row 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 46

Both lists add up to the same total, 174. A good check for your program.

Watch the margins: each visit adds the cell to its row total on the right and to its column total underneath.Open full screen

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
rvalues visitedsum after the rowaverage
012, 15, 14, 135413.50
120, 18, 19, 217819.50
210, 11, 9, 124210.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 same program with sum = 0 in two places, and what each one prints.Open full screen

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 6

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

Change the limit and watch which readings become alarms: 14 above 800, 4 above 900, 1 above 1000.Open full screen

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);
}
The four bugs

Try it yourself first, then open the solution step by step.

    Key words

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