AP® Computer Science A Data Collections Multiple Choice Questions
Work through AP Computer Science A multiple-choice questions on Data Collections, 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: Arrays Clear filter
Question 262
Question 263
Question 264
Question 265
Question 266
Question 267
Question 268
Question 269
Question 270
What is the content of arr after executing the following?
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
int n = arr.length;
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n / 2 + i];
arr[n / 2 + i] = temp;
}Main Solution
The correct answer is C: {5, 6, 7, 8, 1, 2, 3, 4}.
Let's trace through the code step by step.
Initial array: {1, 2, 3, 4, 5, 6, 7, 8}, indices 0–7.n = 8, so n / 2 = 4.
The loop runs for i = 0, 1, 2, 3 (while i < 4). Each iteration swaps arr[i] with arr[4 + i]:
- i = 0: swap
arr[0](1) andarr[4](5) → array becomes{5, 2, 3, 4, 1, 6, 7, 8} - i = 1: swap
arr[1](2) andarr[5](6) → array becomes{5, 6, 3, 4, 1, 2, 7, 8} - i = 2: swap
arr[2](3) andarr[6](7) → array becomes{5, 6, 7, 4, 1, 2, 3, 8} - i = 3: swap
arr[3](4) andarr[7](8) → array becomes{5, 6, 7, 8, 1, 2, 3, 4}
The algorithm swaps the first half of the array with the second half, resulting in {5, 6, 7, 8, 1, 2, 3, 4}.
Teacher Explanation
This question tests array manipulation and loop tracing. The loop swaps each element in the first half of the array with its corresponding element in the second half (offset by n/2). The result is that the two halves are exchanged. Students must carefully trace the index arithmetic: arr[i] pairs with arr[n/2 + i] for each i from 0 to n/2 - 1.
Education Coach Advice
When tracing array loops on the AP exam, write out the array state after each iteration. Pay close attention to index expressions like n / 2 + i — integer division is key. A quick table with columns for i, arr[i], and arr[n/2+i] before and after each swap will prevent errors and save time.
Traps
Option A ({8, 7, 6, 5, 4, 3, 2, 1}) is a common trap for students who think the loop reverses the entire array. A full reversal would require swapping arr[i] with arr[n-1-i], not arr[n/2+i].
Option D ({4, 3, 2, 1, 8, 7, 6, 5}) might attract students who think each half is reversed independently.
Option B (unchanged array) would be the result if the swap logic were incorrect (e.g., swapping an element with itself), but the indices here are distinct.
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.

