What is a Multidimensional Array?
A multidimensional array is an array of arrays. It allows you to store data in a tabular or matrix-like
structure. The most common type of multidimensional array is the 2-dimensional (2D) array, which can be
visualized as a table with rows and columns.
Example of a 2D Array:
A 2D array with 3 rows and 3 columns:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
In this case, the 2D array matrix can be visualized as:
1 2 3
4 5 6
7 8 9
Each element is accessed using two indices: one for the row and one for the column.
Declaration of Multidimensional Arrays
The syntax for declaring a multidimensional array is similar to that of a 1D array, except that you specify
multiple sets of square brackets for the dimensions.
Syntax:
data_type array_name[size1][size2]...[sizeN];
For a 2D array (matrix) with 3 rows and 4 columns:
int matrix[3][4]; // 3 rows, 4 columns
For a 3D array with dimensions 3x3x3:
int cube[3][3][3];
Initialization of Multidimensional Arrays
You can initialize multidimensional arrays at the time of declaration, either by listing out all the elements or
specifying the elements for each sub-array (row).
Example of Initializing a 2D Array:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
This creates a 2x3 matrix:
1 2 3
4 5 6
You can also initialize a 2D array without specifying all the elements:
int matrix[2][3] = {1, 2, 3}; // First row: {1, 2, 3}, Second row: {0, 0, 0}
Accessing Elements in a Multidimensional Array
Each element in a multidimensional array is accessed by specifying the indices for each dimension. For a
2D array, the first index specifies the row, and the second index specifies the column.
Syntax:
array_name[row_index][column_index];
For example, to access the element in the 2nd row and 3rd column of the following array:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
You would use:
int value = matrix[1][2]; // Accessing the value in the 2nd row and 3rd column (value = 6)
Multidimensional Arrays and Loops
Multidimensional arrays are often used with nested loops to traverse or manipulate elements. The outer
loop controls the row index, and the inner loop controls the column index.
Example of Traversing a 2D Array:
for (int i = 0; i < 3; i++) { // Loop through rows
for (int j = 0; j < 3; j++) { // Loop through columns
cout << matrix[i][j] << " ";
}
cout << endl;
}
This would output:
123
456
789
Memory Layout of Multidimensional Arrays
In C++, arrays are stored in row-major order. This means that the elements of each row are stored
consecutively in memory.
For example, consider the following 2D array:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
In memory, the elements would be laid out as:
1 2 3 4 5 6