In this post, we will see how to multiply two matrices in java.

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 |
import java.util.Scanner; public class MatrixOperator { public static void main(String args[]) { int r1, c1, r2, c2, sum = 0, i, j, k; Scanner in = new Scanner(System.in); System.out.print("Enter number of rows and columns of first matrix : "); r1 = in.nextInt(); c1 = in.nextInt(); int first[][] = new int[r1][c1]; System.out.print("Enter first matrix elements : "); for(i=0 ; i<r1; i++){ for(j=0; j<c1; j++){ first[i][j] = in.nextInt(); } } System.out.print("Enter number of rows and columns of second matrix :"); r2 = in.nextInt(); c2 = in.nextInt(); if ( c1 != r2 ){ System.out.print("Matrix of the entered order can't be Multiplied..!!"); } else{ int second[][] = new int[r2][c2]; int multiply[][] = new int[r1][c2]; System.out.print("Enter second matrix elements : \n"); for(i=0; i<r2; i++){ for(j=0; j<c2; j++){ second[i][j] = in.nextInt(); } } for(i=0; i<r1; i++){ for(j=0; j<c2; j++){ for(k=0; k<r2; k++){ sum = sum + first[i][k]*second[k][j]; } multiply[i][j] = sum; sum = 0; } } System.out.print("Matrix multiplication result is : "); for(i=0; i<r1; i++){ for(j=0; j<c2; j++){ System.out.print(multiply[i][j] + "\t"); } System.out.print("\n"); } } } } |

**Output:**

Enter first matrix elements : 2 4 6 8

Enter number of rows and columns of second matrix :2 2

Enter second matrix elements : 3 6 9 12

Matrix multiplication result is :

42 60

90 132

That’s all about mutliplying two matrices in java.