Lesson 7 of 8 · Functions and Arrays · 2 min read · Updated
Two-dimensional arrays
Tables of values in rows and columns: declaring, filling, totalling and transposing them.
A two-dimensional array is a table: int marks[3][4] has 3 rows and 4 columns — say 3 students and 4 tests. marks[1][2] is row 1, column 2. Both counts start at 0.
#include <stdio.h>
int main(void)
{
int marks[3][4] = {
{72, 85, 63, 91},
{55, 78, 88, 69},
{90, 61, 74, 82},
};
for (int s = 0; s < 3; s++) {
int total = 0;
for (int t = 0; t < 4; t++) {
printf("%4d", marks[s][t]);
total += marks[s][t];
}
printf(" total %d\n", total);
}
return 0;
}
72 85 63 91 total 311
55 78 88 69 total 290
90 61 74 82 total 307
Two nested loops visit every cell: the outer loop picks the row, the inner loop walks across its columns. That pattern — for row, for column — is how almost every 2D program starts.
Transposing a matrix
#include <stdio.h>
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int t[3][2];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
t[c][r] = a[r][c]; /* row becomes column */
}
}
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 2; c++) {
printf("%4d", t[r][c]);
}
printf("\n");
}
return 0;
}
1 4
2 5
3 6
Note
In memory, a 2D array is stored row after row in one long line (row-major order). That is why a function receiving one must be told the column count: void show(int a[][4], int rows). The number of rows may be left out; the columns may not.
int m[3][5]; — how many int values does it hold?
Try this now
- Add two 3 × 3 matrices and print the result.
- Print the total of every column (each test) instead of every row.
- Multiply two 2 × 2 matrices using three nested loops.
- Print only the diagonal elements of a 4 × 4 matrix (where row equals column).
Create a free account to save your progress, or sign in.