Java Program To Multiplication Of Two Matrices

01. Example:

import java.util.Scanner;

class multiplicationOfMatrices {
   public static void main(String args[]) {

      int m, n, p, q, sum = 0, c, d, k;

      Scanner input = new Scanner(System.in);
      System.out.print("Enter First Matrix Number Rows And Columns: ");
      m = input.nextInt();
      n = input.nextInt();
      int first[][] = new int[m][n];

      System.out.print("Enter The Elements Of First Matrix: ");

      for (c = 0; c < m; c++)
         for (d = 0; d < n; d++)
            first[c][d] = input.nextInt();
      System.out.print("Enter Second Matrix Number Rows And Columns: ");
      p = input.nextInt();
      q = input.nextInt();

      if (n != p)
         System.out.println("Matrices with entered orders can't be multiplied with each other.");
      else {
         int second[][] = new int[p][q];
         int multiply[][] = new int[m][q];
         System.out.print("Enter The Elements Of Second Matrix: ");
         for (c = 0; c < p; c++)
            for (d = 0; d < q; d++)
               second[c][d] = input.nextInt();
         for (c = 0; c < m; c++) {
            for (d = 0; d < q; d++) {
               for (k = 0; k < p; k++) {
                  sum = sum + first[c][k] * second[k][d];
               }
               multiply[c][d] = sum;
               sum = 0;
            }
         }

         System.out.println("Multiplication Of Matrices");

         for (c = 0; c < m; c++) {
            for (d = 0; d < q; d++)
               System.out.print(multiply[c][d] + "t");
            System.out.print("n");
         }
      }
   }
}

Output:

Enter First Matrix Number Rows And Columns: 2 3
Enter The Elements Of First Matrix: 1 2 3 4 5 6
Enter Second Matrix Number Rows And Columns: 3 2
Enter The Elements Of Second Matrix: 1 2 3 4 5 6
Multiplication Of Matrices
22	28	
49	64

Leave a comment