Explain about two-dimensional array in detail

Estudies4you
Q25. Explain about two-dimensional array in detail.
Answer :

Two-dimensional Array
Two-dimensional array is an array which stores data in the form of a matrix.
Syntax
datatype array_name [row-size] [column-size];
Declaration of Two-dimensional Arrays
The general format of declaring a two-dimensional array is,
type array_name[row-size][column-size];
Where ‘type’ represents the data type of array elements, ‘array_name’ is the name of the array, ‘row-size’ specifies the number of rows in the array and ‘column-size’ specifies number of columns in the array. Both row-size and column-size must be integer constants.
Examples
1. int xyz[2][5];
Here, xyz is an array consisting of two rows with each row consisting of 5 integer elements.
2 float a[5][5];
Here, a.is an array consisting of 5 rows with each row consisting of 5 floating point numbers.
Initialization of Two-dimensional Array Elements
Two-dimensional arrays can also be initialized at the place of declaration itself.
Syntax
type array_name[row-size][column-size]
  = { {list of elements in row 1}, {list of elements in row 2}, -----, {list of elements in row n}};

Examples
1. int xyz[2][3] = {{2, 3, 4}, {5, 6, 7}
Here 2, 3 and 4 are assigned to three columns of first row and 5, 6, 7 are assigned to three columns of second row in order.
If the values are missing in initialization, they are set to garbage values.
2. int xyz[2][3] = {{0}, {0}};
Here, first element of each row is initialized to zero while other elements have some garbage values.
Accessing of Two-dimensional Array Elements:
The elements of two-dimensional array can be accessed using two subscripts, i.e., row and column.
Syntax
data_type array_name [row_size] [column_size]; :
Example
int a[5][3];
The above declaration represents a two-dimensional array consisting of 5 rows and 3 columns. So, the total number of elements which can be stored in this array are 5 x 3 i.e., 15.
The representation of two-dimensional array of size 5 x 3 in the memory is shown below,

Program
#include<iostream.h>
#include<conio.h>
void main( )
{
int rl, cl, r2, 2, i, j, k;
int a[10][10], b[10][10], c[10][10];
clrscr( );
cout<<“\n Enter the order of first matrix:”;
cin>>r1>> cl;
cout<<“\n Enter the order of second matrix:”;
cin>>r2>> c2; ;
cout<<“Enter elements of first matrix:”;
for(i =0; i<rl; i+)
{
for(j = 0; j<cl; j++)
{
cin>>a[i][j];
}
}
cout<<“\n Enter elements of second matrix:”;
for(i =0; i< 12; i++)
{
for(j = 0; j<c2;j++)
{
cin>>b[i][j];
}
}/*Matrix multiplication */
if(cl == 12)
{
for(i=0;i<r2;i++)
{
for(j = 0; j <2; j++)
{
c[i][j] = 0;
for(k = 0; k<r2; k++)
c[i][j] = c[i][j] + a[i][k] * b[i][k];
}
}
cout<<“The multiplication of two matrices is:\n”;
for(i = 0; i <rl; i++)
{
cout<<endl;
for(j = 0; j <cl; j++)
{
cout<< c[i][j];
cout<<" ";
}
}
}
else
cout<<“\n Multiplication not possible”;
getch();
}


Output

To Top