AP® Computer Science A Multiple Choice Questions
Work through AP Computer Science A multiple-choice questions unit by unit, 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 2772
Question 2773
Question 2774
Question 2775
Question 2776
int[][] g = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
int sum = 0;
for (int r = 0; r < g.length; r++)
{
for (int c = 0; c < g[0].length; c++)
{
if (r == c || c == g[0].length - 1 - r)
{
sum = sum + g[r][c];
}
}
}
System.out.println(sum);
What is printed when the code segment executes?Main Solution
Answer
Answer: D. The condition selects cells on either the main diagonal (r == c) or the anti-diagonal (c == cols - 1 - r). For a 3×4 grid (cols = 4), the main-diagonal cells are g[0][0] = 1, g[1][1] = 6, g[2][2] = 11, summing to 18. The anti-diagonal cells are g[0][3] = 4, g[1][2] = 7, g[2][1] = 10, summing to 21. No cell in this 3×4 grid satisfies both conditions, so the union sum is 18 + 21 = 39. Option A counts only the main diagonal; option B counts only the anti-diagonal; option C double-counts a cell that the student incorrectly believed lay on both diagonals.
Answer: Correct: D
A
18
B
21
C
46
D
39
Answer images
Question 2777
Question 2778
Question 2779
Question 2780
name,grade,present
Ali,87,true
Bea,72,false
Cyd,91,true
Dax,54,true
A program creates a properly constructed Scanner sc reading that file, then runs the following code. Assume any imports needed are present.
sc.nextLine();
int total = 0;
int n = 0;
while (sc.hasNext())
{
String line = sc.nextLine();
String[] parts = line.split(",");
if (parts[2].equals("true"))
{
total = total + Integer.parseInt(parts[1]);
n = n + 1;
}
}
sc.close();
double avg = total * 1.0 / n;
What is the value of avg when the segment finishes?Main Solution
Answer
Answer: A. The first sc.nextLine() consumes the header so it is never parsed — option D is wrong because the header is skipped before any parseInt is attempted. Each remaining line is split on commas. Records with parts[2].equals("true") are Ali (87), Cyd (91), and Dax (54); Bea is excluded. So total = 87 + 91 + 54 = 232 and n = 3. avg = 232 * 1.0 / 3 = 77.333…. Option B averages all four students.
Answer: Correct: A
A
77.33333333333333
B
76.0
C
87.0
D
A run-time exception is thrown when parsing the header.
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.

