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.
Question 412
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 413
Question 414
Question 415
Question 416
Question 417
Question 418
Question 419
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
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.

