Question

# Multiply two integer matrices and print both the original matrices and resultant matrix.

```				```
Enter Row size of 1st matrix:
2
Enter Column size of 1st matrix:
3
Enter Row size of 2nd matrix:
3
Enter Column size of 2nd matrix:
4
Enter Elements in First Matrix:
1
2
3
4
5
6
Enter Elements in Second Matrix:
1
2
3
4
5
6
7
8
9
10
11
12
Matrix 1:
1 2 3
4 5 6
Matrix 2:
1 2 3 4
5 6 7 8
9 10 11 12
Matrix 1 * Matrix 2:
38 44 50 56
83 98 113 128
```
```

# Share code with your friends

Code

```				```
import java.util.Scanner;
public class MatrixMultiplication
{
public static void main()
{
int[ ][ ] matrix1,matrix2,ProductOfFirstAndSecondMatrix;
int row1,col1,row2,col2,product,sum=0;
int i,j,k;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Row size of 1st matrix:");
row1=sc.nextInt();
System.out.println("Enter Column size of 1st matrix:");
col1=sc.nextInt();
System.out.println("Enter Row size of 2nd matrix:");
row2=sc.nextInt();
System.out.println("Enter Column size of 2nd matrix:");
col2=sc.nextInt();
if(col1!=row2)
{
System.out.println("Column of the First matrix should be equal to row of second matrix");
}
else
{
matrix1=new int[row1][col1];
matrix2=new int[row2][col2];
ProductOfFirstAndSecondMatrix=new int[row1][col2];
System.out.println("Enter Elements in First Matrix:");
for(i=0;i< row1;i++)
{
for(j=0;j< col1;j++)
{
matrix1[i][j]=sc.nextInt();
}
}
System.out.println("Enter Elements in Second Matrix:");
for(i=0;i< row2;i++)
{
for(j=0;j< col2;j++)
{
matrix2[i][j]=sc.nextInt();
}
}

for(i=0;i< row1;i++)
{
for(j=0;j< col2;j++)
{
k=0;
while(k< col1)
{
product=matrix1[i][k]*matrix2[k][j];
sum=sum+product;
k++;
}
ProductOfFirstAndSecondMatrix[i][j]=sum;
sum=0;
}

}

System.out.println("Matrix 1:");
for(i=0;i< row1;i++)
{
for(j=0;j< col1;j++)
{
System.out.print(matrix1[i][j]+" ");

}
System.out.println();
}

System.out.println("Matrix 2:");
for(i=0;i< row2;i++)
{
for(j=0;j< col2;j++)
{
System.out.print(matrix2[i][j]+" ");

}
System.out.println();
}
System.out.println("Matrix 1 * Matrix 2:");
for(i=0;i< row1;i++)
{
for(j=0;j< col2;j++)
{
System.out.print(ProductOfFirstAndSecondMatrix[i][j]+" ");

}
System.out.println();
}
}
}
}

```
```

Sale

50
Sale

150
Sale

200
Sale

50
Sale

50
Sale

50
Sale

50
Sale

50
Sale

50