Java Program to Multiply Two Matrices

Study this program to get a sense of how to manipulate two-dimensional arrays.

This program multiplies two matrices. Before multiplication, the matrices are checked to see whether they can be multiplied or not. It uses the simplest method of multiplication, but note that there are more efficient algorithms available. This approach isn't recommended for sparse matrices that contain a large number of 0 elements.

 

The Code:

  1. import java.util.Scanner;
  2.  
  3. class MatrixMultiplication
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int m, n, p, q, sum = 0, c, d, k;
  8.  
  9.       Scanner in = new Scanner(System.in);
  10.       System.out.println("Enter the number of rows and columns of first matrix");
  11.       m = in.nextInt();
  12.       n = in.nextInt();
  13.  
  14.       int first[][] = new int[m][n];
  15.  
  16.       System.out.println("Enter elements of first matrix");
  17.  
  18.       for (c = 0; c < m; c++)
  19.          for (d = 0; d < n; d++)
  20.             first[c][d] = in.nextInt();
  21.  
  22.       System.out.println("Enter the number of rows and columns of second matrix");
  23.       p = in.nextInt();
  24.       q = in.nextInt();
  25.  
  26.       if (n != p)
  27.          System.out.println("The matrices can't be multiplied with each other.");
  28.       else
  29.       {
  30.          int second[][] = new int[p][q];
  31.          int multiply[][] = new int[m][q];
  32.  
  33.          System.out.println("Enter elements of second matrix");
  34.  
  35.          for (c = 0; c < p; c++)
  36.             for (d = 0; d < q; d++)
  37.                second[c][d] = in.nextInt();
  38.  
  39.          for (c = 0; c < m; c++)
  40.          {
  41.             for (d = 0; d < q; d++)
  42.             {  
  43.                for (k = 0; k < p; k++)
  44.                {
  45.                   sum = sum + first[c][k]*second[k][d];
  46.                }
  47.  
  48.                multiply[c][d] = sum;
  49.                sum = 0;
  50.             }
  51.          }
  52.  
  53.          System.out.println("Product of the matrices:");
  54.  
  55.          for (c = 0; c < m; c++)
  56.          {
  57.             for (d = 0; d < q; d++)
  58.                System.out.print(multiply[c][d]+"\t");
  59.  
  60.             System.out.print("\n");
  61.          }
  62.       }
  63.    }
  64. }


The Output:

Java matrix multiplication program.

 


Source: https://www.programmingsimplified.com/java/source-code/java-program-multiply-two-matrices
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 3.0 License.

Last modified: Thursday, April 18, 2019, 3:09 PM