5.0k views
5 votes
Write a method named matrixAdd that accepts a pair of two-dimensional arrays of integers as parameters, treats the arrays as 2D matrices and adds them, returning the result. The sum of two matrices A and B is a matrix C where for every row i and column j, Cij = Aij + Bij. You may assume that the arrays passed as parameters have the same dimensions.

User TheLearner
by
5.4k points

1 Answer

4 votes

Answer:

The code to this question can be given as follows:

Code:

int matrixAdd(int[][] a, int[][] b) //defining method matrixAdd

{

int c[x][y]=0;//defining variable

for(int x = 0; x<a.length; x++) //loop for add rows

{

for(int y= 0; y<a[i].length; y++) //loop for add column

{

int c[x][y] = a[x][y] + b[x][y]; //add array elements

}

}

return c[x][y];//return value

}

Step-by-step explanation:

In the above method definition code, a method "matrixAdd" is defined that contains two integer 2D arrays "a[][] and b[][]" in its parameter, and this function returns the sum of both array.

  • Inside this method, another integer 2D array "c[][]" is defined that contains nothing.
  • To add all array elements the for loop is defined, which uses the array variable "c[][]" to add all array elements and return its value.

User Chazefate
by
5.7k points