Write a java program to perform multiplication(product) of two matrices.

 

Write a java program to perform multiplication(product) of two matrices.


Program:

import java.util.*;
public class matrixmul
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the row and columns for matrix A:");
int r1=sc.nextInt();
int c1=sc.nextInt();
System.out.println("Enter the row and columns for matrix B:");
int r2=sc.nextInt();
int c2=sc.nextInt();
int i, j, k;
int a[ ][ ]=new int[r1][c1];
int b[ ][ ]=new int[r2][c2];
int c[ ][ ]=new int[r1][c2];
if(c1!=r2)
System.out.println("Matrix multiplication is not possible");
else
{
System.out.println("Enter the elements for matrixA:");
for(i=0;i<r1;i++)
{ for(j=0;j<c1;j++)

{
a[i][j]=sc.nextInt();
}
}
System.out.println("Enter the elements for matrix B:");
for(i=0;i<r2;i++)
{ for(j=0;j<c2;j++)
{
b[i][j]=sc.nextInt();
}
}
//matrix multiplication
for(i=0;i<r1;i++)
{ for(j=0;j<c2;j++)
{ c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}

System.out.println("Resultant matrix is:");
for(i=0;i<r1;i++)
{ System.out.println();
for(j=0;j<c2;j++)
{
System.out.print(c[i][j]+"\t");
}
}
}
}
}


Output :


Enter the row and columns for matrix A:
2   2
Enter the row and columns for matrix B:
2   2
Enter the elements for matrixA:
1    2
3    4
Enter the elements for matrix B:
5     6
7     8
Resultant matrix is:
19   22
43   50


Or


Enter the row and columns for matrix A:
2   3
Enter the row and columns for matrix B:
2   2
Matrix multiplication is not possible.


Description :

If the order of matrix A is r1 x c1 and of matrix B is r2 x c2 (number of
columns of A = number of rows of B = c1=r2), then the order of matrix C is r1 x c2,
where C = A x B otherwise matrix multiplication is not possible. First accept number of
rows and columns of matrix A into r1, c1 then accept number of rows and columns of
matrix B into r2, c2. If c1 is not equal to r2 then display a message matrix multiplication
is not available otherwise accept two matrices into two arrays and perform the
multiplication operation and store the result in another array and display the same as result.

Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Abstract classes and Abstract methods in Java with Examples rcub.

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.