Arrays can be made multi-dimensional by adding more sets of square brackets. It can be two dimensional or three dimensional. The data is stored in tabular form (row ∗ column) which is also known as matrix.
A two dimensional array of data, is with one dimension representing each row and the second dimension representing each column. A three-dimensional array could be a cube, with one dimension representing width, a second dimension representing height, and a third dimension representing depth. We can even have arrays of more than three dimensions but they are more complex,
When you declare arrays, each dimension is represented as a subscript in the array.
A two-dimensional array has two subscripts.
int grid[5, 13];
A three-dimensional array has three subscripts.
int cube[5, 13, 8];
Let's see a simple example of multidimensional array in C++ which declares, initializes and traverse two dimensional arrays.
#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}You can initialize multidimensional arrays with values just like single-dimension arrays. Values can either be filled in one at a time or all at once during the declaration.
Here’s an example:
int box[5][3] = { 8, 6, 7, 5, 3, 0, 9, 2, 1, 7, 8, 9, 0, 5, 2 };The first value is assigned to box[0][0], the second to box[0][1], and the third to box [0][2]. The next value is assigned to box[1][0], then box[1][1] and box[1][2].
Let's see a simple example of multidimensional array which initializes array at the time of declaration.
#include <iostream>
using namespace std;
int main()
{
int test[3][3] =
{
{2, 5, 5},
{4, 0, 3},
{9, 1, 8} }; //declaration and initialization
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}To have more clarity, you could group the initializations with braces, organizing each row on its own line.
int box[5][3] = {
{8, 6, 7},
{5, 3, 0},
{9, 2, 1},
{7, 8, 9},
{0, 5, 2} };The compiler ignores the inner braces. This makes it easier to see how the numbers are distributed. Each value must be separated by a comma without regard to the braces. The entire initialization set must be within braces, and it must end with a semicolon.
