AP® Computer Science A Selection and Iteration Practice Questions
Work through AP Computer Science A practice questions on Selection and Iteration, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Subtopic: Iteration Clear filter
Question 222
Question 223
Question 224
Question 225
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
Question 226
int total = 0;
for (int i = 1; i <= 6; i++)
{
if (i % 2 == 0 || i < 3)
total = total + i;
}
What value is stored in total after the loop finishes?Main Solution
Answer
Answer: C. The values added are 1 and 2 because they are less than 3, and 4 and 6 because they are even. The total is 1 + 2 + 4 + 6 = 13.
Answer: Correct: C
A
12
B
14
C
13
D
9
Answer images
Question 227
Question 228
Question 229
Question 230
int count = 0;
for (int i = 1; i <= 4; i++)
{
for (int j = i; j <= 4; j++)
count++;
}
What is the value of count after the code segment executes?Main Solution
Answer
Answer: D. For i=1, the inner loop runs 4 times; for i=2, it runs 3 times; then 2 times; then 1 time. The total is 4 + 3 + 2 + 1 = 10.
Answer: Correct: D
A
8
B
12
C
9
D
10
Answer images
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

