Earlier we have discussed Java Program to perform Matrix Addition, we’ll discuss about Java program to perform Matrix Multiplication. Matrix Multiplication is a mathematical operation in which we take two matrices arrays and perform multiplication between them to produce the resultant matrix array.

So how to do the Matrix Multiplication? What are the rules? The rule for multiplying two Matrices is the **Number of Columns of the First matrix must be equal to number of Rows in the Second matrix**.

### Java Program to perform Matrix Multiplication

import java.util.Scanner; class matrixMultiplication { public static void main(String args[]) { Scanner get = new Scanner(System.in); int m1=0, n1=0, m2=0, n2=0; System.out.println("Enter number of Rows in the first Matrix:"); m1 = get.nextInt(); System.out.println("Enter number of Columns in the first Matrix:"); n1 = get.nextInt(); System.out.println("Enter number of Rows in the Second Matrix:"); m2 = get.nextInt(); System.out.println("Enter number of Columns in the Second Matrix:"); n2 = get.nextInt(); if(n1==m2) { int first[][] = new int[m1][n1]; int second[][] = new int[m2][n2]; int result[][] = new int[m1][m2]; int sum=0; System.out.println("First Matrix Input:"); for(int i=0;i<m1;i++) { for(int j=0;j<n1;j++) { System.out.println("Enter "+(i+1)+" row "+(j+1)+" column Element:"); first[i][j] = get.nextInt(); } } System.out.println(); System.out.println("Second Matrix Input:"); for(int i=0;i<m1;i++) { for(int j=0;j<n1;j++) { System.out.println("Enter "+(i+1)+" row "+(j+1)+" column Element:"); second[i][j] = get.nextInt(); } } System.out.println(); System.out.println("Matrix Multiplication Result:"); for(int i=0;i<m1;i++) { for(int j=0;j<n1;j++) { for(int k=0;k<m2;k++) { sum = sum + first[i][k] * second[k][j]; } result[i][j] = sum; sum = 0; } } for(int i=0;i<m1;i++) { for(int j=0;j<m2;j++) { System.out.print(result[i][j]+"\t"); } System.out.println(); } } else { System.out.println("Multiplication is not possible"); } } }

Output:

{ 1 comment… read it below or add one }

Excellent website. Plenty of useful info here. I am sending it to a few buddies ans additionally sharing in delicious.And naturally, thank you for your sweat!