Answer to Question #293387 in Java | JSP | JSF for jeffy

Question #293387

Write a method called addMatrices which will take two matrices (two-dimensional

integer arrays) as argument, and returns the addition of these two matrices as a two-

dimensional integer array.

You may use the following header for this method:

static int[][] addMatrices(int[][] firstMatrix,

int[][] secondMatrix)

For example, if we pass the following two two-dimensional arrays to the method:

5 7 9 4 3 7 3 2 1 5

2 3 9 7 6 3 9 4 0 3

3 6 8 7 9 6 2 8 9 4

1 9 7 5 6 5 0 3 8 7

3 8 7 9 2 1 6 8 4 3

Then the method should return the following two-dimensional array:

12 10 11 5 8

5 12 13 7 9

9 8 16 16 13

6 9 10 13 13

4 14 15 13 5


2. Write a method called printArray that takes a two-dimensional integer array as

argument and prints all elements of array. The method should print each row line by line.

You may use the following header for this method:

static void printArray(int[][] array)

In the main method:

 Declare and initialize two two-dimensional arrays.

 Pass these two-dimensional arrays to addMatrices()method..


1
Expert's answer
2022-02-02T16:49:44-0500
public class Main {
    static int[][] addMatrices(int[][] firstMatrix, int[][] secondMatrix) {
        int[][] result = new int[firstMatrix.length][firstMatrix[0].length];
        for (int i = 0; i < firstMatrix.length; i++) {
            for (int j = 0; j < firstMatrix[i].length; j++) {
                result[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
            }
        }
        return result;
    }

    static void printArray(int[][] array) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] a = {
                {5, 7, 9, 4, 3},
                {2, 3, 9, 7, 6},
                {3, 6, 8, 7, 9},
                {1, 9, 7, 5, 6},
                {3, 8, 7, 9, 2}};
        int[][] b = {
                {7, 3, 2, 1, 5},
                {3, 9, 4, 0, 3},
                {6, 2, 8, 9, 4},
                {5, 0, 3, 8, 7},
                {1, 6, 8, 4, 3},};
        printArray(addMatrices(a, b));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS