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.
Question 1072
Consider the following code segment.
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[0].length; c++)
{
if (r + c == 2)
{
sum = sum + grid[r][c];
}
else if (r == c)
{
sum = sum - grid[r][c];
}
}
}
What is the value of sum after the loops?
Main Solution
Answer
Answer: C. The anti-diagonal values 3, 5, and 7 are added. The main diagonal cells that are not already handled by the first branch are 1 and 9, which are subtracted. The total is 15 - 10 = 5.
Answer: Correct: C
A
15
B
0
C
5
D
-5
Answer images
Question 1073
Question 1074
Question 1075
Question 1076
Question 1077
Question 1078
Question 1079
Consider the following recursive method.
public static int score(int[] arr, int k)
{
if (k >= arr.length)
{
return 0;
}
int rest = score(arr, k + 2);
if (arr[k] % 2 == 0)
{
return rest + arr[k];
}
return rest - arr[k];
}
What value is returned by the following code?
int[] values = {5, 2, 4, 7, 6};
score(values, 0);Main Solution
Answer
Answer: C. The method visits indices 0, 2, and 4. Index 4 contributes +6, index 2 contributes +4, and index 0 contributes -5. The total is 5.
Answer: Correct: C
A
15
B
10
C
5
D
-5
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.

