A multidimensional array is an array that is more than just a single row of elements. It may have rows & columns, as in a 2D array, or may have 3D . All elements must be of the same data type. C++ starts counting at zero for the indexes of arrays.In C++, we can create an array of an array, known as a multidimensional array.
Syntax :
data_type array_name[size1][size2]....[sizeN];
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size a,b you would write something as follows −
data_type array_name [ a ][ b ];
For example :
int x[3][4];
In the Example shown above x is 2D array of data type int and It can hold a
maximum of 12 elements.
3D arrays also work in a similar way.
For example:
float x[3][4][6];
This array x can hold a maximum of 72 elements.
In order to find out the total number of elements in an array just simply multiply its dimensions: we have 72 see below.
3 * 4 * 6 = 72
A Multidimensional Array can be initialize in more than one way.
int my array[2][3];
Method 1:
int arr[2][3] = {4,7,9,11,16,19};
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
int arr[2][3] = {{4,7,9} , {11,16,19}};
Accessing array elements:
arr[0][0] – first element arr[0][1] – second element arr[0][2] – third element arr[1][0] – fourth element arr[1][1] – fifth element arr[1][2] – sixth element
Example: Two dimensional array in C++
#include <iostream>
using namespace std;
int main() {
int arr[2][3] = {{4,7,9}, {11,16,19}};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3 ; j++) {
cout << "arr[" << i << "][" << j << "]:
" << arr[i][j] << endl;
}
}
return 0;
}
Output:
arr[0][0]: 4 arr[0][1]: 7 arr[0][2]: 9 arr[1][0]: 11 arr[1][1]: 16 arr[1][2]: 19
int my array[2][3][2];
Initialization : We have many ways to initialize arrays.
Method 1:
int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};
Method 2:
int arr[2][3][2] =
{
{ {11,-11}, {12, -12}, {13, -13}},
{ {14, -14}, {15, -15}, {16, -16}}
}
Example:
#include <iostream>
using namespace std;
int main() {
// initializing the array
int arr[2][3][2] = { { {11,-11}, {12,-12}, {13,-13} },
{ {14,-14}, {15,-15}, {16,-16} }
};
// displaying array values
for (int p = 0; p < 2; p++) {
for (int q = 0; q < 3; q++) {
for (int r = 0; r < 2; r++) {
cout << arr[p][q][r] << " ";
}
}
}
return 0;
}
Output:
11 -11 12 -12 13 -13 14 -14 15 -15 16 -16