A multi-dimensional array is simply an array of arrays. A two-dimensional array is an array of arrays, whereas a three-dimensional array is an array of arrays of arrays. These arrays have to be restricted to one data type. A two-dimensional array can be pictured as a table of rows and columns.
data_type name[size1][size2]...[sizeN];
//2d array with 5 rows and 4 columns:
int score[5][4];
//3d array:
int score [2][2][3];
The following is a visual representation of a one-dimensional array:
The arrays can also be initialized at declaration. For example, the following code initializes the 1-D, 2-D and 3-D arrays. The elements can be accessed through indexing, i.e, rows and columns start from 0. The element in the first row and the first column can be indexed through array_name[0][0]
. The element in the first row and second column can be accessed by array_name[0][1]
, and so on.
The first part of the code shows how arrays can be initialized. It is not important to assign values to the array at this point as long as the size of the array is declared.
The code prints the two arrays using for
loops. A nested for
loop is needed to print the 2-D array with the first loop running up to the
#include <iostream>using namespace std;int main(){int one_dim[5] = {1,2,3,4,5}; //specifying the size (5 in this case) is not important if you are initializingint two_dim [3][2] = { {1,2}, {3,4}, {5,6} };int three_dim [2][3][2] = {{ {10,11}, {12,13}, {14,15} },{ {16,17}, {18,19}, {20,21} }};cout<<"printing one-dimensional array: ";for(int i =0;i <5; i++){cout<<"\t"<<one_dim[i];}cout<<endl;cout<<"printing the two-dimensional array: "<<endl;for(int i = 0; i<3 ; i++) //num of rows{for(int j =0 ; j<2; j++) //num of cols{cout<<two_dim[i][j]<<"\t";}cout<<endl;}return 0;}