Two dimension array (2-D): – It is also called as matrix. There are two subscript associated with variable name. The first subscript is dedicated for row and second subscript is dedicated for column.

The total elements of 2-D array is calculated by Row Size * Column Size.

Declaration of 2-D array –

Syntax: –

                Data_Type Array_Variable[Row_Size][Column_Size];

Ex: –

                int a[3][4];
                char ch[4][10];
                float f[3][2];

Initialization of 2-D array: –

Case (1) – Initialization during declaration

Syntax: –

                Data_Type Array_Variable[Row_Size][Column_Size]={Values};

Ex: –

                int a[3][4]={10,11,12,13,6,7,8,9,51,52,53,54};
                                Or
                int a[3][4]={{10,11,12,13},{6,7,8,9},{51,52,53,54}};
                                Or
                int a[3][4]={{10,11,12},{6,7},{51,52,53,54}};

Case (2.A) –

                int a[3][4];
                a[0][0]=10;
                a[1][0]=20;
                a[0][2]=30;
                a[2][0]=40;

Case (2.B) – For dynamic initialization

                int a[3][4],i,j;
                for(i=0;i<3;i++)                  //outer for loop for row
                                {
                                for(j=0;j<4;j++)                 //inner for loop for column
                                                {
                                                cout<<”Enter value of a[“<<i<<”][“<<j<<”] = “;
                                                cin>>a[i][j];
                                                }
                                }

Note: – If at the time of 2-D declaration, we are initializing to them then the row size is option to give.

                int a[][4]={10,11,12,13,6,7,8,9,51,52,53,54};

Row=Number of Element/Column

Advertisements