JAVA- Two dimensional or multidimensional Array

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++)

{

System.out.println(A[i][j]);

}

}

Program:

//PROGRAM TO PERFORM MULTIPLICATION OF TWO MATRICES

class Multiplication

{

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

int[ ][ ] b={{1,1},{4,5},{3,4},{2,8}};

int[ ][ ] c={{0,0},{0,0}};

int i,j,k;

void calculate( )

{

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

{

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

{

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

{

c[i][k]=c[i][k]+a[i][j]*b[j][k];

}

}

}

}

void show( )

{

System.out.println(“Multiplication of two matrices is: “);

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

{

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

{

System.out.print(” “+c[i][j]);

}

System.out.println( );

}

}

}

class Execute

{

public static void main(String s[ ])

{

Multiplication m= new Multiplication( );

m.calculate( );

m.show( );

}

}

Leave a Reply

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