Cpp - Array Multidimensional Arrays

Introduction

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]; 

An example of a two-dimensional array is a chessboard.

int board[8][8]; 

Initializing Multidimensional Arrays

You can initialize multidimensional arrays with values.

Values are assigned to array elements in order. Here's an example:

int box[5][3] = { 1, 6, 7, 
                  1, 3, 0, 
                  1, 2, 1, 
                  1, 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].

Demo

#include <iostream> 
  
int main() /*from   ww w  .  ja  va2s . c  om*/
{ 
    int box[5][3] = { 1, 6, 7, 
                  1, 3, 0, 
                  1, 2, 1, 
                  1, 8, 9, 
                  0, 5, 2 }; 

    for (int i = 0; i < 5; i++) 
    { 
           for (int j = 0; j < 3; j++) 
           { 
                std::cout << "box[" << i << "]"; 
                std::cout << "[" << j << "] = "; 
                std::cout << box[i][j] << "\n"; 
           } 
    } 
}

Result

The box variable holds a two-dimensional array.

For the sake of 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} };