An array can have rows and columns, like a table or a chess board. This is a 2D array:
#include <stdio.h>
int main() {
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("Row 0, column 2: %d\n", grid[0][2]);
printf("Row 1, column 0: %d\n", grid[1][0]);
return 0;
}Output
Row 0, column 2: 3 Row 1, column 0: 4
[2][3]means 2 rows and 3 columns.grid[row][column]picks one cell. Both start at 0.
Think of it like this: A 2D array is like seats in a cinema: you need the row and the seat number to find your place.
Looping over a 2D array
Use one loop for the rows and one inside it for the columns:
#include <stdio.h>
int main() {
int sales[3][4] = {
{5, 3, 8, 2},
{1, 0, 4, 6},
{7, 7, 2, 9}
};
for (int r = 0; r < 3; r++) {
int rowTotal = 0;
for (int c = 0; c < 4; c++) {
printf("%3d", sales[r][c]);
rowTotal += sales[r][c];
}
printf(" | total %d\n", rowTotal);
}
return 0;
}Output
5 3 8 2 | total 18 1 0 4 6 | total 11 7 7 2 9 | total 25
Common mistake: Swapping rows and columns.
grid[2][3]has rows 0–1 and columns 0–2, sogrid[2][0]is outside the array.