Repository navigation
Expand file tree
/
Copy path35-MatrixMultiplication.java
More file actions
47 lines (43 loc) · 1.58 KB
/
Copy path35-MatrixMultiplication.java
File metadata and controls
47 lines (43 loc) · 1.58 KB
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
import java.util.Scanner;
class MatrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] first = readMatrix(scanner, "first");
int[][] second = readMatrix(scanner, "second");
if (first.length == 0 || first[0].length != second.length) {
System.out.println("Matrix multiplication is not possible");
} else {
int[][] result = new int[first.length][second[0].length];
for (int i = 0; i < first.length; i++) {
for (int j = 0; j < second[0].length; j++) {
for (int k = 0; k < second.length; k++) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
System.out.println("Product:");
printMatrix(result);
}
scanner.close();
}
private static int[][] readMatrix(Scanner scanner, String name) {
System.out.print("Enter rows and columns for " + name + " matrix: ");
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}
private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}