Latest :

Matrix Multiplication In Java – 4 Ways | Programs

Matrix Multiplication In Java – Here, we will discuss the various methods on how to multiply two matrices using Java. The compiler has been added so that you can execute the given programs yourself, alongside suitable examples and sample outputs.

  • Using For Loop
  • Using While Loop
  • Using Do-While Loop

How To Perform Matrix Multiplication:

Matrix multiplication is a simple binary operation that produces a single matrix from the entries of two given matrices. When two Matrices P & Q of order a*b and b*c are multiplied, the resultant matrix will be of the order a*c.

Here, the a entries across a row of P are multiplied with the b entries down a column of Q to produce the entry of PQ. The example given below explains the multiplication between two 2*2 matrices.

Matrix Multiplication In Java – Using For Loop 

1) Condition for multiplication of two matrices is -1st matrix column number equal to 2nd matrix row number.

2) Read row,column numbers of matrix1, matrix2 and check column number of matrix1= row number of matrix2. If condition is true then

a) Insert the elements at matrix1 using  two for loops:

  • for ( i= 0 ; i < r1 ; i++ )
  • for ( j= 0 ; j < c1 ;j++ )
  • Insert element at mat1[i][j].

b) Similarly insert the elements at matrix2 using  2 loops with the  structures  for (i=0;i<r2;i++ ),for (j= 0;j<c2;j++ ).


Using While Loop

1) Read row, column numbers of the two matrices and checks the column number of matrix1 =row number of matrix2.If condition true then insert the elements into the matrices using while loop.

2) a) Insert elements at matrix1-

  • While loop iterates until i <r1 condition is false.
  • then j initialized to 0.
  • while loop iterates until the condition j<c1 is true.
  • insert the element at mat1[i][j].
  • increase the j value.
  • Now i value increased.

b) Similarly insert elements at matrix2 with the conditions i<r2,j<c2.

2) For multiplication

  • while loop iterates until i<r1  is false.
  • j initialized to 0.
  • while loop iterates until j<c2 is false.
  • sum initialized to 0.
  • k=0.
  • while loop iterates until k<r2.
  • sum =sum+mat1[i][k]*mat2[k][j].
  • increases the k value.
  • insert sum value in to the resultant matrix at res[i][j].
  • increase the j value.
  • increase i value.

3) Print the matrix using while loops with the conditions i<r1, j<c2.


Using Do While Loop

1) Multiply two matrices mat1,mat2, res is the resultant matrix.

  • This loop iterates until k<r2 is false.
  • Insert sum in to the resultant matrix at res[i][j],increase j value, then checks the condition j<c2.
  • This loop iterates until j<c2 is false.
  • Increase the i value, then checks the condition i<r1.
  • This loop iterates until i<r1 is false.


Check Also

Merge Sort Java – Program 2 Ways | Sortings

Merge Sort Java –  Java program to implement merge sort using array & Buffered reader. ...