Codiqo

Learn C · lesson 54 of 60 · about 8 minutes

Looping over Rows and Columns

Visit every cell with nested loops, and total rows and columns.

What you'll learn

  • Loop over every cell with nested for loops
  • Total each row and each column
  • Search a grid for a value

The day's traffic

Next the report sums up the day's network traffic. There's a line of 4 numbers for each of the 3 servers, web, db and mail, one number for each quarter of the day, so the requests make a grid of 3 rows and 4 columns. A line that isn't 4 numbers counts as all zeros, with Traffic for db missing. The report totals each row, how busy each server was, web: 440 requests, and each column, to find the busiest quarter of the day: Busiest quarter: 3 (320 requests).

Two loops, one grid

To visit every cell, put one loop inside another. The outer loop picks the row, the inner loop walks across its columns:

for (int r = 0; r < ROWS; r++) and inside it for (int c = 0; c < COLS; c++).

Printing and totalling

#include <stdio.h>

int main(void) {
    int sales[2][3] = {{4, 0, 7}, {2, 9, 1}};
    int total = 0;
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 3; c++) {
            printf("%3d", sales[r][c]);
            total += sales[r][c];
        }
        printf("\n");
    }
    printf("Total: %d\n", total);
    return 0;
}

Output

  4  0  7
  2  9  1
Total: 23

Row totals and column totals

For a row total, reset the sum at the start of each row. For a column total, swap the loops so the outer loop picks the column and the inner loop goes down the rows.

Totals both ways

#include <stdio.h>

int main(void) {
    int s[2][3] = {{4, 0, 7}, {2, 9, 1}};
    for (int r = 0; r < 2; r++) {
        int sum = 0;
        for (int c = 0; c < 3; c++) sum += s[r][c];
        printf("Row %d: %d\n", r, sum);
    }
    for (int c = 0; c < 3; c++) {
        int sum = 0;
        for (int r = 0; r < 2; r++) sum += s[r][c];
        printf("Column %d: %d\n", c, sum);
    }
    return 0;
}

Output

Row 0: 11
Row 1: 12
Column 0: 6
Column 1: 9
Column 2: 8

Finding the busiest column

For the busiest quarter, each column total is worked out inside the outer loop with its own int sum = 0, then compared with the best so far. Starting busiest_total at -1 means even a quiet day of zeros has a busiest quarter, the first one, and using > rather than >= keeps the first quarter when two tie. Quarters are printed from 1, so the column number gets 1 added.

Tip

Name the loop variables r and c (or row and col) instead of i and j. It makes mixed-up indexes much easier to spot.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.