Summing a 2D Array Diagonal
Consider the following code segment.
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int result = 0;
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
if (row == col) {
result += matrix[row][col];
}
}
}
System.out.println(result);
What is printed as a result of executing the code segment?
A
9
B
45
C
15
D
6
Question Leaderboard
Not enough data yet to show leaderboard.
