2D arrays
Read · 1 of 4
An array of rows
int m[3][4]; is 3 rows of 4 columns. m[r][c] is the cell in row r, column c, both starting at 0.
Walk it with two loops: the outer one over rows, the inner one over the columns of that row.
Read this lesson as text
Rows and columns: marks tables, matrices and grids.
An array of rows
int m[3][4]; is 3 rows of 4 columns. m[r][c] is the cell in row r, column c, both starting at 0.
Walk it with two loops: the outer one over rows, the inner one over the columns of that row.
Reading a cell
#include <stdio.h>
int main() {
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("%d %d\n", m[1][0], m[0][2]);
return 0;
}What does this print?
- 4 3
- 2 6
- 3 4
Show the answer
4 3 m[1][0] is row 1 (the second row), column 0: 4. m[0][2] is the first row, third column: 3.
Exercise: Row and column totals
Read r and c (1 to 10), then an r × c table of whole numbers, row by row.
Print the sum of each row on one line, then the sum of each column on the next line, separated by spaces.
Exercise: Flip a matrix
Read r and c (1 to 10) and an r × c matrix. Print its transpose (c rows of r numbers): row i of the answer is column i of the input.