0% found this document useful (0 votes)
11 views

AP CS Java Arrays Answers

The document consists of a series of answers and explanations for a programming-related assessment, detailing the reasoning behind each answer choice for various coding scenarios. It covers topics such as array manipulation, object handling, and algorithm efficiency, providing insights into common pitfalls and correct practices. Each explanation clarifies the logic behind the selected answers, emphasizing the importance of understanding data structures and their behaviors in programming.

Uploaded by

Shreyas Parekh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

AP CS Java Arrays Answers

The document consists of a series of answers and explanations for a programming-related assessment, detailing the reasoning behind each answer choice for various coding scenarios. It covers topics such as array manipulation, object handling, and algorithm efficiency, providing insights into common pitfalls and correct practices. Each explanation clarifies the logic behind the selected answers, emphasizing the importance of understanding data structures and their behaviors in programming.

Uploaded by

Shreyas Parekh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

24.

C
25. D
26. A
27. E
28. D
29. D
30. E
31. A
32. A
33. B
34. D
35. B
36. D
37. D
38. E
39. E
40. D
41. C
42. A
43. E

Answer Explanations
1. (E) Segment I is an initializer list which is equivalent to

Segment II creates four slots for integers, which by default are


initialized to 0. The for loop in segment III is therefore unnecessary.
It is not, however, incorrect.
2. (C) If arr contains no negative integers, the value of i will
eventually exceed N-1, and arr[i] will cause an
ArrayIndexOutOfBoundsException to be thrown.

3. (E) The intent is to sum elements arr[0], arr[1], …,


arr[arr.length-1]. Notice, however, that when i has the value
arr.length-1, it is incremented to arr.length in the loop, so the
statement sum += arr[i] uses arr[arr.length], which is out of
range.
4. (A) The code segment has the effect of removing all occurrences of 0
from array arr1. The algorithm copies the nonzero elements to the
front of arr1. Then it transfers them to array arr2.
5. (C) If arr[i] < someValue for all i from 2 to k, SMALL will be
printed on each iteration of the for loop. Since there are k - 1
iterations, the maximum number of times that SMALL can be printed is
k - 1.

6. (C) Array arr is changed by doSomething. Here are the memory


slots:
7. (D) Arrays are of fixed length and do not shrink or grow if the size of
the data set varies. An ArrayList automatically resizes the list.
Choice A is false: The [] notation is compact and easy to use. Choice
B is not a valid reason because an array arr also provides instant
access to its length with the quantity arr.length. Choice C is invalid
because an array can also contain objects. Also, generality is beside
the point in the given program: The list must hold String objects.
Choice E is false: Whether a String object is arr[i] or
list.get(i), the String methods are equally easy to invoke.

8. (A) In order for numerical elements to be added to an ArrayList,


each element must be wrapped in a wrapper class before insertion
into the list. Then, to retrieve a numerical value from the ArrayList,
the element must be unboxed using the intValue or doubleValue
methods. Even though these operations can be taken care of with
autoboxing and unboxing, there are efficiency costs. In an array, you
simply use the [] notation for assignment (as in arr[i] = num) or
retrieval (value = arr[i]). Note that choices B and C are false
statements: Both insertion and deletion for an array involve writing
code to shift elements. An ArrayList automatically takes care of this
through its add and remove methods. Choice D is a poor reason for
choosing an array. While the get and set methods of ArrayList
might be slightly more awkward than using the [] notation, both
mechanisms work pretty easily. Choice E is false: Efficiency of
access is roughly the same.
9. (D) For each Address object a in list, access the name of the object
with a.getName().
10. (B) Since the Address class does not have a toString method, each
data field must explicitly be printed. Segment III would work if there
were a toString method for the class (but there isn’t, so it doesn’t!).
Segment I fails because of incorrect use of the enhanced for loop:
The array index should not be accessed.
11. (C) Each Student name must be accessed via the getName()
accessor of the Address class. The expression
student.getAddress() accesses the entire address of that student.
The name field is then accessed using the getName() accessor of the
Address class.

12. (E) Both correct solutions are careful not to lose the student who has
the highest idNum so far. Segment II does it by storing a reference to
the student, highestSoFar. Segment III does it by storing the array
index of that student. Code segment I is incorrect because it returns
the first student whose idNum is greater than max, not necessarily the
student with the highest idNum in the list.
13. (B) For each i, tickList[i] is a new Ticket object that must be
constructed using the Ticket constructor. Therefore eliminate
choices C, D, and E. Choice A is wrong because getRow(),
getSeat(), and getPrice() are accessors for values that already
exist for some Ticket object. Note also the absence of the dot
member construct.
14. (C) To access the price for each Ticket in the tickList array, the
getPrice() accessor in the Ticket class must be used, since price
is private to that class. This eliminates choices A and E. Choice B
uses the array name incorrectly. Choices D and E incorrectly declare
a Transaction object. (The method applies to an existing
Transaction object.)

15. (A) An array of type Transaction is required. This eliminates


choices C and D. Additionally, choices B and D incorrectly use type
Ticket on the right-hand side. Choice E puts the identifier
listOfSales in the wrong place.

16. (B) There are two problems with the segment as given:
1. arr[1] is not tested.
2. When i has a value of n-1, incrementing i will lead to an
out-of-range error for the if(arr[i] < min) test.
Modification II corrects both these errors. The change suggested in
III corrects neither of these errors. The change in I corrects (1) but not
(2).
17. (A) Notice that either vIndex or wIndex is incremented at the end of
the loop. This means that, when the loop is exited, the current values
of v[vIndex] and w[wIndex] have not been compared. Therefore,
you can only make an assertion for values v[0]..v[vIndex-1] and
w[0]..w[wIndex-1]. Also, notice that if there is no common value in
the arrays, the exiting condition for the while loop will be that the
end of one of the arrays has been reached, namely vIndex equals N
or wIndex equals M.
18. (B) Objects in an array can be changed in an enhanced for loop by
using mutator methods of the objects’ class. The changeStatus
method, a mutator in the Book class, will work as intended in the
given code. Choice C would be true if it were not given that each
Book in bookList was initialized. If any given b had a value of null,
then a NullPointerException would be thrown.
19. (D) The declaration must start with the type of value in the array,
namely BingoCard. This eliminates choices A and E. Eliminate
choice B: The type on the right of the assignment should be
BingoCard. Choice C is wrong because the number of slots in the
array should be NUMPLAYERS, not 20.
20. (C) Segment III is the only segment that works, since the enhanced
for loop should not be used to replace elements in an array. After the
declaration
BingoCard[] players = new BingoCard[NUMPLAYERS];

each element in the players array is null. The intent in the given
code is to replace each null reference with a newly constructed
BingoCard.

21. (D) The big defect of Algorithm 2 is that it eventually slows down.
This is because every time it selects an empty element, it has to loop
again. Each of the other choices is true. In choice A, for example, the
element cards[0] always moves to shuffled[0], eliminating all
permutations that have cards[0] in a different slot. For choice B, by
the time you get to assign the last element, all but two slots of the
cards array are marked empty. So, on average, you will need to go
through NUMCARDS tries to find one of those two nonempty slots. For
choice C, even though Algorithm 2 is slow, in theory every element
in cards could land in any given slot in shuffled. This is not true
for Algorithm 1, where the first element never budges out of the first
slot. For choice E, because of the precise ordering of elements in
Algorithm 1, the array will always eventually return to its original
state, assuming there are sufficient iterations.
22. (B) If starts with the value NUMCARDS, the method encounters
k
cards[NUMCARDS] on Line 7 and throws an
ArrayIndexOutOfBoundsException.
23. (E) All elements added to strList must be of type String. Each
choice satisfies this except choice E. Note that in choice D, the
expression ch + 8 becomes a String since ch is a String (just one
of the operands needs to be a String to convert the whole expression
to a String). In choice E, neither intOb nor 8 is a String.
24. (C) The effect of choice C is to adjust the size of the list to 7 and to
add the Integer 9 to the last slot (i.e., the slot with index 6).
Choices A, D, and E will all cause an IndexOutOfBoundsException
because there is no slot with index 6: the last slot has index 5. Choice
B will cause a compile-time error, since it is attempting to add an
element of type Double to a list of type Integer.
25. (D) If element is smaller than the last item in the list, it will be
compared with every item in the list. Eventually index will be
incremented to a value that is out of bounds. To avoid this error, the
test in the while loop should be

while(index < list.size() &&


element.compareTo(list.get(index)) < 0)

Notice that if element is greater than or equal to at least one item in


list, the test as given in the problem will eventually be false,
preventing an out-of-range error.
26. (A) Recall that add(index, obj) shifts all elements, starting at
index, one unit to the right, then inserts obj at position index. The
set(index, obj) method replaces the element in position index
with obj. So here is the state of list after each change:
27. (E) The value of each Coin c in coins must be accessed with
c.getValue(). This eliminates choice D. Eliminate choices A and B:
The loop accesses each Coin in the coins ArrayList, which means
that there should not be any statements attempting to get the next
Coin. Choice B would be correct if the first statement in the loop
body were

double value = c.getValue();

28. (D) Code segment III is wrong because the equals method is defined
for objects only. Since getValue returns a double, the quantities
c.getValue() and aCoin.getValue() must be compared either
using ==, or as described in the box on p. 70 (better).
29. (D) Segment II is the straightforward solution. Segment I is correct
because it initializes all slots of the matrix to 0, a perfect square. (By
default, all arrays of int or double are initialized to 0.) Segment III
fails because r is undefined in the condition c < mat[r].length. In
order to do a column-by-column traversal, you need to get the
number of columns in each row. The outer for loop could be

for (int c = 0; c < mat[0].length; c++)

Now segment III works. Note that since the array is rectangular, you
can use any index k in the conditional c < mat[k].length, provided
that k satisfies the condition 0 ≤ k < mat.length (the number of
rows).
30. (E) When col is 0: row is 3, then 2, then 1.
When col is 1: row is 3, then 2.
When col is 2: row is 3.
Here are the corresponding elements, in order, that are printed:
The fifth element in the list is mat[2][1], which is 7.
31. (A) Method alter shifts all the columns, starting at column c+1, one
column to the left. Also, it does it in a way that overwrites column c.
Here are the replacements for the method call alter(1):

32. (A) matStuff processes the row selected by the row parameter, 2 in
the method call. The row value, 2, overwrites each element in row 2.
Don’t make the mistake of selecting choice B—the row labels are 0,
1, 2.
33. (B) Hand execute this for a 2 × 2 matrix. i goes from 0 to 0 and j
goes from 0 to 0, so the only interchange is swap mat[0][0] with
mat[1][1], which suggests choice B. Check with a 3 × 3 matrix:

The elements to be interchanged are shown paired in the following


figure. The result will be a reflection through the minor diagonal.

34. (D) The method as given will throw an


ArrayIndexOutOfBoundsException. For the matrix in the example,
mat[0].length is 4. The call mat.alter(1) gives c a value of 1.
Thus, in the inner for loop, j goes from 1 to 3. When j is 3, the line
mat[i][j] = mat[i][j+1] becomes mat[i][3] = mat[i][4].
Since columns go from 0 to 3, mat[i][4] is out of range. The
changes in segments I and II both fix this problem. In each case, the
correct replacements are made for each row i: mat[i][1] =
mat[i][2] and mat[i][2] = mat[i][3]. Segment III makes the
following incorrect replacements as j goes from 3 to 2: mat[i][2] =
mat[i][3] and mat[i][1] = mat[i][2]. This will cause both
columns 1 and 2 to be overwritten. Before inserting zeros in the last
column, mat will be

This does not achieve the intended postcondition of the method.


35. (B) For the method call isThere(mat, 2, 2, "$"), the code counts
how many times "$" appears in row 2 and how many times in
column 2. The method returns true only if count == SIZE for either
the row or column pass (i.e., the whole of row 2 or the whole of
column 2 contains the symbol "$"). This eliminates choices I and II.
36. (D) The matrix mat consists of an array of rows, mat[0], mat[1],
mat[2], each of which is an array. The method alterArray swaps
the first and last elements of an array, then the second and second-
last elements, and so on, until it reaches the middle of the array. The
method call alterArray(mat[2]) performs this series of swaps on
row 2 of the matrix, the bottom row, resulting in the matrix in choice
D.
37. (D) Segment I is a row-by-row traversal; segment II is a column-by-
column traversal. Each achieves the correct postcondition. Segment
III traverses the matrix but does not alter it. All that is changed is the
local variable element. You cannot use this kind of loop to replace
elements in an array.
38. (E) Since there are 365 valid days in a year, the divisor in calculating
the average must be 365. It may appear that segments II and III are
incorrect because they include rainfall for invalid days in total.
Since these values are initialized to 0.0, however, including them in
the total won’t affect the final result.
39. (E) This is similar to the previous question, but in this case segment I
is also correct. This is because instead of replacing a matrix element,
you are modifying it using a mutator method.
40. (D) Segment I works because p is a reference to the element
pixels[row][col]. Changing p with a mutator method will change
the array. Segment II changes the two-dimensional array directly.
Segment III fails because pixels is not an array of integers.
41. (C) Look at Example 2 for this question:

Now consider one element, 12, say. It must be replaced by its vertical
mirror image 9, i.e., mat[2][3]=mat[2][0]. The value of width is 4.
See which expression in the answer choices correctly makes this
assignment. Eliminate choices A and D right away because col can
only have the values 0 and 1 in this algorithm, so mat[2][3] will not
be assigned. In choice B, when col has value 1, mat[2][3]=mat[2]
[1], an incorrect assignment. Choice C works: when row is 2 and col
is 0, mat[2][3]=mat[2][0]. In choice E, when row is 2 and col is 0,
the assignment mat[2][3]=mat[0][2] is incorrect.
42. (A) Method alter places a mirror along the major diagonal and
reflects the elements from left to right across this diagonal.
In this algorithm, when row is 1, col can only be 0, and when row is
2, col takes on the values 0 and 1. Thus, only three elements are
altered: mat[0][1], mat[0][2], and mat[1][2]. (Note that the
method assigns values to mat[col][row].) These elements are all to
the right of the diagonal. Choice A is the only choice that leaves
elements to the left of the diagonal unchanged.
43. (E) There are three things that must be done in each row:

Add an opening boundary line:

s = s + "|";

Add the symbol in each square:

Add a closing boundary line and go to the next line:

s = s + "|\n";

All of these statements must therefore be enclosed in the outer for


loop, that is,

for (int r = …)

You might also like