C++ Two dimensional or multidimensional Array

Two dimensional or multidimensional :  In the single dimensional array we can store only values in the form of list, but sometimes we needs to process the data in the form of rows and columns or we called it matrix. Then we use the two dimensional array.

 Syntax:            data-type array-name[ ][ ] = new data-type[2][2];

e.g       int  A[ ][ ] = new int [2][2];

 

Representation of the two dimensional array: The two dimensional array is stored like in the form of rows and columns.

The representation of 2*2 matrix:

Column 0         Column 1

 

Row 0       15              8          

[0][0]         [0][1]

Row 1       4               12

[1][0]          [1][1]

We can see how the elements are stored in the two dimensional array, and we have given the values and we can see their corresponding locations.

 

Initialization:

a.      Compile time: like the one dimensional array the initialization is almost same but we have to concentrate on the order of the row and columns.

e.g:            int A[2][2]={1,1,2,2}

the above array is of 2*2 means 2 rows and 2 columns. We can also initialize the values as follows:

int A[2][2]={{1,1},{2,2}};

b.      Run time: for run time initialization we have to take two variables, the first one for rows and another for columns.

Getting the values:

e.g:

for(i=0;i<2;i++)

{

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

{

A[i][j]=1;

}

}

Printing the values:

e.g:           

for(i=0;i<2;i++)

{

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

{

cout<<A[i][j];

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *