In this tutorial, we will write a java program to calculate the multiplication of two matrices. As this program is based on Array and uses of for loop so you may go through the following first.
Matrices mean having two-dimension that is there are columns and rows in the following java example.
The Program takes the input for both the column and row elements from the user using the scanner class and a third two-dimensional array is created to store the multiplication result of two matrices. And lastly displays the final result.
Java Program to Multiply Two Matrices
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 68 69 70 71 72 73 74 75 76 77 | //multiplication of a matrix import java.util.Scanner; public class MultilicationMatrix { public static void main(String args[]) { int r1, r2,c1,c2,i,j,k,sum; Scanner in = new Scanner(System.in); //first matrix System.out.println("Enter the number of rows of matrix1"); r1 = in.nextInt(); System.out.println("Enter the number columns of matrix 1"); c1 = in.nextInt(); //second matrix System.out.println("Enter the number of rows of matrix2"); r2 = in.nextInt(); System.out.println("Enter the number of columns of matrix 2"); c2 = in.nextInt(); //condition for multiplication if(c1==r2) { int mat1[][] = new int[r1][c1]; int mat2[][] = new int[r2][c2]; int result[][] = new int[r1][c2]; System.out.println("Enter the elements of matrix1"); for ( i= 0 ; i < r1 ; i++ ) { for ( j= 0 ; j < c1 ;j++ ) { mat1[i][j] = in.nextInt(); } } System.out.println("Enter the elements of matrix2"); for ( i= 0 ; i < r2 ; i++ ) { for ( j= 0 ; j < c2 ;j++ ) { mat2[i][j] = in.nextInt(); } } System.out.println("Result of multiplication:-"); for ( i= 0 ; i < r1 ; i++ ) { for ( j = 0 ; j < c2; j++) { sum = 0; for ( k = 0 ; k < r2; k++ ) { sum += mat1[i][k] * mat2[k][j] ; } result[i][j] = sum; } } for ( i= 0 ; i < r1; i++ ) { for ( j=0 ; j < c2; j++ ) { System.out.print(result[i][j]+" "); } System.out.println(); } } else System.out.print("Multiplication cannot be processed"); } } |
Output:
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 | Enter the number of rows of matrix1 2 Enter the number columns of matrix 1 3 Enter the number of rows of matrix2 3 Enter the number of columns of matrix 2 2 Enter the elements of matrix1 2 3 4 2 1 4 Enter the elements of matrix2 5 4 2 3 5 3 Result of multiplication: 36 29 32 23 |