Question
Program to find product of two matrices
Two matrices can be multiplied if and only if The number of columns present in the first matrix should be equal to the number of rows present in the second matrix.
Matrix A = [9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Matrix B = [1, 2, 3]
[4, 5, 6]
[7, 8, 9]
PRODUCT OF TWO MATRICES
90 114 138
54 69 84
18 24 30
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class ProductOfTwoMatrices
{
public static void main(String[] args)
{
int row=0, col=0,rowb=0,colb=0,i=0,j=0,k=0;
int a[][],b[][],product[][];
boolean flag=true;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE ROW OF MATRIX A");
row=sc.nextInt();
System.out.println("ENTER THE COLUMN OF MATRIX A");
col=sc.nextInt();
System.out.println("ENTER THE ROW OF MATRIX B");
rowb=sc.nextInt();
System.out.println("ENTER THE COLUMN OF MATRIX B");
colb=sc.nextInt();
if(col!=rowb)
{
System.out.println("MATRICES CANNOT BE MULTIPLIED");
}
else
{
a=new int[row][col];
System.out.println("ENTER THE ELEMENTS IN MATRIX A");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
a[i][j]=sc.nextInt();
}
}
b=new int[rowb][colb];
System.out.println("ENTER THE ELEMENTS IN MATRIX B");
for(i=0;i< rowb;i++)
{
for(j=0;j< colb;j++)
{
b[i][j]=sc.nextInt();
}
}
product=new int[row][colb];
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
for(k=0;k< rowb;k++)
{
product[i][j]=product[i][j]+ a[i][k] * b[k][j];
}
}
}
System.out.println("Product of two matrices: ");
for(i = 0; i < row; i++)
{
for(j = 0; j < colb; j++)
{
System.out.print(product[i][j] + " ");
}
System.out.println();
}
}
}
}