Understanding C++ Multi-Dimensional Arrays
C++ Multi Dimensional Arrays Introduction to Multi Dimensional Arrays A multi dimensional array is essentially an array composed of arrays. When declaring a multi dimensional ar...
C++ Multi-Dimensional Arrays
Introduction to Multi-Dimensional Arrays
A multi-dimensional array is essentially an array composed of arrays. When declaring a multi-dimensional array, start by defining the type of the variable, then specify the name of the array followed by square brackets to indicate the number of elements in the primary array. Add additional sets of square brackets to specify the number of elements in each sub-array.
Similar to regular arrays, you can populate multi-dimensional arrays using an array literal—a list of values separated by commas and enclosed in curly braces. Each entry in a multi-dimensional array literal is itself an array literal. Each additional set of square brackets in the array declaration introduces a new dimension. An array with two sets of square brackets is two-dimensional. Arrays can have multiple dimensions, but increasing dimensions can make the code more complex. For example, an array with three dimensions is structured as follows:

int array[3][4][5];
Accessing Elements in Multi-Dimensional Arrays
To retrieve a value from a multi-dimensional array, specify an index number for each dimension. For example, accessing the element in the first row (0) and third column (2) of an array named letters would be done like this:
cout << letters[0][2];
Note: Array indexing starts at 0, so the first element is at index [0], the second at [1], and so forth.
Modifying Elements in Multi-Dimensional Arrays
To change an element's value in a multi-dimensional array, reference the index number within each dimension. For example:
letters[0][2] = 'Z';
Iterating Through Multi-Dimensional Arrays
When iterating over a multi-dimensional array, you need a loop for each dimension. Below is an example of iterating over all elements in a two-dimensional array called letters:
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << letters[i][j] << " ";
}
}
For a three-dimensional array, you would add an additional loop:
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
for (int k = 0; k < z; ++k) {
cout << array[i][j][k] << " ";
}
}
}
Benefits of Multi-Dimensional Arrays
Multi-dimensional arrays are particularly useful for representing data structures like grids or matrices. They can be applied in various contexts, such as creating a representation of a Battleship game board using a two-dimensional array.