C++ Multi-dimensional Array

In the previous topic we have learnt about the basic concepts of array in C++. In this tutorial we are looking for another type of an array called multi-dimensional array.

C++ Multi-dimensional Array :

In C++ we can create multidimensional array.Syntax to create multidimensional array is as below -

data-type name[size1][size2]...[sizeN];

Suppose we need to create the 2-dimensional array then we can declare it as -

int mat[5][4];

The above 2-dimensional array consists of the 5 rows and 4 columns.

Two-Dimensional Arrays:

  1. Simplest form of the multidimensional array is the two-dimensional array.
  2. 2-dimensional array is also called as matrix or table.
  3. 2-dimensional array has 2 dimensions.
  4. First dimension represents the number of row
  5. Second dimension represents the number of columns.

Example of 2-dimensional array :

Consider the 2-dimensional array of size x,y then we can declare it like

data_type nameOfArray [ x ][ y ];

where -

  • data_type will be any valid C++ data type
  • nameOfArray will be name of 2-dimensional array.
  • x will be number of rows
  • y will be number of columns

Representation :

two_dimensional_arrays

Cell LocationMeaning
a[0][0]0th Row and 0th Column
a[0][1]0th Row and 1st Column
a[0][2]0th Row and 2nd Column
a[0][3]0th Row and 3rd Column
a[1][0]1st Row and 0th Column
a[1][1]1st Row and 1st Column
a[1][2]1st Row and 2nd Column
a[1][3]1st Row and 3rd Column
a[2][0]2nd Row and 0th Column
a[2][1]2nd Row and 1st Column
a[2][2]2nd Row and 2nd Column
a[2][3]2nd Row and 3rd Column

Two-Dimensional Array : Summary with Sample Example

Summary PointExplanation
No of Subscript Variables Required2
Declarationa[3][4]
No of Rows3
No of Columns4
No of Cells12
No of for loops required to iterate2

Initializing the 2-D array :

int a[3][2] = {
    { 1 , 4 },  /*Initialize 0th row*/
    { 5 , 2 },  /*Initialize 1st row*/
    { 6 , 5 }   /*Initialize 2nd row*/
};

We can alternatively declare it as -

int a[3][2] = {1,4,5,2,6,5};