ARTICLE AD BOX
I am practicing matrix operations in Java and trying to create a method that adds two matrices.
The program compiles and runs, but some values in the resulting matrix are incorrect.
Observed behavior:
The output does not match the expected matrix addition.
Expected behavior:
The result should be:
6 8
10 12
What I already tried:
I reviewed the nested loops and checked the dimensions of both matrices, but I still cannot find why the calculation is wrong.
public class Main { public static int[][] addMatrices(int[][] a, int[][] b) { int[][] result = new int[a.length][a[0].length]; for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[0].length; j++) { result[i][j] = a[i][j] + b[i][i]; } } return result; } public static void main(String[] args) { int[][] matrix1 = { {1, 2}, {3, 4} }; int[][] matrix2 = { {5, 6}, {7, 8} }; int[][] result = addMatrices(matrix1, matrix2); for(int i = 0; i < result.length; i++) { for(int j = 0; j < result[0].length; j++) { System.out.print(result[i][j] + " "); } System.out.println(); } } }