- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixSum.java
More file actions
Latest commit
69 lines (65 loc) · 2.73 KB
/
Copy pathMatrixSum.java
File metadata and controls
69 lines (65 loc) · 2.73 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
/* Christopher Yonek
CSC-164-651 - Mr. Ng
2/20/20
8.5 Sum of Two Matrices: This program asks the user to enter the size of the matrices, and to enter their elements
it will out put Matrix C which is the sum of the two
*/
importjava.util.Scanner;
publicclassMatrixSum {
publicstaticvoidmain(String []args) {
//Get n, for n x n matrix
intnByn = GetMatrixSize();
System.out.println("== Matrix A ==");
//Elements for the first matrix
Double[][] matrixA = GetMatrixElements(nByn);
System.out.println("== Matrix B ==");
//Elements for the second matrix
Double[][] matrixB = GetMatrixElements(nByn);
//Add A+B
Double[][] matrixSum = AddMatrix(nByn,matrixA,matrixB);
//Output to user
PrintMatrixSum(matrixSum,nByn);
}
publicstaticintGetMatrixSize(){
//Asks the user to enter one of the dimensions of the matrix
intmatrixSize;
System.out.println("Enter the size of your square matrix (i.e. 3, for 3 x 3)");
ScanneruserInput = newScanner(System.in);
matrixSize = userInput.nextInt();
returnmatrixSize;
}
publicstaticDouble[][] GetMatrixElements(intsize) {
intmatrixOneRow = size, matrixOneCol = size, rowI, colJ;
DoublematrixOne[][] = newDouble[size][size];
//Create scanner for input
ScanneruserInput = newScanner(System.in);
// Prompt user to enter the elements
System.out.println("Enter " + size * size + " Array Elements: ");
for (rowI = 0; rowI < matrixOneRow; rowI++) {
for (colJ = 0; colJ < matrixOneCol; colJ++) {
matrixOne[rowI][colJ] = userInput.nextDouble();
}
}
returnmatrixOne;
}
publicstaticDouble[][] AddMatrix(intsize, Double[][] a, Double[][] b){
// Takes in 2 Arrays and Adds them up
Double[][] matrixC = newDouble[size][size];
for(introw = 0; row < a.length; row++){
for(intcol = 0; col < a[row].length; col++){
matrixC[row][col] = a[row][col] + b[row][col];
}
}
returnmatrixC;
}
publicstaticvoidPrintMatrixSum(Double[][] c, intsize){
// Outputs the Array sum to the user
System.out.print("The Sum is :\n");
for(inti=0; i < size; i++){
for(intj=0; j < size; j++){
System.out.print(c[i][j]+ " ");
}
System.out.println();
}
}
}