Here you will get java program for matrix multiplication.
Suppose we have matrix A with number of rows and columns as m and n. Let B be a matrix with number of rows and columns as p and q. Their multiplication is possible only if number of columns of matrix A is equal to number of rows of matrix B i.e. n should be equal to p. The resultant matrix is of order mxq.
Also Read: Java Program for Matrix Addition
Java Program for Matrix Multiplication
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 |
import java.util.Scanner; public class JavaMatrixMultiplication { public static void main(String args[]) { int a[][], b[][], c[][], m, n, p, q, i, j, k; Scanner sc = new Scanner(System.in); System.out.println("Enter number of rows and columns of first matrix:"); m = sc.nextInt(); n = sc.nextInt(); System.out.println("Enter number of rows and columns of second matrix:"); p = sc.nextInt(); q = sc.nextInt(); if(n != p) { System.out.println("Multiplication can't be done"); } else { a = new int[m][n]; b = new int[p][q]; c = new int[n][p]; System.out.println("Enter elements of first matrix row wise:"); for(i = 0; i < m; ++i) { for(j = 0; j < n; ++j) { a[i][j] = sc.nextInt(); } } System.out.println("Enter elements of second matrix row wise:"); for(i = 0; i < p; ++i) { for(j = 0; j < q; ++j) { b[i][j] = sc.nextInt(); } } for(i = 0; i < m; ++i) { for(j = 0; j < q; ++j) { for(k = 0; k < n; ++k) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } } System.out.println("Matrix after multiplication:"); for(i = 0; i < m; ++i) { for(j = 0; j < q; ++j) { System.out.print(c[i][j] + " "); } System.out.print("\n"); } } sc.close(); } } |
Output
Enter number of rows and columns of first matrix:
2
2
Enter number of rows and columns of second matrix:
2
2
Enter elements of first matrix row wise:
4 5
6 7
Enter elements of second matrix row wise:
1 2
4 3
Matrix after multiplication:
24 23
34 33