Two-Dimensional Arrays

A grid of rows and columns. Add up each row with nested loops.

C · beginner · 7 min · 22 steps · free

What you'll learn

arrays_2d.c

#include <stdio.h>

int main(void) {
    int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int row_sum[2] = {0, 0};
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 3; c++) {
            row_sum[r] += grid[r][c];
        }
    }
    printf("%d %d\n", row_sum[0], row_sum[1]);
    return 0;
}

Step by step

  1. 2 rows of 3. In memory they are stored one row after the other.
  2. row_sum is created on the stack with the value [0, 0].
  3. r is created on the stack with the value 0.
  4. c is created on the stack with the value 0.
  5. row_sum[0] += grid[0][0].
  6. c changes from 0 to 1.
  7. row_sum changes from [1, 0] to [3, 0].
  8. c changes from 1 to 2.
  9. row_sum changes from [3, 0] to [6, 0].
  10. c goes out of scope and disappears.
  11. r changes from 0 to 1. c is created on the stack with the value 3.
  12. c changes from 3 to 0.
  13. Row 1 starts.
  14. c changes from 0 to 1.
  15. row_sum changes from [6, 4] to [6, 9].
  16. c changes from 1 to 2.
  17. row_sum changes from [6, 9] to [6, 15].
  18. c goes out of scope and disappears.
  19. r goes out of scope and disappears.
  20. It prints 6 15.
  21. The method returns 0.
  22. 6 and 15.

Common mistakes

Best practices

Key takeaways

Check yourself

int g[3][4] has how many ints?

Answer: 12. 3 × 4.

g[1][0] is?

Answer: The first value of the second row. Row first.

·

More in Arrays and Strings