Multi – Dimensional Array in C++

Written by

Vaaruni Agarwal

We have read about arrays and how can we declare them in C++. But, so far we have focused only on the one-dimensional arrays, now we will take a look at the multidimensional arrays in C++.

We can create an array of innumerable dimensions in C++, however, arrays having more than 3 – dimensions are considered tedious and are hard to manage. 

So, as we talk about arrays having the multiple dimensions, our major focus will be on, the 2 – dimensional arrays.

A 2 – dimensional array forms a matrix, which can be used to perform various matrix operations in C++. 

 

Declaring a multidimensional array:

Here is the general form of a multidimensional array declaration −

Syntax:

type name[size 1][size 2]...[size N];

For example:

The following declaration creates a two-dimensional integer array −

int dim[3][3];

This integer array will have three rows and three columns.

A two-dimensional array can be thought of as a table, which will have x number of rows and y number of columns

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

 

Initializing Multi-Dimensional Arrays:

Multi dimensioned arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {  

   {0, 1, 2, 3} ,   /* initializers for row indexed by 0 */

   {4, 5, 6, 7} ,   /* initializers for row indexed by 1 */

   {8, 9, 10, 11}   /* initializers for row indexed by 2 */

};

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example −

 

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing elements in a multidimensional array:

Following program is used to access the elements of a two-dimensional array.

#include <iostream.h>

int main () {

   // an array with 5 rows and 2 columns.

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

 

   // output each array element's value                      

   for ( int i = 0; i < 5; i++ )

      for ( int j = 0; j < 2; j++ ) {

      

         cout << "a[" << i << "][" << j << "]: ";

         cout << a[i][j]<< endl;

      }

 

   return 0;

}

Multi &#8211; Dimensional Array in C++