In java, Write a method to add two matrices of ints. The header of the method is
ID: 647291 • Letter: I
Question
In java, Write a method to add two matrices of ints. The header of the method is as follows: public static int[][] addMatrices(int[][] a, int[][] b)
In order to be added, the two matrices must have the same dimensions. You may assume that all rows are the same length, and that the dimensions are positive. (Each matrix has at least one row and one column). Two matrices are added by adding the pairs of elements that have the same indices. The method should not modify a or b. Also write a printMatrix method for printing a matrix: public static void printMatrix(int[][] matrix) { … }
Test your two methods by putting the following code in your main method: int[][] a = { {5, 4, 3, 2}, {10, 9, 8, 7}, {15, 14, 13, 12} }; int[][] b = { {10, 12, 14, 16}, {-5, -7, -9, -11}, {20, 15, 10, 5} }; printMatrix(addMatrices(a, b));
The output should be:
15 16 17 18
5 2 -1 -4
35 29 23 17
Note that the output of each number is right-justified in a field of width 3. So make sure that your printMatrix method uses a System.out.printf statement with a format specifier of "%3d".
Explanation / Answer
public class MatrixAddition{
static int[][] addMatrices(int[][] a, int[][] b) {
int[][] matrix = new int[a.length][a[0].length];
for(int i = 0; i < matrix.length; ++i){
for(int j = 0; j < matrix[i].length; ++j){
matrix[i][j] = a[i][j] + b[i][j];
}
}
return matrix;
}
public static void printMatrix(int[][] matrix) {
for(int i = 0; i < matrix.length; ++i){
for(int j = 0; j < matrix[i].length; ++j){
System.out.printf("%3d", matrix[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void main(String []args){
int[][] a = { {5, 4, 3, 2}, {10, 9, 8, 7}, {15, 14, 13, 12} };
int[][] b = { {10, 12, 14, 16}, {-5, -7, -9, -11}, {20, 15, 10, 5} };
printMatrix(addMatrices(a, b));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.