C++ Multidimensional Arrays
A multidimensional array is an array of arrays. It lets you store data in a grid or table format, using rows and columns. This is useful for things like game boards, spreadsheets, and matrices.
Declaring a Two-Dimensional Array
A two-dimensional array uses two sets of square brackets. The first number is the number of rows, and the second is the number of columns. You can picture it as a table where every value sits at the crossing of a row and a column.
A 2x3 array (2 rows, 3 columns)
#include <iostream>
using namespace std;
int main() {
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
cout << grid[0][2];
return 0;
}
// Output: 3Accessing Elements
To read a value, give both indexes: the row first, then the column. Remember both start at 0. In the example above grid[0][2] means the first row, third column, which holds the value 3.
Looping Through a 2D Array
To visit every element you use a nested loop: an outer loop for the rows and an inner loop for the columns. The outer loop picks a row, and the inner loop walks across all the columns in that row before moving on.
Nested loop over a grid
#include <iostream>
using namespace std;
int main() {
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
cout << grid[row][col] << " ";
}
cout << "\n";
}
return 0;
}
// Output:
// 1 2 3
// 4 5 6- The first bracket is always the row.
- The second bracket is always the column.
- You can add more dimensions, like grid[2][3][4], but two dimensions cover most everyday needs.