You are here

Java program to multiply two matrices

Java program to multiply two matrices: before multiplication matrices are checked whether they can be multiplied or not. We will use the simplest method of multiplication, there are more efficient algorithms available. Also this approach isn't recommended for sparse matrices which contains a large number of elements as zero.

Java programming 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. }

Output of program:
Java matrix multiplication program.

Download Matrix multiplication program class file.