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 212
int n = 128;
int steps = 0;
while (n > 1)
{
n = n / 2;
steps = steps + 1;
}
System.out.println(steps);
What is printed when the code segment executes?Main Solution
Answer
Answer: C. The loop halves n (using integer division) on every iteration and increments steps. Starting from 128: 128 → 64 → 32 → 16 → 8 → 4 → 2 → 1. That is 7 halvings, so steps ends at 7. The loop then exits because n > 1 is false when n == 1. Option B is obtained by stopping one step early; option D adds an extra division that would take n to 0, but the guard prevents it.
Answer: Correct: C
A
5
B
6
C
7
D
8
Answer images
Question 213
Question 214
Question 215
Question 216
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(2);
nums.add(4);
nums.add(4);
nums.add(6);
nums.add(4);
for (int i = 0; i < nums.size(); i++)
{
if (nums.get(i) == 4)
{
nums.remove(i);
}
}
System.out.println(nums);
What is printed when the code segment executes?Main Solution
Answer
Answer: B. This is the classic index-shift bug. When remove(i) is called, every later element slides one position to the left, but i is still incremented. Trace: at i=0 value 2 (skip); at i=1 value 4 (remove) → list becomes [2, 4, 6, 4]; at i=2 value 6 (skip, because the middle 4 shifted into index 1 and was jumped over); at i=3 value 4 (remove) → list becomes [2, 4, 6]; the loop ends because i = 4 is no longer less than size() = 3.
Answer: Correct: B
A
[2, 6]
B
[2, 4, 6]
C
[2, 4, 4, 6, 4]
D
[2, 6, 4]
Answer images
Question 217
Question 218
Question 219
int n = 100;
int steps = 0;
while (n > 1)
{
if (n % 2 == 0)
{
n = n / 2;
}
else
{
n = n - 1;
}
steps = steps + 1;
}
System.out.println(steps);
What is printed when the code segment executes?Main Solution
Answer
Answer: B. Trace n after each iteration: 100 → 50 → 25 → 24 → 12 → 6 → 3 → 2 → 1. That is 8 updates before the loop condition n > 1 fails, so steps = 8. Option A forgets the final divide-by-two from 2 → 1; option C double-counts an iteration; option D treats the odd step as still halving.
Answer: Correct: B
A
7
B
8
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.

