Question 391
int[][] g = { {3, 8, 2},
{5, 1, 9},
{4, 6, 7} };
int count = 0;
for (int r = 0; r < g.length; r++)
{
int rowMax = g[r][0];
for (int c = 1; c < g[r].length; c++)
{
if (g[r][c] > rowMax)
{
rowMax = g[r][c];
}
}
for (int c = 0; c < g[r].length; c++)
{
if (g[r][c] == rowMax)
{
count = count + 1;
}
}
}
System.out.println(count);
What is printed when the code segment executes?Main Solution
Answer
Answer: C. The outer loop processes one row at a time. For each row, the first inner loop computes the row's maximum; the second inner loop counts how many cells in that row equal the maximum. Row 0 = {3, 8, 2} has max 8, occurring once. Row 1 = {5, 1, 9} has max 9, occurring once. Row 2 = {4, 6, 7} has max 7, occurring once. Total count = 3. Option B sums all elements; option A sums each row's maximum without counting; option D forgets the per-row reset.
Answer: Correct: C
A
6
B
9
C
3
D
1
Answer images

