Wednesday, August 14, 2013

Matrix Multiplication Java Program

import java.util.Scanner;

public class MatrixMultiplication {
       public static void main(String args[]) {
              int sum = 0;
              Scanner in = new Scanner(System.in);
              System.out.println("Enter the number of rows and columns of matrixA :");
              int r1 = in.nextInt();
              int c1 = in.nextInt();

              int matrixA[][] = new int[r1][c1];

              System.out.println("Enter the elements of matrixA :");

              for (int i = 0; i < r1; i++) {
                     for (int j = 0; j < c1; j++) {
                           matrixA[i][j] = in.nextInt();
                     }
              }
              System.out.println("Enter the number of rows and columns of matrixB :");
              int r2 = in.nextInt();
              int c2 = in.nextInt();

              if (c1 != r2) {
                     System.out
                                  .println("Matrices with entered orders can't be multiplied with each other.");
              } else {
                     int matrixB[][] = new int[r2][c2];
                     int matrixC[][] = new int[r1][c2];

                     System.out.println("Enter the elements of matrixB :");

                     for (int i = 0; i < r2; i++) {
                           for (int j = 0; j < r2; j++) {
                                  matrixB[i][j] = in.nextInt();
                           }
                     }
                     for (int i = 0; i < r1; i++) {
                           for (int j = 0; j < c2; j++) {
                                  for (int k = 0; k < r2; k++) {
                                         sum = sum + matrixA[i][k] * matrixB[k][j];
                                  }

                                  matrixC[i][j] = sum;
                                  sum = 0;
                           }
                     }

                     System.out.println("Product of entered matrices:-");

                     for (int i = 0; i < r1; i++) {
                           for (int j = 0; j < c2; j++) {
                                  System.out.print(matrixC[i][j] + "\t");
                           }
                           System.out.print("\n");
                     }
              }
       }
}




OUTPUT:

Enter the number of rows and columns of matrixA :
3 3
Enter the elements of matrixA :
4 5 6
7 8 9 
9 8 6
Enter the number of rows and columns of matrixB :
3 3
Enter the elements of matrixB :
4 1 2 
2 5 8
9 6 3
Product of entered matrices:-
80 65 66
125 101 105
106 85 100


No comments:

Post a Comment