Arrays

Java Program to Multiply Two Matrices

A Java program to multiply two matrices.

Problem Description

Write a Java program to multiply two matrices.

Code

MultiplyMatrices.java
public class MultiplyMatrices {
    public static void main(String[] args) {
        int r1 = 2, c1 = 3;
        int r2 = 3, c2 = 2;
        int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
        int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

        // 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("Product of two matrices is: ");
        for(int[] row : product) {
            for (int column : row) {
                System.out.print(column + "    ");
            }
            System.out.println();
        }
    }
}

Output

Product of two matrices is: 
24    29    
6    25    

Explanation

  1. Matrix Multiplication Rule: The number of columns in the first matrix must equal the number of rows in the second matrix.
  2. Triple Loop: Iterate through rows of the first, columns of the second, and the common dimension.