-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMatrixMultiplication.java
More file actions
66 lines (53 loc) · 1.42 KB
/
MatrixMultiplication.java
File metadata and controls
66 lines (53 loc) · 1.42 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package lecture5;
import java.util.Scanner;
public class MatrixMultiplication {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("rows and cols 1 matrix");
int r1 = s.nextInt();
int c1 = s.nextInt();
System.out.println("rows and cols 2 matrix");
int r2 = s.nextInt();
int c2 = s.nextInt();
if (c1 != r2)
System.out.println("invalid input not \n possible multiplication");
else {
int[][] a = takeinput(r1, c1);
int[][] b = takeinput(r2, c2);
int[][] c = multiply(a, b);
display(c);
}
}
public static int[][] multiply(int[][] a, int[][] b) {
int[][] c = new int[ a.length][b[0].length];
int sum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b[0].length; j++) {
sum = 0;
for (int k = 0; k < a[0].length; k++) {
sum += (a[i][k] * b[k][j]);
}
c[i][j] = sum;
}
}
return c;
}
public static void display(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
System.out.print(arr[row][col] + " ");
}
System.out.println();
}
}
public static int[][] takeinput(int rows, int cols) {
int[][] arr = new int[rows][cols];
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
System.out.println("arr[" + row + "-" + col + "]");
arr[row][col] = s.nextInt();
}
}
return arr;
}
}