5 Steps to a 5 AP Computer Science A 2017 (2016)

STEP 2

Determine Your Test Readiness

CHAPTER 3   Take a Diagnostic Exam

CHAPTER 3

Take a Diagnostic Exam

IN THIS CHAPTER

Summary: This step contains a diagnostic exam that is exactly one-half the length of the actual AP Computer Science A Exam. However, in all other ways, it closely matches what you can expect to find on the real test. Use this test to familiarize yourself with the AP Computer Science A Exam and to assess your strengths and weaknesses as you begin your review for the test.

Key Ideas

   Familiarize yourself with the types of questions and the level of difficulty of the actual Computer Science A Exam early in your test preparation process.

   Use the diagnostic exam to identify the content areas on which you need to focus your test preparation efforts.

Using the Diagnostic Exam

The purpose of the diagnostic exam is to give you a feel for what the actual AP Computer Science A Exam will be like and to identify content areas that you most need to review. This diagnostic exam is one-half the length of the real exam.

When to Take the Diagnostic Exam

Since one purpose of the diagnostic exam is to give you a preview of what to expect on the AP Computer Science A Exam, you should take the exam earlier rather than later. However, if you are attempting the diagnostic exam without having studied Java yet, you may feel overwhelmed and confused. If you are starting this book in September, you may want to read a sampling of questions from the diagnostic exam, but then save the test until later when you know some Java. Taking the diagnostic exam when you begin to review will help you identify what content you already know and what content you need to revisit; then you can alter your test prep plan accordingly.

Take the diagnostic exam in this step when you begin your review, but save both of the full-length practice exams at the end of this book until after you have covered all of the material and are ready to test your abilities.

How to Administer the Exam

When you take the diagnostic exam, try to reproduce the actual testing environment as closely as possible. Find a quiet place where you will not be interrupted. Do not listen to music or watch a movie while taking the exam! You will not be able to do this on the real exam. Set a timer and stop working when the 45 minutes are up for each section. Note how far you have gotten so you can learn to pace yourself, but take some extra time to complete all the questions so you can find your areas of weakness. Use the answer sheet provided and fill in the correct ovals with a #2 pencil. Although this is a computer science exam, the AP exam is a paper-and-pencil test.

Part I of the exam contains multiple-choice questions. On the actual exam you’ll have 90 minutes to complete 40 multiple-choice questions. For this diagnostic exam, give yourself 45 minutes to complete the 20 multiple-choice questions. Note that there is no penalty for guessing on the exam, so if you’re not sure of an answer, eliminate obviously wrong answer choices and guess. You’ll find more helpful strategies to use in answering the multiple-choice questions in Step 3.

Part II of the exam consists of free-response questions. On the AP Computer Science A Exam, you’ll have 90 minutes to complete four questions, each containing multiple parts. On this diagnostic exam, give yourself 45 minutes to complete the two free-response questions. Strategies you can use to approach the free-response question efficiently and effectively can be found in Step 3. Read those strategies after you’ve tried the diagnostic exam and become familiar with the types of questions on the exam.

After Taking the Diagnostic Exam

Following the exam, you’ll find not only the answers to the test questions, but also complete explanations for each answer. Don’t just read the explanations for the questions you missed; you also need to understand the explanations for the questions you got right but weren’t sure of. In fact, it’s a good idea to work through the explanations for all the questions. Working through the step-by-step explanations is one of the most effective review tools in this book.

If you missed a lot of questions on the diagnostic exam or are just starting out learning how to program in Java, don’t stress out! Step 4 of this book explains all of the concepts that will appear on the AP Computer Science A Exam. Read Concepts 0–13 in Step 4, do the practice questions for each concept, and read the explanations so you understand what the correct answer is and why it is correct. Then you’ll be well prepared for the AP Computer Science A Exam.

On the other hand, if you did well on some of the questions on the diagnostic exam and understand the explanations for these questions, you may be able to skip some of the concepts in Step 4. Look at the summaries and key ideas that begin each of the concepts in Step 4. If you’re reasonably sure you understand a concept already, you may want to skip to that concept’s review questions or the “Rapid Review” and then move on to the next concept. A good test prep plan focuses on the areas you most need to review.

Now let’s get started.

Diagnostic Exam

Multiple-Choice Questions

ANSWER SHEET

AP Computer Science A Diagnostic Exam

Part I

Multiple Choice

Time: 45 minutes

Number of questions: 20

Percent of total score: 50

Directions: Choose the best answer for each problem. Some problems take longer than others. Consider how much time you have left before spending too much time on any one problem.

Notes:

  • The diagnostic exam is exactly one-half the length of the actual AP Computer Science A Exam.
  • You may assume that all import statements have been included where they are needed.
  • You may assume that the parameters in method calls are not null.
  • You may assume that declarations of variables and methods appear within the context of an enclosing class.
  1. Consider the following method.

What value is returned by the call someMethod(13) ?

(A)  17

(B)  25

(C)  28

(D)  31

(E)  Nothing is returned. There is a compile-time error.

  1. Consider the following code segment.

What is printed as a result of executing the code segment?

(A)  -11

(B)  4

(C)  11

(D)  13

(E)  15

  1. Assumelist is an ArrayList<Integer> that has been correctly constructed and populated with the following items.

[13, 7, 0, 5, 12, 6, 10]

Consider the following method.

What value is returned by the call calculate(list) ?

(A)  10

(B)  11

(C)  13

(D)  35

(E)  45

  1. Consider the following class declarations.

Which of the following declarations compiles without error?

  1. Planet mars = new Planet();
  2. Planet pluto = new DwarfPlanet("Pluto");

III.  Planet ceres = new DwarfPlanet();

(A)  I only

(B)  II only

(C)  I and II only

(D)  I and III only

(E)  I, II, and III

  1. Consider the following code segment.

What is printed as a result of executing the code segment?

(A)  [Zombie, Werewolf, Mummy, Witch]

(B)  [Zombie, Werewolf, Ghost, Witch]

(C)  [Zombie, Werewolf, Mummy, Ghost]

(D)  [Zombie, Vampire, Werewolf, Mummy, Ghost]

(E)  [Zombie, Vampire, Werewolf, Mummy, Witch]

  1. Consider the following interface and class declarations.

Which of the following could replace /* missing code */ so that the method getNumberOfZones returns the number of Polygons that contain the coordinate point defined by x and y ?

  1. Consider the following partial class declaration.

Assume that the following declaration has been made in the main method of another class.

Which of the following statements compiles without error?

(A)  int num = park.acres;

(B)  String name = central.getName();

(C)  boolean play = park.hasPlayground();

(D)  int num = park.getAcres(acres);

(E)  park.hasPlayground = true;

  1. Consider the following code segment.

What is printed as a result of executing the code segment?

(A)  mmm

(B)  nonono

(C)  mnomno

(D)  nomnono

(E)  mnomnomno

  1. Consider the following method.

What value is returned by the call loopy(12) ?

(A)  12

(B)  21

(C)  23

(D)  27

(E)  29

  1. Consider the following class declarations.

Consider the following code segment.

What is printed as a result of executing the code segment?

(A)  abA

(B)  aba

(C)  letterlettera

(D)  letterletterletter

(E)  Nothing is printed. There is a compile-time error.

  1. Consider the following method.

What is returned by the call lengthen("APCS") ?

(A)  "APCS"

(B)  "APCSACAA"

(C)  "APCSAPCS"

(D)  Nothing is returned. Run-time error: StringIndexOutOfBoundsException

(E)  Nothing is returned. The call will result in an infinite loop.

  1. Consider the following code segment.

What is printed as a result of executing the code segment?

(A)  1

(B)  13

(C)  13   1

(D)  2   4   5

(E)  2   4   5   9

  1. Assume thatk , m , and n have been declared and correctly initialized with int values. Consider the following statement.

For which statement below does b2 = !b1 for all values of k , m , and n ?

(A)  boolean b2 = (n >= 4) && ((m == 5 && k < 2) || (n > 12));

(B)  boolean b2 = (n < 4) || ((m != 5 || k >= 2) && (n <= 12));

(C)  boolean b2 = (n < 4) && (m != 5) && (k >= 2) || (n <= 12);

(D)  boolean b2 = (m == 5 || k < 2) && (n > 12);

(E)  boolean b2 = (n < 4);

  1. Consider the following code segment.

What is printed as a result of executing the code segment?

(A)  Nothing is printed. Runtime error: ArrayIndexOutOfBounds

(B)  18

(C)  181620

(D)  68

(E)  1820

  1. Consider the following method.

Assume that the string codeword has been declared and initialized as follows.

What value is returned by the call mystery(codeword, 9) ?

(A)  5

(B)  6

(C)  7

(D)  Nothing is returned. Infinite recursion causes a stack overflow error.

(E)  Nothing is returned. Run-time error: StringIndexOutOfBoundsException

  1. Consider the following method.

Consider the following code segment.

What is printed as a result of executing the code segment?

(A)  num = 10 val[3] = 10

(B)  num = 10 val[3] = -2

(C)  num = 10 val[4] = 8

(D)  num = -2 val[3] = 10

(E)  num = -2 val[4] = 8

  1. Consider the following code segment.

Consider these additional code segments.

III.   

Which of the code segments produce the same output as the original code segment?

(A)  I only

(B)  II only

(C)  III only

(D)  II and III only

(E)  I, II, and III

  1. Consider the following method.

The method above could be best described as an implementation of which of the following?

(A)  Insertion Sort

(B)  Binary Search

(C)  Selection Sort

(D)  Merge Sort

(E)  Sequential Sort

  1. Consider the following statement.

After executing the statement, what are the possible values for the variable number ?

(A)  All integers from 13 to 21 (inclusive).

(B)  All real numbers from 13 to 34 (not including 34).

(C)  All integers from 13 to 34 (inclusive).

(D)  All integers from 13 to 33 (inclusive).

(E)  All real numbers from 0 to 21 (not including 21).

  1. Consider the following class declaration.

Assume ArrayList<City> cities has been properly instantiated and populated with City objects.

Consider the following code segment.

Which of the following should replace /* missing code */ so that, after execution is complete, maxPop will contain the largest population that exists in the ArrayList ?

(A) 

(B) 

(C) 

(D) 

(E) maxPop should have been set to Integer.MAX_VALUE . This cannot work as written.

STOP. End of Part I.

AP Computer Science A Diagnostic Exam

Part II

Free Response

Time: 45 minutes

Number of questions: 2

Percentage of total score: 50%

Directions: Write all of your code in Java. Show all your work.

Notes:

  • The diagnostic exam is exactly one-half the length of the actual AP Computer Science A Exam.
  • You may assume all imports have been made for you.
  • You may assume that all preconditions are met when making calls to methods.
  • You may assume that all parameters within method calls are not null.
  • Be aware that you should, when possible, use methods that are defined in the classes provided as opposed to duplicating them by writing your own code.
  1. Complex Numbers

In Mathematics, a complex number is a number that is composed of both a real component and an imaginary component. Complex numbers can be expressed in the form a + bi where a and b are real numbers and i is the imaginary number  (which means that i 2 = -1). In complex expressions, a is considered the real part and b is considered the imaginary part .

You can add, subtract, multiply and divide complex numbers. Addition with complex numbers involves adding the real parts and the imaginary parts as two separate sums and expressing the answer as a new complex number. Here are some examples of the addition of complex numbers.

Example 1: 

Example 2: 

Multiplication of complex numbers involves using the distributive property, just like multiplying polynomials. The first term is always a real number (no i ), the middle two terms have an i and can be combined, and the last term has an i 2 . Remember that i 2 = -1, so, after simplifying i 2 to -1 and multiplying, the last term is a real number (no i ) and can be added to the first term.

Combine like terms: 8 + (-6) = 2 and 4i + 12i = 16i .

Write in complex number format: 2 + 16i .

Here are some additional examples of multiplication of complex numbers.

Example 1: 

Example 2: 

Write the complete ComplexNumber class , including:

  • any necessary instance variables
  • a constructor that takes twoint variables, a and b , representing the components of the complex number expressed a + bi
  • theadd method that takes another ComplexNumber object as a parameter, adds to this ComplexNumber object as described above, and returns the solution as a ComplexNumber object
  • themultiply method that takes another ComplexNumber object as a parameter, multiplies with this ComplexNumber object as described above, and returns the solution as a ComplexNumber object
  • accessor methodsgetA() and getB() for the components of the complex number

An outline of the class including method declarations follows.

  1. Coin Collector

The High School Coin Collection Club needs new software to help organize its coin collections. Each coin in the collection is represented by an object of the Coin class. The Coin class maintains three pieces of information for each coin: its country of origin, the year it was minted, and the type of coin it is. Because coin denominations vary from country to country, the club has decided to assign a coin type of 1 to the coin of lowest denomination, 2 to the next lowest, and so on. For American coins, coinType is assigned like this:

The Coin Club currently keeps track of its coins by maintaining an ArrayList of Coin objects for each country. The coins in the ArrayList are in order by year, oldest to newest. If two or more coins were minted in the same year, those coins appear in a random order with respect to the other coins from the same year.

The Coin Club has acquired some new collection boxes of various sizes to store their coins. The boxes are rectangular and contain many small compartments in a grid of rows and columns. The club will store coins from different countries in different boxes.

The CoinCollectionTools class below assists the coin club in organizing and maintaining their collection.

(a)  The CoinCollectionTools class constructor initializes the instance variable coinBox as a two-dimensional array of Coin objects with dimensions specified by the parameters. It then instantiates each of the Coin objects in the array as a default Coin object with country equal to the country name passed as a parameter, year equal to 0, and coinType equal to 0.

Complete the CoinCollectionTools class constructor.

(b)  The Coin Club intends to fill the collection boxes from their list of coins, starting in the upper left corner and moving down the columns in order until all Coin objects have been placed in a compartment.

The fillCoinBox method takes as a parameter an ArrayList of Coin objects in order by year minted and returns a chart showing their position in the box, filled in column-major order.

You may assume that coinBox is initialized as intended, regardless of what you wrote in part (a).

Complete the method fillCoinBox .

(c)  Sometimes the Coin Club would prefer to see a list of its coins organized by coin type.

The fillCoinTypeList method uses the values in coinBox to create and return an ArrayList of Coin objects filled first with all the Coin objects of type 1, then type 2, and so on through type 6. You may assume that no country has more than 6 coin types. Note that the number of coins from any specific type may be 0.

Since the original coinBox was filled in column-major order, Coin objects should be retrieved from the coinBox in column-major order. This will maintain ordering by year within each coin type.

Remember that the CoinCollectionTools class constructor filled the coinBox with default Coin objects with a coinType of 0, so no entry in the coinBox is null .

You may assume that coinBox is initialized and filled as intended, regardless of what you wrote in parts (a) and (b).

Complete the method fillCoinTypeList .

STOP. End of Part II.

Diagnostic Exam Answers and Explanations

Part I (Multiple-Choice) Answers and Explanations

Bullets mark each step in the process of arriving at the correct solution.

  1. The answer is B.
  • When we first enter the loop, val = 13 and i = 2. The if condition is looking for even numbers. Since val + i is odd, we skip the if clause. Increment i to 3. i < 7 so we continue.
  • val = 13, i = 3. This time val + i is even, so add 3 to val. val = 16, increment i to 4, i < 7 so we continue.
  • val = 16, i = 4. val + i is even, add 3 to val. val = 19, increment i to 5, i < 7, continue.
  • val = 19, i = 5. val + i is even, add 3 to val. val = 22, increment i to 6, i < 7, continue.
  • val = 22, i = 6. val + is even, add 3 to val. val = 25, increment i to 7. This time, when we check the loop condition, i is too big, so we exit the loop.
  • val = 25 and that is what is returned.
  1. The answer is E.
  • The first if condition evaluates to (2 < 5 && 13 < 5), which is false, so we skip to the else clause.
  • The else clause has its own if statement. The condition evaluates to (2 = = 2 && 13 < 2), which is false, so we skip to the else clause.
  • result = 2 + 13 = 15, which is what is printed.
  1. The answer is D.
  • The for-each loop can be read like this: for each Integer in numbers, which I am going to call n.
  • The if clause is executed only when the element is > 8, so the loop adds all the elements greater than 8 to the sum variable.
  • The elements greater than 8 are 13, 12, and 10, so sum = 35, and that is what the method returns.
  1. The answer is C.
  • Option I is correct. The reference variable type Planet matches the Planet object being instantiated, and the Planet class contains a no-argument constructor.
  • Option II is correct. The reference variable type Planet is a superclass of the DwarfPlanet object being instantiated, and the DwarfPlanet class contains a constructor that takes one String parameter.
  • Option III is not correct. Although the reference variable type Planet is a superclass of the DwarfPlanet object being instantiated, the DwarfPlanet class does not contain a no-argument constructor. Unlike a method, the constructor of the parent class is not inherited.
  1. The answer is A.
  • Let’s picture the contents of our ArrayList in a table. After the 3 adds, we have:

Setting 0 to Zombie gives us:

Adding Mummy at position 2 pushes Ghost over one position:

Witch gets added at the end:

After the remove at index 3, Ghost goes away and Witch shifts over one:

  1. The answer is E.
  • Options A, B, and C can be eliminated because they return a boolean. If we look at the method declaration, we can see that this method must return an int.
  • The difference between D and E is a matter of syntax. We are trying to say if the element contains (x, y) increment total. The for-each loop can be read like this: for each Polygon in zones, which I am going to call p… and there’s the answer. I’m going to call each Polygon p, so I want p.contains(x, y).
  1. The answer is C.
  • Option A will not compile, because acres is a private instance variable.
  • Option B will not compile, because the name of the object is park, not central.
  • Option C is correct. The method is called properly and it returns a boolean.
  • Option D will not compile, because getAcres does not take a parameter.
  • Option E will not compile, because hasPlayground is not a public boolean variable.
  1. The answer is B.
  • The for loop goes through the entire string, looking at each character individually. If the character is an m, the substrings add the section of the stringbefore the m to the section of the string after the m, leaving out the m.
  • The result is that all the m’s are removed from the string, and the rest of the string is untouched.
  1. The answer is D.
  • This is a recursive method. Let’s trace the calls. The parts initalics were filled in on the way back up. That is, the calls in the plain type were written top to bottom until the base case returned a value. Then the answer were filled in bottom to top .

loopy (12) = loopy(15) + 2 = 25 + 2 = 27 , which gives us our final answer.

loopy(15) = loopy(18) + 2 = 23 + 2 = 25

loopy(18) = loopy(21) + 2 = 21 + 2 = 23

loopy(21) Base Case! return 21

  1. The answer is B.
  • The compiler looks at the left side of the equals sign and checks to be sure that whatever methods are called are available to variables of that type. Since Letter and ALetter both contain toString methods, the compiler is fine with the code. Option E is incorrect.
  • The run-time environment looks at the right side of the equals sign and calls the version of the method that is appropriate for that type.
  • System.out.print(x) results in an implicit call to the ALetter toString method, and prints "a".
  • System.out.print(y) results in an implicit call to the BLetter toString method and prints "b".
  • System.out.print(z) tries to make an implicit call to a CapALetter toString method, but there isn’t one, so it moves up the hierarchy and calls the toString method of the ALetter class and prints "a".
  1. The correct answer is B.
  • On entry, word = "APCS" and index = 0.

word = word + its substring from 0 to 1, or "A". word = "APCSA".

  • Add 2 to index, index = 2. word.length() is 5, 2 < 5 so continue.

word = word + its substring from 2 to 3, or "C". word = "APCSAC".

  • Add 2 to index, index = 4. word.length() is 6, 4 < 6, so continue.

word = word + its substring from 4 to 5, or "A". word = "APCSACA".

  • Add 2 to index, index = 6. word.length() is 7, 6 < 7, so continue.

word = word + its substring from 6 to 7, or "A". word = "APCSACAA".

  • Add 2 to index, index = 8. wordlength() is 8, 8 is not < 8 so the loop exits.
  • Notice that since word is altered in the loop, word.length() is different each time we evaluate it at the top of the loop. You can’t just replace it with 4, the length of word at the beginning of the method. You must re-evaluate it each time through the loop.
  1. The answer is C.
  • Each time through the loop:
  • We are considering element n.
  • We calculate array[n] – array[n – 1] and compare it to array[n] – array[n + 1]. In other words subtract the element before from the nth element, then subtract the element after from the nth element. If the before subtraction < the after subtraction, print n.
  • Let’s make a table. As a reminder, here is our array:
  • Printing array[n] in the YES cases gives us 13 1. Remember that we are printing theelement not the index .
  1. The answer is C.
  • We want to negate our expression, so we are trying to solve this (note the added ! at the beginning).
  • DeMorgan’s theorem tells us that we can distribute the !, but we must change AND to OR and OR to AND when we do that. Let’s take it step by step.
  • Distribute the ! to the 2 expressions around the|| (which will change to &&).
  • !(n >= 4) is the same as (n < 4).
  • Now let’s distribute the ! to the expression around the second && (which becomes|| ).
  • Fix the !(n > 12) because that’s easy.
  • One to go! Distribute the ! around the|| in parentheses (which becomes &&).
  • Simplify those last two simple expressions.
  • A good way to double-check your solution is to assign values to m, n, and k and plug them in. If you don’t think you can simplify the expression correctly, assigning values and plugging them in is another way to find the answer, though you may need to check several sets of values to be sure you’ve found the expression that works every time.
  1. The answer is E.
  • Consider Option A. Can an index be out of bounds? The largest values m and n will reach are 4 and 6, respectively. 4 + 6 = 10, and ray[10] is the 11th element in the array (because we start counting at 0). The array has a length of 11, so we will not index out of bounds.
  • Look at the first for loop. The array is being filled with elements that are equal to twice their indices, so the contents of the array look like { 0, 2, 4, 6, 8, … }.
  • Look at the nested for loop. The outer loop will start at m = 0 and continue through m = 4. For each value of m, n will loop through 0, 2, 4, 6, because n is being incremented by 2. (It’s easy to assume all loops use n++. Look!)
  • We are looking for m + n > 8. Since the largest value for n is 6, that will not happen when m is 0, 1, or 2.
  • The first time m + n is greater than 8 is when m = 3 and n = 6.

ray[3 + 6] = ray[9] = 2 * 9 = 18. Print 18.

  • The next time m + n is greater than 8 is when m = 4 and n = 6.

ray[4 + 6] = ray[10] = 2 * 10 = 20. Print 20.

  • Notice that we aren’t printing any spaces, so the 1820 are printed right next to each other.
  1. The answer is E.
  • This is a recursive method. Let’s trace the calls.

mystery("advanced placement", 9) = mystery("vanced placement", 10)

mystery("vanced placement", 10) = mystery("nced placement", 11)

mystery("nced placement", 11) = mystery("ed placement", 12)

mystery("ed placement", 12) = mystery ("placement", 13)

  • By this point we should have noticed that we are getting farther and farther from the base case. What will happen when we run out of characters? Let’s keep going and see.

mystery("placement", 13) = mystery("lacement", 14)

mystery("lacement", 14 = mystery("cement", 15)

mystery("cement", 15) = mystery("ment", 16)

mystery ("ment", 16)= mystery("nt", 17)

  • "nt".substring(2) is, somewhat surprisingly, a valid expression. You are allowed to begin a substring just past the end of a string. This call will return an empty string.

mystery ("nt", 17) = mystery("", 18)

  • This time code.substring(2) fails:StringIndexOutOfBoundsException .
  1. The answer is A.
  • This problem requires you to understand that primitives are passed by value and objects are passed by reference.
  • When a primitive argument (or actual parameter) is passed to a method, its value is copied into the formal parameter. Changing the formal parameter inside the method will have no effect on the value of the variable passed in; num and index will not be changed by the method.
  • When an object is passed to a method, its reference is copied into the formal parameter. The actual and formal parameters become aliases of each other; that is, they both point to the same object. Therefore, when the object is changed inside the method, those changes will be seen outside of the method. Changes to array nums inside the method will be seen in array val outside of the method.
  • num and index remain equal to 10 and 3, respectively, but val[3] has been changed to 10.
  1. The answer is B.
  • The original code segment is a nested loop. The outer loop has an index, which will take on the values 2, 4, 6. For each of those values, the inner loop has an index, which will take on the values 30, 20, 10. The code segment will print:

(2+30) (2+20) (2+10) (4+30) (4+20) (4+10) (6+30) (6+20) (6+10) = 32 22 12 34 24 14 36 26 16

We need to see which of I, II, III also produce that output.

  • Option I is a for loop. On entry, num = 32, count = 0, i = 0.
  • 32 is printed, num = 34, count % 3 = 0, so we execute the if clause and set count = 0 and num = 20.
  • Next time through the loop, 20 is printed . . . oops, no good! Eliminate option I.
  • Option II is a while loop. On entry, num = 32.
  • 32 is printed, num = 22, if condition is false.
  • Next time through the loop, 22 is printed, num = 12, if condition is false.
  • 12 is printed, num = 2, if condition is true, num = 34.
  • 34 is printed, num = 24, if condition is false.
  • 24 is printed, num = 14, if condition is false.
  • 14 is printed num = 4, if condition is true, num = 36.
  • 36 is printed, num = 26, if condition is false.
  • 26 is printed, num = 16, if condition is false.
  • 16 is printed, num = 6, if condition is true, num = 38.
  • Loop terminates – looks good! Option II is correct.
  • Option III is a nested for loop.
  • The first time through the loops, h = 0, k = 30,
  • h + k = 30, so 30 is printed. That’s incorrect. Eliminate option III.
  1. The answer is A.
  • This is one way of implementing the Insertion Sort algorithm. The interesting thing about this implementation is the use of a compound condition in the for loop. This condition says “Continue until you reach the beginning of the array OR until the element we are looking at is bigger than the key.” When the for loop exits, the “key” is put into the open slot at position j. That’s an Insertion Sort algorithm.
  • Looking at this problem a different way:
  • It can’t be B. If this were a search algorithm, there would have to be a parameter to tell us what element we are looking for, and that isn’t the case.
  • It can’t be D because Merge Sort is recursive and there’s no recursion in this code segment.
  • It can’t be E, because we know Sequential Search but there isn’t a Sequential Sort.
  • That just leaves Selection Sort. Selection Sort has nested for loops, but the loops have no conditional exit. They always go to the end of the array. And on exit, elements are swapped. There’s no swap code here.
  1. The answer is D.
  • The general form for generating a random number betweenhigh and low is
  • high – low + 1 = 21, low = 13, so high = 33.
  • The correct answer is integers between 13 and 33 inclusive.
  1. The answer is D.
  • Option A is incorrect. It uses array syntax rather than ArrayList syntax to retrieve the element.
  • Option B is incorrect. It attempts to access the instance variable population directly, but population is private (as it should be).
  • Option C is incorrect. First of all, the algorithm is wrong. It is only comparing the population in consecutive elements of the ArrayList, not in the ArrayList overall. In addition, it will end with an IndexOutOfBoundsException, because it uses (i + 1) as an index.
  • Option D works correctly. It accesses the population using the getter method, and it compares the accessed population to the previous max.
  • Option E is incorrect. If we began by setting maxPop = Integer.MAX_VALUE, then that is the value maxPop will have when the code segment completes.

Part II (Free-Response) Solutions

Please keep in mind that there are multiple ways to write the solution to a free-response question, but the general and refined statements of the problem should be pretty much the same for everyone. Look at the algorithms and coded solutions, and determine if yours accomplishes the same task.

General penalties (assessed only once per problem):

-1    using a local variable without first declaring it

-1    returning a value from a void method or constructor

-1    accessing an array or ArrayList incorrectly

-1    overwriting information passed as a parameter

-1    including unnecessary code that causes a side effect like a compile error or console output

  1. Complex Numbers

General Problem: Write a ComplexNumber class that will represent a complex number and allow addition and multiplication of two ComplexNumber objects.

Refined Problem: Write a ComplexNumber class that includes:

  • instance variables representing the real and imaginary components of the complex number,
  • a valid constructor that takes 2 parameters,
  • methods for multiplication and addition of ComplexNumbers that take the second ComplexNumber object as a parameter and return the answer in a ComplexNumber object, and
  • accessors (getters) for the instance variables.

Algorithm:

  • Declare two instance variables, a and b.
  • Write a constructor that assigns passed values to the instance variables.
  • Write an add method that adds the a and b components of the passed object to the a and b components of this object, places the result in a new ComplexNumber object, and returns it.
  • Write a multiply method that does the 4 required multiplications using the a and b components of the passed object and the a and b components of this object, simplifies the result remembering to multiply the last term by -1, places the result in a new ComplexNumber object, and returns it.
  • Write the accessors (getters) for a and b.

Java Code:

Common Errors:

  • Remember to instantiate a new ComplexNumbers object in the add and multiply methods.
  • Check the arithmetic carefully in the multiply method, and don’t forget the -1.

Java Alternate Solution:

  • The add and multiply methods can be written without the extra variables, but the statements become awfully long and complex.

Scoring Guidelines:

+1 Instantiates 2 private instance variables and initializes them to passed parameters in the constructor

+3 Implements the add method

+1    Accesses the 2 components of the parameter ComplexNumber

+1    Adds the components of the parameter to the components of this object

+1    Instantiates and returns a new ComplexNumber object, containing the correct sum

+4 Implements the multiply method

+1    Multiplies this real component by other real component and multiplies this imaginary component by other imaginary component by -1

+1    Multiplies this real component by other imaginary component and this imaginary component by other real component

+1    Adds the four results to find the real and imaginary components of the product

+1    Instantiates and returns a new ComplexNumber object, containing the correct product

+1    Correctly implements accessors for both instance variables

  1. Coin Collector

(a)  General Problem: Complete the CoinCollectionTools class constructor.

Refined Problem: Instantiate the instance variable coinBox as a new array of the size specified by the parameters. Traverse the array filling every cell with a Coin object instantiated with country = the country parameter, year = 0, and coinType = 0.

Algorithm:

  • Instantiate coinBox as a new array of Coin objects with dimensions [rows][columns].
  • Outer loop: traverse the rows of the array.

Inner loop: traverse the columns of the array.

  • Instantiate a new Coin object, passing parameters (country, 0, 0).

Java Code:

Common Errors:

  • If you look above the constructor in the code for the class, you will see that the coinBox has been declared as an instance variable. If you write:

then you are declaring a different array named coinBox that exists only within the constructor. The instance variable coinBox has not been instantiated.

Java Code Alternate Solution:

If you read the whole problem before starting to code, you might have noticed that the other two parts work in column-major order. You can write this in column-major order also. Since you are filling every cell with the same information, it doesn’t make any difference.

(b)  General Problem: Complete the fillCoinBox method.

Refined Problem: The parameter myCoins is an ArrayList of Coin objects in order by year minted. Assign them to the coinBox grid in column-major order.

Algorithm:

  • Create a count variable.
  • Loop through all of the Coin objects in myCoins using variable count as the loop counter.
  • Update the row and column variables based on count.
  • Get the next Coin object from the ArrayList, and place it in the coinBox location specified by the row and column variables.
  • Increment the count variable.
  • Return the completed coinBox.

Java Code:

Java Code Alternate Solution #1:

You may not have thought of using % and / to keep track of column and row. Here’s another way to do it.

Java Code Alternate Solution #2:

This solution bases its loops on the grid, rather than the ArrayList.

Common Errors:

  • Do not count on the fact that you can fill the entire grid. It is tempting to write nested for loops that traverse the whole grid, but if there are fewer Coin objects in the ArrayList than elements in the grid, your program will terminate with an IndexOutOfBoundsException.
  • It is common to write the row and column loops in the wrong order. In column-major order, columns vary slower than rows (we do all the rows before we change columns), so the column loop is the outer loop. In row-major order, the row loop is the outer loop.
  • Even though we are filling our array in column-major order, the syntax for specifying the element we want to fill is coinBox[row][column], not the other way around.
  • If you used remove instead of get when accessing the Coin objects in the ArrayList, you modified the list and that’s not allowed. It’s calleddestruction of persistent data and may be penalized.
  • In the solutions that loop through the grid (Alternates #2 and #3), be careful not to use incorrect notation for the end conditions. In general, the number of rows is arrayName.length and the number of columns is arrayName[row].length. When processing in column-major order, the loop that varies the column is the outer loop. We cannot use the loop variable row as the array index when finding the length of a column, because it does not exist outside of the inner loop. Since this is not a ragged array, it is safe to use [0] as our index.

(c)  General Problem: Complete the fillCoinTypeList method.

Refined Problem: Given a coinBox as created by part (a) and filled in part (b), create a list that contains Coins in order by coin type (1–6). If Coins are retrieved from the coinBox in column-major order, they will already be in order by year.

Algorithm:

  • Loop 1: Complete the inner loops 6 times, once for each coin type 1–6.
  • Loop 2: Loop through the columns.
  • Loop 3: Loop through the rows.
  • If the Coin object at the row-column location specified by the loop counters of loops 2 and 3 matches the coinType specified from the loop counter of loop 1:
  • Add the Coin object to the ArrayList.
  • Return the ArrayList of Coin objects.

Java Code:

Common Errors:

  • You should not create a new Coin object to add to the myCoins list. The Coin object already exists in the array.
  • Do not worry about the default Coins added in the constructor. Since they have a coinType of 0, they will be ignored.

Scoring Guidelines:

Sample Driver:

There are many ways to write these methods. Maybe yours is a bit different from our sample solutions and you are not sure if it works. Here is a sample driver program. Running it will let you see if your code works, and will help you debug it if it does not.

Copy CoinCollectionToolsDriver into your IDE along with the complete Coin and CoinCollectionTools classes (including your solutions). You will also need to add this import statement as the first line in your CoinCollectionTools class: import java.util.ArrayList;