Matrix Multiplication Using Arrays in Java

Exercise:

Write a Java Program to multiply two matrices using multi-dimensional arrays.

Click Here to View the Solution!
public class MatriceMultiplication {
  
     public static void main(String[] args) {
         int r1 = 2, c1 = 3;
         int r2 = 3, c2 = 2;
         int[][] firstMatrix = { {4,1,7}, {4,5, 4} };
         int[][] secondMatrix = { {1,3}, {-8, 0}, {0, -6} };
  
         // Mutliplying Two matrices
         int[][] product = new int[r1][c2];
         for(int i = 0; i < r1; i++) {
             for (int j = 0; j < c2; j++) {
                 for (int k = 0; k < c1; k++) {
                     product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
                 }
             }
         }

        // Displaying the result
         System.out.println("Sum of two matrices is: ");
         for(int[] row : product) {
             for (int column : row) {
                 System.out.print(column + "    ");
             }
             System.out.println();
         }
     }
 } 
Click Here to View the Output!
Sum of two matrices is: 
 -4    -30    
 -36    -12   
Click Here to View the Explanation!
  • The program given here describes the multiplication operation between two matrices with a resultant matrix as follows:

 (a11 x b11) + (a12 x b21) + (a13 x b31)    (a11 x b12) + (a12 x b22) + (a13 x b32)  

 (a21 x b11) + (a22 x b21) + (a23 x b31)    (a21 x b12) + (a22 x b22) + (a23 x b32)

  • Placing the values in the above matrix as per the example, results in:

(4 x 1) + (1 x -8) + (7x 0) = -4    (4 x 1) + (1 x 0) + (7 x 4) = -30   

(4 x 1) + ( 5 x -8) + (4 x 0) = -36     (4 x 3) + ( 5 x 0) + (4 x -6) = -12