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 282
Question 283
Question 284
Question 285
Question 286
Question 287
arr is an int array.
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
int count = 0;
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] < arr[i + 1])
{
count++;
}
}
System.out.println(count);
What is printed?Main Solution
Solution:
Correct: B. Compare each adjacent pair: 3<1 F, 1<4 T, 4<1 F, 1<5 T, 5<9 T, 9<2 F, 2<6 T. That is 4 true comparisons.
Answer: Correct: B
Answer images
Question 288
int array.
int[] arr = {2, 5, 1, 8, 3, 9, 4};
int best = arr[0] + arr[1];
for (int i = 1; i < arr.length - 1; i++)
{
int s = arr[i] + arr[i + 1];
if (s > best)
{
best = s;
}
}
System.out.println(best);
What is printed?Main Solution
Solution:
Correct: C. Adjacent pair sums: (2+5)=7, (5+1)=6, (1+8)=9, (8+3)=11, (3+9)=12, (9+4)=13. Initial best=7, updated successively to 9, 11, 12, 13. Maximum is 13.
Answer: Correct: C
Answer images
Question 289
int array.
int[] arr = { 7, 3, 9, 1, 5 };
for (int i = 1; i < arr.length; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
What are the contents of arr immediately after the outer loop has completed three iterations (that is, after the iterations for i = 1, i = 2, and i = 3)?Main Solution
Solution:
Answer: B. After i = 1 the key is 3; it bubbles past the 7 at index 0, giving { 3, 7, 9, 1, 5 }. After i = 2 the key is 9; the inner loop's guard arr[j] > key is already false (7 < 9), so no shifts occur and the array is unchanged. After i = 3 the key is 1; it shifts past 9, 7, and 3, ending at index 0: { 1, 3, 7, 9, 5 }. The last element 5 is still out of place — insertion sort has sorted only the prefix of length four at this point.
Answer: Correct: B
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.

