Example:
import java.util.Scanner;
class MatrixExample
{
int m,n,p,q;
int[][] a;
int[][]b;
int[][]c;
public void readData()
{
int i,j;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the order of the matrix A");
m=sc.nextInt();
n=sc.nextInt();
System.out.println("Enter the order of the matrix B");
p=sc.nextInt();
q=sc.nextInt();
if(n!=p)
{
System.out.println("matrix order mismatch for multiplication");
System.exit(0);
}
a=new int[m][n];
b=new int[p][q];
c=new int[m][q];
System.out.println("enter the elements of Matrix A");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
System.out.printf("a[%d][%d]=",i,j);
a[i][j]=sc.nextInt();
System.out.println("\n");
}
System.out.println("enter the elements of Matrix B");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
{
System.out.printf("b[%d][%d]=",i,j);
b[i][j]=sc.nextInt();
System.out.println("\n");
}
}
public void multiply()
{
for(int i=0;i<m;i++)
for(int j=0;j<q;j++)
{
c[i][j]=0;
for(int k=0;k<n;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
public void printMatrix()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<q;j++)
System.out.printf("%d\t",c[i][j]);
System.out.println("\n");
}
}
public static void main(String []args)
{
MatrixExample obj=new MatrixExample();
obj.readData();
obj.multiply();
System.out.println("The result of multiplication is ");
obj.printMatrix();
}
}
Output:
No comments:
Post a Comment