Java Program to Multiply 2 matrices

In this program we will take three level nested loop is used to perform the multiplication.First, you have to ask the user to enter the number of rows and columns of the first matrix and then ask to enter the first matrix elements.Again ask the same for the second matrix. Then multiply two matrices and store the multiplication result inside the any variable say res and then print all the matrices as a result


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

Basics of CPP Programs

In this post you will learn fundamental C++ programs. These programs for freshers or beginners. 1 .write a cpp program to display hello w...