Matrix Multiplication in Java
Here, You will get the program code of Matrix Multiplication in Java using Scanner class. Rule of matrix multiplication table given bellow.
Rule of Matrix Multiplication
Matrix Multiplication in Java using Scanner
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | //Matrix multiplication in java using scanner import java.util.Scanner; class MatrixMultiplication { public static void main(String args[]) { int Matrix1row,Matrix1col,Matrix2row,Matrix2col,i, j,k; Scanner in = new Scanner(System.in); //Input number of rows and columns of Matrix 1 System.out.println("Enter the number of rows and columns :"); Matrix1row = in.nextInt(); Matrix1col = in.nextInt(); //Input number of rows and columns of Matrix 2 System.out.println("Enter the number of rows and columns :"); Matrix2row = in.nextInt(); Matrix2col = in.nextInt(); if (Matrix1col != Matrix2row ) System.out.println("Matrix multiplication is not Possible!"); else { int first[][] = new int[Matrix1row][Matrix1col]; int second[][] = new int[Matrix2row][Matrix2col]; int mutiplymatrix[][] = new int[Matrix1row][Matrix2col]; //input elements in first matrix System.out.println("Enter elements of first matrix : "); for ( i = 0 ; i < Matrix1row ; i++ ) for ( j = 0 ; j < Matrix1col ; j++ ) first[i][j] = in.nextInt(); //input elements in second matrix System.out.println("Enter elements of second matrix : "); for ( i = 0 ; i < Matrix2row ; i++ ) for ( j = 0 ; j < Matrix2col ; j++ ) second[i][j] = in.nextInt(); // Multiplying matrices for(i = 0; i < Matrix1row; i++) { for(j = 0; j < Matrix2col; j++) { for(k = 0; k < Matrix1col; k++) { mutiplymatrix[i][j] += first[i][k] * second[k][j]; } } } //Print elements of third matrix System.out.println("Result of Matrix multiplication :-"); for ( i = 0 ; i < Matrix1row ; i++ ) { for ( j = 0 ; j < Matrix2col ; j++ ) { System.out.print(mutiplymatrix[i][j]+"\t"); } System.out.println(); } } } } |
Output
Check out our other Java Programming Examples