Multiplication of Two Matrix in Java of Same Dimensions using For loop
ADVERTISEMENTS
Multiplication of two matrix in java of same dimensions using for loop. In this article, you will learn how to make program of multiplication of two matrix in java of same dimensions using for loop.
Matrix Multiplication Formula
{ M1 } x { M2 } = { M3 }
Source Code
// Multiplication of Two Matrix in Java of Same Dimensions using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int r, c, i, j, k;
// r - To store number of rows
// c - To store number of columns
System.out.println ("Enter the number of rows & columns of the matrix::\n");
r = in.nextInt();
c = in.nextInt();
int x[][], y[][], m[][];
x = new int[r + 1][c + 1];
y = new int[r + 1][c + 1];
m = new int[r + 1][c + 1];
// x - To store first matrix elements
// y - To store second matrix elements
// m - To store multiplication of matrices
System.out.println ("\n---Enter the first matrix's elements---");
for (i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
x[i][j] = in.nextInt();
}
}
System.out.println ("---Enter the second matrix's elements---");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
y[i][j] = in.nextInt();
}
}
System.out.println ("\n\n-----The multiplication of the matrices is-----\n");
// It's the calculation of matrices's multiplications
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
m[i][j] = 0;
for(k = 0; k < c; k++) {
m[i][j] += x[i][k] * y[k][j];
}
}
}
// This will display matrices's outputs
for(i = 0; i < r; i++) {
System.out.print ("\t");
for(j = 0; j < c; j++) {
System.out.print (m[i][j] + "\t");
}
System.out.println ("\n");
}
}
}
Output
Enter the number of rows & columns of the matrix::
3
4
---Enter the first matrix's elements---
12 32 43 54
21 34 54 22
23 45 56 67
---Enter the second matrix's elements---
12 34 56 76
12 43 54 54
12 54 76 34
-----The multiplication of the matrices is-----
1044 4106 5668 4102
1308 5092 7116 5268
1488 5741 7974 6082