C++ Multidimensional arrays
A multidimensional array in C++ is an array of arrays, where each component of the primary array is an array in its own right. Two-dimensional, three-dimensional, and even more dimensional multidimensional arrays are possible.
Syntax of multidimensional array:
data_type array_name[row_size][column_size];
For example, the following code declares and initializes a 2D array named matrix:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
With the elements initialised to the values in the initializer list, this generates a 2D array with three rows and three columns.
In a multidimensional array, you must supply the element’s row and column indices in order to access it. For instance, you would write the following to access the element in the matrix array’s second row and third column:
int element = matrix[1][2]; // row index 1, column index 2
You can also use nested loops to iterate through the elements of a multidimensional array. For example, the following code prints out all the elements of the matrix array:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
The matrix array’s elements are iterated through and printed out using a nested loop in this code. While the inner loop iterates over columns, the outer loop iterates over rows.
You can declare and utilize arrays of more than two dimensions, such as 3D arrays, 4D arrays, and so forth, in addition to 2D arrays. With the addition of additional pairs of square brackets for each additional dimension, the syntax for declaring multidimensional arrays with more than two dimensions is similar to that of 2D arrays.
Example:
#include <iostream>
using namespace std;
int main() {
// declare and initialize a 2D array
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// access the elements of the array using nested loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12