C Multidimensional Arrays
A multidimensional array is a table of values with rows and columns. A plain array held one row; this table needs two numbers to pick one value, row first, then column.
Read one cell
Row 1 holds 4, 5, 6, so column 2 of that row is 6. The print line shows 6.
#include <stdio.h>
int main() {
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("%d\n", grid[1][2]);
return 0;
}Change one cell
The first cell changes from 1 to 9. The print lines show 9, then the value next to it, 2.
#include <stdio.h>
int main() {
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
grid[0][0] = 9;
printf("%d\n", grid[0][0]);
printf("%d\n", grid[0][1]);
return 0;
}Print the whole table
The loop runs once per row and prints the three values in that row. Both rows print: 1 2 3, then 4 5 6.
#include <stdio.h>
int main() {
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
printf("%d %d %d\n", grid[i][0], grid[i][1], grid[i][2]);
}
return 0;
}Example
#include <stdio.h>
int main() {
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
int total = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
total = total + grid[i][j];
}
}
printf("%d\n", total);
return 0;
}Key points
- int grid[2][3] makes a table with 2 rows and 3 columns.
- The first pair of brackets holds the row count, and the second pair holds the column count.
- grid[1][2] is the value in row 1, column 2.
- Rows and columns both start counting at 0.
- Each row is written inside its own pair of braces.
- grid[0][0] = 9; puts 9 in the first row and first column.
- One loop can walk the rows, and a second loop inside it can walk the columns.
The table holds the values 1 to 6. The outer loop walks the rows and the inner loop walks the columns, adding each value. The print line shows 21.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is grid[1][0] when grid holds {{1, 2, 3}, {4, 5, 6}}?