Write a Java program to Multiply two given matrices.

Program Code in JAVA:
import java.io.*;
class Matrix
{
int a[5][5],b[5][5],c[5][5];
int i,j,k,m,n,p,q;
DataInputStream dis=new DataInputStream(System.in);
void readA()
{
try
{
System.out.println("Enter the Size of Matrix A (Rows and Columns) ");
m=Integer.parseInt(dis.readLine());
n=Integer.parseInt(dis.readLine());
a=new int[m][n];
System.out.println("Enter the Matrix A values:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j]=Integer.parseInt(dis.readLine());
}
catch(Exception e){}
}
void readB()
{
try
{
System.out.println("Enter the Size of Matrix B (Rows and Columns) ");
p=Integer.parseInt(dis.readLine());
q=Integer.parseInt(dis.readLine());
b=new int[p][q];
System.out.println("Enter the Matrix A values:");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
b[i][j]=Integer.parseInt(dis.readLine());
}
catch(Exception e){}
}
void printA()
{
System.out.println("Matrix A \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println(" ");
}
}
void printB()
{
System.out.println("Matrix B \n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
}
System.out.println(" ");
}
}
void mulAB()
{
c=new int[m][q];
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<p;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
void printC()
{
System.out.println("Matrix Multiplication is \n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println(" ");
}
}
}
class MatrixMul
{
public static void main(String[] args) throws Exception
{
Matrix mat=new Matrix();
mat.readA();
mat.readB();
if(mat.n==mat.p)
{
mat.printA();
mat.printB();
mat.mulAB();
mat.printC();
}
else
System.out.println("Matrix Multiplication is Not Possible");
}
}



Program Output:
c:\java>javac MatrixMul.java
c:\java>java MatrixMul
Enter the Size of Matrix A (Rows and Columns)
2
2
Enter the Matrix A values:
1 2
1 2
Enter the Size of Matrix B (Rows and Columns)
2
2
Enter the Matrix A values:
2 1
2 1
Matrix A
1 2
1 2
Matrix B
2 1
2 1
Matrix Multiplication is
6 3
6 3
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: