Matrix.java
import java.util.*;
class Matrix{
public static void main(String args[])throws Exception
{
Scanner s=new Scanner(System.in);
int r1,r2,c1,c2;
System.out.println("Enter row and column for matrix1:");
r1=s.nextInt();
c1=s.nextInt();
int[][] m1=new int[r1][c1];
System.out.println("Enter the elements of first matrix");
for(int i=0;i < r1;i++)
{
for(int j=0;j < c1;j++)
{
m1[i][j]=s.nextInt();
}
}
System.out.println("Enter row and column for matrix2:");
r2=s.nextInt();
c2=s.nextInt();
if(c1!=r2)
{
System.out.println("Matrix multiplication is not possible");
}
else
{
int m2[][] = new int[r2][c2];
int multiply[][] = new int[r1][c2];
int sum=0;
System.out.println("Enter the elements of second matrix");
for(int i=0;i < r2;i++)
{
for(int j=0;j < c2;j++)
{
m2[i][j]=s.nextInt();
}
}
for(int i=0;i < r1;i++)
{
for(int j=0;j < c2;j++)
{
for(int k=0;k < r2;k++)
{
sum=sum+m1[i][k]*m2[k][j];
}
multiply[i][j] = sum;
sum = 0;
}
}
System.out.println("multiplication of m1*m2 matrices:");
System.out.println("--------------------------------");
for (int i=0;i < r1;i++)
{
for (int j=0;j < c2;j++)
System.out.print(multiply[i][j]+"\t");
System.out.print("\n");
}
}
}
}
OUTPUT
javac Matrix.java java Matrix Enter row and column for matrix1: 3 3 Enter the elements of first matrix 1 2 3 4 5 6 7 8 9 Enter row and column for matrix2: 3 3 Enter the elements of second matrix 9 8 7 6 5 4 3 2 1 multiplication of m1*m2 matrices -------------------------------- 30 24 18 84 69 54 138 114 90
Comments
Post a Comment