Loading lessons...
Multidimensional Arrays
Multidimensional Arrays
An array whose elements are themselves arrays forms a grid: rows and columns.
A 2D array
string letters[2][3] = {
{"A", "B", "C"},
{"E", "F", "G"}
};
- The first index picks the row.
- The second index picks the column.
cout << letters[0][1]; // B (row 0, column 1)
cout << letters[1][2]; // G (row 1, column 2)
Nested loops
To visit every cell, use a loop inside another loop - one for the rows, one for the columns:
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
cout << letters[r][c];
}
}
That prints ABCEFG, walking each row from left to right.
More dimensions
Add another index for another dimension: int cube[2][3][4]; is a 2x3x4 block of ints. The pattern is the same - one nested loop per dimension.
TL;DR
- A 2D array is an array of arrays - a grid with rows and columns.
- First index = row; second index = column.
letters[1][2]reaches index row 1, column 2.- Walk all cells with nested loops.
- Each additional dimension adds one more index and one more loop.