Java Program for Matrix Multiplication

Here you will get java program for matrix multiplication.

Suppose we have matrix A with number of rows and columns as m and n. Let B be a matrix with number of rows and columns as p and q. Their multiplication is possible only if number of columns of matrix A is equal to number of rows of matrix B i.e. n should be equal to p. The resultant matrix is of order mxq.

System.out.println("Enter number of rows and columns of first matrix:");

m=sc.nextInt();

n=sc.nextInt();

System.out.println("Enter number of rows and columns of second matrix:");

p=sc.nextInt();

q=sc.nextInt();

if(n!=p){

System.out.println("Multiplication can't be done");

}

else{

a=newint[m][n];

b=newint[p][q];

c=newint[n][p];

System.out.println("Enter elements of first matrix row wise:");

for(i=0;i<m;++i){

for(j=0;j<n;++j){

a[i][j]=sc.nextInt();

}

}

System.out.println("Enter elements of second matrix row wise:");

for(i=0;i<p;++i){

for(j=0;j<q;++j){

b[i][j]=sc.nextInt();

}

}

for(i=0;i<m;++i){

for(j=0;j<q;++j){

for(k=0;k<n;++k){

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

}

}

}

System.out.println("Matrix after multiplication:");

for(i=0;i<m;++i){

for(j=0;j<q;++j){

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

}

System.out.print("\n");

}

}

sc.close();

}

}

Output

Enter number of rows and columns of first matrix:22Enter number of rows and columns of second matrix:22Enter elements of first matrix row wise:4 56 7Enter elements of second matrix row wise:1 24 3Matrix after multiplication:24 23 34 33