-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrixAddition.java
More file actions
106 lines (92 loc) · 2.06 KB
/
Copy pathmatrixAddition.java
File metadata and controls
106 lines (92 loc) · 2.06 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
* Jiarong Xu
*/
package src;
import java.util.Scanner;
public class matrixAddition {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//greeting+ get the first matrix
System.out.println("Welcome to the matrix adder program!"
+ "\nPlease enter the length and width of the first matrix");
//get the length and width
int l1 = keyboard.nextInt();
//keyboard.next();
int w1 = keyboard.nextInt();
//keyboard.next();
int[][] array1 = new int[l1][w1];
for(int i=0; i<l1; i++)
{
for(int j=0; j<w1; j++)
{
System.out.println("Enter value at index "+i+" "+j);
array1[i][j] = keyboard.nextInt();
//keyboard.next();
}
}
//get the second matrix
System.out.println("Please enter the length and width of the second matrix");
//get the length and width
int l2 = keyboard.nextInt();
//keyboard.next();
int w2 = keyboard.nextInt();
//keyboard.next();
int[][] array2 = new int[l2][w2];
for(int i=0; i<l2; i++)
{
for(int j=0; j<w2; j++)
{
System.out.println("Enter value at index"+i+" "+j);
array2[i][j] = keyboard.nextInt();
//keyboard.next();
}
}
//check same size or not
if(l2 == l1 && w2 == w1)
{
// get result
int [][] array3 = new int [l1][w1];
for(int i=0; i<l1; i++)
{
for(int j=0; j<w1; j++)
{
array3[i][j] = array1[i][j]+ array2[i][j];
}
}
//print first matrix
for(int i=0; i<l1; i++)
{
for(int j=0; j<w1; j++)
{
System.out.print(array1[i][j]+" ");
}
System.out.println();
}
System.out.println("+");
//print second matrix
for(int i=0; i<l1; i++)
{
for(int j=0; j<w1; j++)
{
System.out.print(array2[i][j]+" ");
}
System.out.println();
}
System.out.println("=");
//print result
for(int i=0; i<l1; i++)
{
for(int j=0; j<w1; j++)
{
System.out.print(array3[i][j]+" ");
}
System.out.println();
}
}
else
{
System.out.println("Invalid Dimensions. These cannot be added.");
System.exit(0);
}
}
}