Computer Program Reading Comprehension Project
U of T Computer Program Reading Comprehension Project
Matrix Addition
Uses two-dimensional arrays to add two integer matrices and prints the resulting matrix.

Download files: matrixAdd.java
Areas: 2D arrays


matrixAdd.java
1/**
2 * MatrixAdd.java -
3 *   Method and test cases for matrix addition.  The method
4 *   addMatrices computes the sum of two matrices.
5 *
6 *   For example:
7 *       +-   -+   +-   -+   +-   -+
8 *       |1 2 3|   |2 3 4|   |3 5 7|
9 *       |4 5 6| + |5 4 3| = |9 9 9|
10 *       |2 1 0|   |0 1 2|   |2 2 2|
Displaying 10 of 52 lines
View full source


Question 1
In which method are the matrices t1 and t2 initialized?
Solution

Question 2
Which element does t1[1][0] refer to?
Solution

Question 3
If this line was executed:
int answer = t1[0][2] + t2[1][1];
What would the value of answer be?
Solution

Question 4
Draw the matrices t1 and t2? Example: If we had a matrix
int[][] t3 = {{78, 9}, {333, 1}};
drawing matrix t3 would produce:
78       9
333     1
Solution

Question 5
What is the value of t1.length?
Solution

Question 6
What does m1[0].length refer to?
Solution

Question 7
After this line is executed:
result = addMatrices(t1,t2)
What will the dimensions of the array result be?
Hints Solution

Question 8
Declare and construct a two-dimensional double array height with 3 rows and 5 columns.
Solution

Question 9
Write a method subtractMatrices(int[][] m1, int[][] m2) that subtracts matrix m2 from matrix m1 and returns the resulting matrix.
Hints Solution

Question 10
Write a method sumDiagonal that returns the sum of all the elements that lie on the main diagonal of a matrix m. The main diagonal of a matrix is a diagonal that extends from the upper left corner of a matrix to the lower right corner. For example, the main diagonal of
    1     2     3
    4     5     6
    2     1     0
is [1 5 0].
Hints Solution