Multi-dimensional Arrays
Learn to use arrays of arrays in C++.
What is a multi-dimensional array
In C++, a multi-dimensional array is an array that contains other arrays as its values or members. The container array is termed an outer array, and the member array is termed an inner array. An array is said to be a multi-dimensional array if it has another array as its members. Can you think of some instances where we might have been using a structure same as a multi-dimensional array? One such example is a crossword puzzle!
Individual values in multi-dimensional arrays
The individual values in a multi-dimensional array are accessed through multiple index numbers used in the following format:
arrayname[row number][column number];
Let’s take the example of the following array:
int array1[2][3]= {
{10,12,14},
{16,18,20}
};
-
The
array1
is a two-dimensional array. -
The value
20
can be accessed asarray1 [ 1 ] [ 2 ]
. -
The number of indexes depends on the level of dimensions.
Note: The size of the outer array is optional while declaring a two-dimensional array. The size of the inner array is mandatory.
The general concepts of two-dimensional arrays, or n-dimensional arrays are implemented as follows in C++:
#include <iostream>using namespace std;int main(){int array[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}}; // Declaring a 2-dimensional arrayfor (int i = 0; i < 3; i++) // Printing a 2-dimensional array{for (int j = 0; j < 3; j++){cout << array[i][j] << " ";}cout << endl;}return 0;}
The following illustration shows the structure of the array above:
And here’s another example of the structure of a two-dimensional array:
#include <iostream>using namespace std;int main(){int array[3][2] = {{1,2}, {4,5}, {7,8}};for (int i = 0; i < 3; i++){for (int j = 0; j < 2; j++){cout << array[i][j] << " ";}cout << endl;}return 0;}
The following illustration shows the structure of the array above:
And here’s another example of a two-dimensional array with character elements:
#include <iostream>using namespace std;int main(){char array[3][2] = {{'A','B'}, {'C','D'}, {'E','F'}};for (int i = 0; i < 3; i++){for (int j = 0; j < 2; j++){cout << array[i][j] << " ";}cout << endl;}return 0;}
The following illustration shows the structure of the above array.
A mathematical matrix is implemented as a two-dimensional array in C++, as shown in the following example:
...