Write a program to multiply two matrices and check the eligibility for matrix multiplication
Answers
I hope this will help you
if not then comment me
Answer:
import java.util.*;
class Multiply_matrix
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter m, n, p and q");
int m=sc.nextInt();
int n=sc.nextInt();
int p=sc.nextInt();
int q=sc.nextInt();
int a[][]=new int[m][n];
int b[][]=new int[p][q];
int g[][]=new int[m][q];
int s=0,f;
System.out.println("Enter "+(m*n)+" elements");
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
a[i][j]=sc.nextInt();
System.out.println("Enter "+(p*q)+" elements");
for(int i=0;i<p;i++)
for(int j=0;j<q;j++)
b[i][j]=sc.nextInt();
System.out.println("ARRAY 1:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
System.out.println("ARRAY 2:");
for(int i=0;i<p;i++)
{
for(int j=0;j<q;j++)
System.out.print(b[i][j]+" ");
System.out.println();
}
if(n!=p)
System.out.println("Matrices cannot be multiplied");
else
{
int i=0,j=0,l=0;
for(int k=0;k<m;k++)
{
f=0;
l=0;
for(int t=0;t<(p*q);t++)
{
s+=a[k][l]*b[l][f];
if((t+1)%p==0)
{
g[i][j]=s;
s=0;
f++;
if(j==q-1)
{
i++;
j=0;
}
else
j++;
}
if(l==n-1)
l=0;
else
l++;
}
}
}
System.out.println("Product of matrices= ");
for(int i=0;i<m;i++)
{
for(int j=0;j<q;j++)
System.out.print(g[i][j]+" ");
System.out.println();
}
}
}