Question

Language Java Write a function named sumMatrices() that takes two matrices, say A and B, and...

Language Java

Write a function named sumMatrices() that takes two matrices, say A and B, and returns a summation matrix C = A + B whose C[i][j] = A[i][j]+B[i][j].
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is code:

private static int[][] sumMatrices(int[][] A, int[][] B) {
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[i].length; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}

Sample code to test:

public class Sum {

public static void main(String[] args) {
int matA[][] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};

int matB[][] = {{12, 11, 10, 9},
{8, 7, 6, 5},
{4, 3, 2, 1}};

int[][] matC = sumMatrices(matA, matB);
for (int i = 0; i < matC.length; i++) {
for (int j = 0; j < matC[i].length; j++) {
System.out.print(matC[i][j] + " ");
}
System.out.println("");
}
}

private static int[][] sumMatrices(int[][] A, int[][] B) {
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[i].length; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
}

Output:

13 13 13 13 13 13 13 13 13 13 13 13

Add a comment
Know the answer?
Add Answer to:
Language Java Write a function named sumMatrices() that takes two matrices, say A and B, and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT