-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2.java
More file actions
76 lines (65 loc) · 2.37 KB
/
Copy pathQ2.java
File metadata and controls
76 lines (65 loc) · 2.37 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
67
68
69
70
71
72
73
74
75
76
package WIX1002_1_2019;
import java.util.Random;
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter N : ");
int N = input.nextInt();
int[][] matrixA = new int[N][N];
int[][] matrixB = new int[N][N];
int[][] matrixAns = new int[N][N];
generateMatrix(matrixA, N);
generateMatrix(matrixB, N);
System.out.println("Matrix A");
display(matrixA);
System.out.println("Matrix B");
display(matrixB);
matrixAns = addMatrix(matrixA, matrixB);
System.out.println("Matrix A + B");
display(matrixAns);
matrixAns = multiplyMatrix(matrixA, matrixB);
System.out.println("Matrix A X B");
display(matrixAns);
}
public static void generateMatrix(int[][] matrix, int N){
Random random = new Random();
for (int row = 0; row < N; row++) {
for (int column = 0; column < N; column++) {
matrix[row][column] = random.nextInt(10);
}
}
}
public static void display(int[][] matrix){
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[0].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
public static int[][] addMatrix(int[][] matrixA, int[][] matrixB){
int N = matrixA.length;
int[][] matrixAns = new int[N][N];
for (int row = 0; row < N; row++) {
for (int column = 0; column < N; column++) {
matrixAns[row][column] = matrixA[row][column] + matrixB[row][column];
}
}
return matrixAns;
}
public static int[][] multiplyMatrix(int[][] matrixA, int[][] matrixB){
int N = matrixA.length;
int[][] matrixAns = new int[N][N];
for (int row = 0; row < N; row++) {
for (int column = 0; column < N; column++) {
for (int i = 0; i < N; i++) {
// System.out.print(matrixA[row][i] + " x " + matrixB[column][i] + " + ");
matrixAns[row][column] += matrixA[row][i] * matrixB[i][column];
}
// System.out.println();
}
}
return matrixAns;
}
}