Monday, March 6, 2017

Java Program to Multiply two Matrices

In this article i will you how to write a matrix multiplication program in Java. As a fresh graduate and for student this program feels difficult to understand. Here is our program in easy way. Take a look

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:




See also:

Java Program to Print Prime numbers between 1 to 100
Basic Java Programs

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...