Question 141
int[][] g = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
int sum = 0;
for (int r = 0; r < g.length; r++)
{
for (int c = 0; c < g[0].length; c++)
{
if (r == c || c == g[0].length - 1 - r)
{
sum = sum + g[r][c];
}
}
}
System.out.println(sum);
What is printed when the code segment executes?Main Solution
Answer
Answer: D. The condition selects cells on either the main diagonal (r == c) or the anti-diagonal (c == cols - 1 - r). For a 3×4 grid (cols = 4), the main-diagonal cells are g[0][0] = 1, g[1][1] = 6, g[2][2] = 11, summing to 18. The anti-diagonal cells are g[0][3] = 4, g[1][2] = 7, g[2][1] = 10, summing to 21. No cell in this 3×4 grid satisfies both conditions, so the union sum is 18 + 21 = 39. Option A counts only the main diagonal; option B counts only the anti-diagonal; option C double-counts a cell that the student incorrectly believed lay on both diagonals.
Answer: Correct: D
A
18
B
21
C
46
D
39
Answer images

