Question 7
Back to Exercise
What is the output of the following Java program?
public class Main {
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int diag = 0, anti = 0, last = 0;
for (int i = 0; i < m.length; i++) {
diag += m[i][i];
anti += m[i][m.length - 1 - i];
}
for (int v : m[2]) last += v;
System.out.println(diag + " " + anti + " " + last);
}
}
- A 15 15 24 Correct
- B 15 15 18
- C 12 15 24
- D 15 18 24
Correct Answer: Option A
Main diagonal 1 + 5 + 9, anti-diagonal 3 + 5 + 7, last row 7 + 8 + 9.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!