4 18 May 2009 | 2009 AP Computer Science Exam Answers The

advertisement
2009 AP Computer Science A Exam Multiple Choice Explanations 4
18 May 2009 | 2009 AP Computer Science Exam Answers
The College Board released the complete 2009 AP Computer Science A Exam, including the multiple choice section. While
their released exam includes detailed explanations for each free response question, it does not offer detailed explanations
for each multiple choice question. Question by question explanations for the 2009 AP Computer Science A Multiple Choice
Section are below.
You must purchase the released exam itself from the College Board’s Online Store. Refer to the College Board product for
the original questions and for the letter answers.
Review the 2009 AP CS A Exam Multiple Choice with AP CS Tutor Brandon Horn.
2009 AP CS Exam Free Response Solutions
 NumberCube Free Response Solution
 StockpileCritter Free Response Solution
 BatteryCharger Free Response Solution
 TileGame Free Response Solution
Recommended Practice Topics
 Sorting & Searching Practice Problems
 List & ArrayList Practice Problems
 Recursion Practice Problems
 Inheritance & Polymorphism Practice Problems
Question 1
value is unchanged before it is printed the first time, so the first number output is 15. value is incremented after the call
to println and the loop stops when value == 28 so the last number output is 27.
Question 2
Case I: The && operation evaluates to true if and only if both operands are true. The condition in Case I is evaluated as
(bonusOne && bonusTwo) && bonusThree. For the condition to evaluate to true all 3 variables must be true. This
correctly implements the intended condition.
Case II: The || operation is true if at least 1 operand is true. The condition in Case II evaluates to true if at least 1 of
the variables is true, which is not the intent.
Case III: The conditions are evaluated independently. It is possible for grade to be incremented by 0, 5, 10 or 15 points
depending on the values of the variables. This is not the intent.
Question 3
Interchanging, often called swapping, the values of at 2 positions in an array, or in an ArrayList requires the use of a
variable to store the value that would otherwise be lost when one value in the array is replaced with the other.
Answers A and B fail to use a temporary variable. Answer C uses a temporary variable but stores the wrong value. Answer
E stores the correct variable but does not use the temporary variable.
Answer D correctly stores one of the values in the temporary variable, overwrites the original copy then retrieves the
temporary copy.
Question 4
The Quick Reference contains documentation for each ArrayList method called. The list after each step is below.
[A]
[A, B]
[A, B, C]
[D, A, B, C]
[D, A, B]
[E, D, A, B]
Question 5
1
2009 AP Computer Science A Exam Multiple Choice Explanations 4
A superclass contains fields and methods that are used by all of its subclasses. The term superclass is not intended to
imply importance or complexity, but rather indicates that the superclass is above a subclass in a class hierarchy.
In the GridWorld Case Study, the Actor class is a superclass for subclasses such as Bug, Rock and Critter. Actor
contains methods common to all its subclasses such as getLocation and getGrid.
Answers B and C incorrectly refer to the complexity of a superclass. Answer D suggests that data should be public, which is
not only unnecessary but also violates the principle of encapsulation.
Answer E states that the superclass should provide the most specific details; however, a superclass is actually less specific
than its subclasses. For example, an Actor could be a Bug, a Critter or another subclass. The subclass is can contain
details specific to itself. For example, Critter contains the method getMoveLocations.
Question 6
If k is initialized to 1, the outer loop will never run, so the inner loop will never run, so Hello will not be printed at all.
Question 7
If k is initialized to n, the outer loop will run n – 1 times. (If p was initialized to 1, the outer loop would run n times.) Each
time the outer loop runs, the inner loop will run n – 1 times.
(n – 1) runs of the outer loop multiplied by (n – 1) runs of the inner loop is (n – 1)2.
Question 8
Case I uses a straightforward for loop to traverse the vals. total is incremented by vals[pos] during each run of the
loop. After the loop total contains the sum of all values in vals, as intended.
Case II attempts to traverse vals backwards, which would work, except pos is initialized to vals.length.
vals.length is not a valid index in vals, so the loop throws an ArrayIndexOutOfBoundsException on its first
iteration.
Case III uses a while loop to traverse vals. The loop is exactly equivalent to the for loop from Case I, so it works as
intended.
Question 9
The loop runs 5 times. Each value of rep and the String printed are shown below.
0: ab
1: bc
2: cd
3: de
4: ef
Everything is printed on the same line, so the output is abbccddeef.
Question 10
Tracing the method for 50 iterations of the loop would take too long, so it is important to determine what each variable
represents. Each if statement is independent (there are no else if statements, so:
typeA is incremented for each value of k that is a multiple of both 2 and 5.
typeB is incremented for each value of k that is a multiple of 2 (regardless of whether it is also a multiple of 5).
typeC is incremented for each value of k that is a multiple of 5 (regardless of whether it is also a multiple of 2).
The loop is run for values of k from 1 to 50, inclusive. Within that range, there are 5 multiples of both 2 & 5, 25 multiples
of 2 and 10 multiples of 5. The method outputs 5 25 10.
Question 11
/* expression */ should evaluate to true if and only if the value in nameList at position j is equal to name.
2
2009 AP Computer Science A Exam Multiple Choice Explanations 4
nameList is an ArrayList so the element at position j is accessed as nameList.get(j). The contents of String
objects are compared using the equals method, not ==.
The correct comparison is nameList.get(j).equals(name).
Question 12
Case I returns n * 10 for all values of n that are multiples of both 3 and 4. It returns n for all other values of n.
In the table of example inputs and outputs, someProcess(3) returns 30. Case I would return 3 because 3 is not a
multiple of both 3 and 4. Case I will not produce the intended results.
Case II returns n * 10 for all values of n that are multiples of either 3 or 4. It returns n for all other values of n.
This corresponds exactly with the table given. Each value of n that is a multiple of either 3 or 4 results in a return vale of n
* 10. All other values of n result in a return value of n.
Case III is equivalent to Case I. Both conditions must evaluate to true for the method to return n * 10.
Question 13
x is an integer >=0. x / 10 is x without its least significant (last) digit. x % 10 is the least significant digit itself. The
recursive call to mystery is prior to the call to print, so the last digit removed is the first digit printed. The last digit
removed is 1. The second to last digit removed is 2 and so on. mystery is just an elaborate way of printing x.
My Stack based trace of 2009 AP CS A Multiple Choice #13 shows a step by step solution.
Question 14
Case I attempts to calculate the value for yrs as extraMonths % 12 and the value for mos as extraMonths / 12.
There are 2 issues with this approach. The assignments are reversed. There are extraMonths / 12 additional years and
extraMonths % 12 additional months. Also, Case I fails to take into account the situation in which months + mos
exceeds 12.
Case II correctly converts the original age into months as years * 12 + months. It then adds extraMonths to
correctly calculate the new age in months. Case II then converts the total number of months into years (totalMonths /
12) and months (totalMonths % 12) and assigns the results to years and months. Case II works as intended.
Case III first computes the total number of months, including the new months as months + extraMonths. Case III
correctly determines how many years are represented by those months as totalMonths / 12 and correctly adds the
result to years. The total number of months is what remains after converting all groups of 12 months to years,
totalMonths % 12. Case III correctly assigns this to months. Case III works as intended.
Question 15
inRangeMessage returns “Not in range” if either part of the condition is true; otherwise, it returns “In range”. In
other words, inRangeMessage returns “In range” if and only if value >= 0 && value <= 100.
Case I incorrectly returns “In range” if value >= 0 without checking whether value <= 100.
Case II checks each out of range condition separately and returns “Not in range” if either condition is true. If neither
condition is true, it correctly returns “In range”. Case II works as intended.
Case III has the same problem as Case I. Case III immediately returns “In range” if value >= 0 without checking the
upper bound.
Question 16
After the 3 assignment statements, one and three refer to the same instance of SomeClass. two refers to a different
instance. The statement one.increment(200) increments the value of num in the object to which both one and three
refer. The object to which two refers in unaffected.
Immediately prior to the println statement, one and three refer to the same object inside which num stores 300. two
refers to a different object inside which num stores 100.
3
2009 AP Computer Science A Exam Multiple Choice Explanations 4
Question 17
sortArray implements a variant of selection sort that sorts the array starting at the end. /* missing code */
controls the inner loop, which is responsible for finding the maximum value from 0 to j. pos starts at j, so the inner loop
only needs to traverse the elements from 0 to j – 1. The order in which it does this is irrelevant, but it must cover each
element in the range and ignore all elements outside the range.
Answer A incorrectly excludes the element at position 0.
Answer B correctly visits each element in the range and no other elements.
Answer C incorrectly excludes the element at position 0 and incorrectly continues until the end of the array, rather than
stopping at j – 1. Although stopping at j would also be acceptable, proceeding farther means that the loop will visit
elements from the already sorted part of the array while seeking the minimum.
Answer D has a condition that would prevent the loop from running (k > arr.length).
Answer E correctly includes the element at position 0, but also incorrectly continues into the already sorted part. Answer E
also exceeds the bounds of the array by including arr.length.
Question 18
Let a = x && y. The statement is equivalent to a || ! a which always evaluates to true.
Question 19
As specified in the Quick Reference, Math.random() generates a random value in the range 0 <= r < 1.
Math.random() * 5.0 generates a random value in the range 0 <= r < 5.0. Math.random() * 5.0 + 0.5
generates a random value in the desired range.
Multiplying the result of Math.random changes the maximum possible value. Adding to the result of Math.random
changes both the minimum and maximum possible values. It is possible to generate numbers within any desired range by
combining these operations.
Question 20
Case I explicitly checks each part of the specified conditions and returns the correct value in each case.
Case II uses the same correct technique, but includes the extra variable pass. pass is initialized to false then changed
to true if and only if one of the desired conditions is met. Case II works correctly.
Case III is a more efficient variant of the same combination of checks that avoids the if statements and just returns the
result of a single correct boolean condition. Case III works correctly.
Question 21
The Quick Reference contains documentation for each Location class method called.
loc2.getAdjacentLocation(Location.EAST) returns a Location object representing (3, 3). The first condition
evaluates to true and “aaa” is printed.
loc1 and loc2 have the same row value. The second condition is also true and “XXX” is printed.
loc1.getDirectionToward(loc2) returns 270 (Location.WEST). The third condition is false so nothing else is
printed.
Question 22
Case I correctly calculates the desired direction by getting the direction the bug is facing, adding Location.RIGHt for
the 90 degree right turn, then modding the result by Location.FULL_CIRCLE (360) to correctly handle values that
exceed 360. Case I then runs super.turn until the bug’s direction matches the desired direction. super.turn turns 45
degrees to the right, so running it repeatedly will eventually result in the bug facing in the desired direction. Case I works
as intended.
Case II takes a much simpler approach and runs super.turn twice, which correctly accomplishes a 90 degree right turn.
4
2009 AP Computer Science A Exam Multiple Choice Explanations 4
Case III explicitly sets the direction to the bug’s original direction plus Location.RIGHT. The setDirection method
handles values &gt= 360 so Case III also works correctly.
Question 23
Both Bug and Critter extend Actor which has method getDirection. Lines 1, 2, and 3 are syntactically correct (do
not cause a compile time error).
Rock does not contain a getMoveLocations method, so Line 4 is syntactically incorrect (causes a compile time error).
Critter does contain a getMoveLocations method with the appropriate signature, so Line 5 is syntactically correct.
Question 24
The act method of TestBug uses the canMove and move methods from its superclass Bug. canMove from Bug checks if
the location in front of the bug is empty or contains a flower while move moves to the location in front of the bug.
When act is run on t, the TestBug does the following:
 Checks its forward location (2, 2) and finds it empty
 Moves to location (2, 2)
 Checks the next forward location (1, 2) and finds it empty
 Moves to location (1, 2)
The code in the else statement is never run. The bug just moves forward two locations and does not change its direction.
Question 25
Case I: DancingCritter.getActors returns a list of neighboring DancingCritter objects rather than the list of all
neighbors returned by Critter.getActors. When DancingCritter.processActors calls
super.processActors, the superclass method does not receive the neighbors it is supposed to remove.
Case II: DancingCritter.processActors fails to call the superclass method to remove actors like a Critter.
Case III: makeMove is an acceptable place to turn. DancingCritter.makeMove adheres to the postconditions of
makeMove, which permit turning.
Question 26
This problem is most easily solved by tracing the loop for each value of k. It can also be solved by recognizing the pattern;
however, correctly identifying the number of times the loop runs is critical. A trace of the loop for each value of k is below.
0: 0 is printed
2: 2 is printed
3: 0 is printed
5: 2 is printed
6: 0 is printed
8: 2 is printed
9: 0 is printed
k becomes 11 and the loop terminates. All values are printed on the same line as 0 2 0 2 0 2 0.
Question 27
The given method should assume that all numbers are even until it is determined that at least one is not. isEven should
be initialized to true and set to false as soon as a number that is not even is detected. This is exactly what Answer C
does.
Answer A initializes isEven to false and sets it to true as soon as a single even number is found. This detects whether
any number in arr is even, not whether all numbers are even.
Answers B, D and E all contain the same error. The else statement in each answer’s /* loop body */ means that the
final value of isEven is based only on the last value checked from arr. The initial value assigned to isEven is irrelevant
as is the condition checked in each answer’s if statement.
5
2009 AP Computer Science A Exam Multiple Choice Explanations 4
Question 28
In the last line, !result is equivalent to !(x < y) which is equivalent to (x >= y).
The last line is actually equivalent to ( (x >= y) && (x >= y) ) which is obviously true if and only if x >= y.
Question 29
When n is 4, the outer loop runs 4 times. For each run of the outer loop, the inner loop runs outer + 1 times. Each time
the inner loop runs, it prints outer. A trace of the output from the inner loop for each value of outer is below.
0: 0
1: 1 1
2: 2 2 2
3: 3 3 3 3
All output is on the same line, so the output is 0 1 1 2 2 2 3 3 3 3
Question 30
Answers A and B compile because Base has the required constructors. The reference and object types are identical.
Answer C compiles because Sub (the object type) is a subclass of Base (the reference type). Referring to a subclass object
with a superclass reference is acceptable.
Answer D compiles because Sub has the required constructor. The reference and object types are identical.
Answer E does not compile because Sub does not have a constructor with a parameter (so new Sub(5) is not
syntactically valid).
Question 31
If a is not less than b and a is not greater than b, a must be equal to b. The expression is equivalent to a == b.
Question 32
This problem is most easily solved by tracing the loop.
Before 1st run: a = 24, b = 30
1st run: r = 24, a = 30, b = 24
2nd run: r = 6, a = 24, b = 6
3rd run: r = 0, a = 6, b = 0
The loop terminates after the 3rd iteration because b != 0 is false. After the loop, r does not exist (its scope is the
loop), a = 6 and b = 0. The println statement prints a which is 6.
Question 33
The outer loop runs lim times. The inner loop runs lim – outer + 1 times for each run of the outer loop. lim is 10.
For each value of outer, s is incremented as shown below.
1: s += 10
2: s += 9
3: s += 8
…
10: s += 1
s is 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 which is 55.
Question 34
The loop must continue until pos exceeds the bounds of arr or until val is found. To avoid an exception when checking
arr[pos], the bounds check must be performed first.
6
2009 AP Computer Science A Exam Multiple Choice Explanations 4
Answer A correctly stops the loop when either condition described above is met. It also prevents an exception by checking
that pos is valid before checking arr[pos].
Answer B fails to ensure that pos is valid before checking arr[pos], so it will crash if val is not found.
Answer C incorrectly allows the loop to continue if either condition is true rather than requiring that both be true.
Answer D incorrectly continues the loop only if val has been found, rather than when val has not been found. It will also
crash if it gets to the end of arr (if every value is val).
Answer E will always continue until it exceeds the bounds of arr and crashes.
Question 35
Case I visits the numbers 1, 4, 7, 10, 13, 16, 19 and prints those such that k % 3 == 1. This condition is true for each
number visited, so the loop produces the desired output.
Case II visits each number 1 <= k < 20 and prints those such that k % 3 == 1. This condition is true for each
number in the desired output and no others, so the loop produces the desired output.
Case III visits the numbers 1, 4, 7, 10, 13, 16, 19 and prints each number. This produces the desired output.
Question 36
All arguments in Java are passed by value. This means that the parameter becomes a copy of the value of the argument.
For an object reference the parameter becomes a copy of the value of the reference. The object to which the reference
refers is not copied. In other words, both the argument and the parameter refer to the same object. Variables of type
int[] are references to objects of type int[].
When nums is passed to as an argument to changeIt, list becomes a copy of the reference to the array. The array
itself is not copied. nums and list are separate references to the same array. The first line of changeIt assigns list to
refer to a new int[]. nums remains a reference to the original array. None of the changes to the array to which list
refers affect the array to which nums refers.
When the primitive type value is passed as an argument to changeIt, num is assigned the value 6. There is no further
connection between num and value. The change made to num in changeIt has no affect on value.
Question 37
Case I incorrectly declares a local variable seq and fills it with random values. The instance fields seq remains null.
Case II correctly initializes the instance fields and fills it with random values.
Case III declares an initializes a temporary ArrayList, fills it with random values, then assigns the instance field seq to
refer to it. Although this unnecessary, it does work as intended.
Question 38
Calculations with double values are subject to roundoff error. Calculations with int values are subject to overflow;
however, a and b are not of type int. None of the other answers would explain the discrepancy.
Question 39
recur first computes and stores val % 3 as a String dig. It then either returns dig or returns dig with the value of a
recursive call concatenated.
My Stack based trace of 2009 AP CS A Multiple Choice #39 shows a step by step solution.
Question 40
My Stack based trace of 2009 AP CS A Multiple Choice #40 shows a step by step solution.
7
Download