AP Computer Science A • Unit 4.5

Implementing Array Algorithms

Detailed answer explanations for the Unit 4.5 multiple-choice practice questions.

Q1B
Q2A
Q3B
Q4C
Q5D
Q6B
Q7C
Q8B
Q9B
Q10A
Q11C
Q12B
Q13A
Q14D
How to use this page: First try each question without looking at the explanation. Then compare your answer with the key and read why the other choices are not correct.

Answer Explanations

Q1

Which variable is commonly used to count how many array elements satisfy a condition?

AAn accumulator that stores a running sum
BA counter
CA Boolean flag that records whether a match exists
DThe index variable used to traverse the array
Correct answer: B. A counter is the variable the count pattern increments once for every element that satisfies the condition.
Explanation

The count pattern starts a counter at 0 before the traversal, increments it inside an if, and returns it after the loop. Because a later element could still match, the finished count is known only after every value has been visited.

  • A is not correct: An accumulator adds the element values themselves to a running total, which measures how much the array holds rather than how many elements matched.
  • C is not correct: A Boolean flag records only whether a match exists at all, so it cannot distinguish one matching element from many of them.
  • D is not correct: The index variable tracks which position the traversal is visiting, and it advances on every iteration whether or not the element matches.
Q2

After a nonempty array has been totaled in a double total, which expression computes its average?

Atotal / values.length
Bvalues.length / total
Ctotal / (values.length - 1)
Dtotal
Correct answer: A. Dividing the accumulated total by the number of elements is exactly what getAverage does with values.length.
Explanation

An accumulator algorithm initializes total before the loop, adds each value inside the loop, and then uses that total. The average step divides the finished total by the element count, which is why the array must be nonempty.

  • B is not correct: This inverts the division; dividing the element count by the total does not describe a typical value of the array.
  • C is not correct: Dividing by values.length - 1 uses one fewer than the number of values that were actually added into total.
  • D is not correct: total by itself is the sum; it becomes an average only after being divided by the number of elements.
Q3

When finding the maximum value in a nonempty array, what is a common initialization?

ASet max to nums.length always.
BSet max to the first array element.
CDo not initialize max.
DSet max to 0 always.
Correct answer: B. Initializing max from the first array element guarantees the starting value is one the nonempty array actually contains.
Explanation

The section warns against starting a maximum or minimum at an arbitrary value unless that value is guaranteed to be safe. findMin shows the reliable pattern: take the first element, then replace it whenever a better value appears.

  • A is not correct: nums.length counts the elements rather than being one of them, so it is just an arbitrary number that may exceed every stored value.
  • C is not correct: With no initialization there is no value to compare against and no value to return if no update ever happens.
  • D is not correct: 0 is an arbitrary starting value; if every stored value is negative, the method would report a maximum the array never held.
Q4

Which pattern is useful for determining whether an array contains a target?

AA nested-loop duplicate check
BAn accumulator that adds every array value
CA traversal that returns true when the target is found
DAn adjacent-pair traversal
Correct answer: C. Searching for a target is the any pattern, which returns true as soon as a matching value is found.
Explanation

The any pattern returns true at the first match and returns false only after every value has been checked, exactly as hasNegative does. Returning false at the first nonmatching value would be a bug, because a later value could still match.

  • A is not correct: Nested loops compare each element with the elements after it, which answers whether some value repeats, not whether one particular value is present.
  • B is not correct: An accumulator produces a sum of all the values, and a total gives no information about whether one specific value occurs.
  • D is not correct: Comparing each element with its right neighbor answers questions about consecutive pairs rather than about a single target value.
Q5

A method reports whether every temperature is at least 0. Where should it return true?

AInside the loop after the first passing value
BBefore the loop begins
CInside the condition that finds a failing value
DAfter the loop finishes without finding a failure
Correct answer: D. The all pattern can report true only after the traversal finishes without finding a failing value.
Explanation

allPositive shows the shape: return false at the first failure, and reach the final true only when the loop has ended. Until every temperature has been examined, a value below 0 could still be waiting.

  • A is not correct: Returning true after one passing value ends the traversal early, while a later temperature could still fail the test.
  • B is not correct: Before the loop begins no temperature has been examined, so nothing yet justifies either answer.
  • C is not correct: The place where a failing value is found is where the method must return false; returning true there reports the opposite of what was discovered.
Q6

A minimum algorithm starts with the first value of {7, -2, 5} and updates only when it finds a smaller value. What is the final minimum?

A7
B-2
C5
D0
Correct answer: B. min starts at 7, is replaced by -2 because -2 is smaller, and is never replaced again.
Explanation

This is findMin applied to three values: initialize from the first element, then update only when a smaller value appears. Because every stored result came out of the array, the answer is always a value the array contains.

  • A is not correct: 7 is only the starting value taken from index 0, and it is replaced as soon as a smaller value is visited.
  • C is not correct: 5 is larger than the value already stored in min, so the update condition is false when it is visited.
  • D is not correct: 0 never appears in this array, and the algorithm only ever stores values it has read from the array.
Q7

Which operation moves a displaced value to the opposite end of an array?

AA shift
BA count
CA rotation
DA minimum search
Correct answer: C. A rotation wraps the displaced value around to the other end of the array instead of discarding it.
Explanation

rotateRightInPlace saves the last value, moves the remaining values one position right, and places the saved value at index 0. A left rotation is the mirror image, saving the first value and placing it at the last index.

  • A is not correct: A shift does not wrap the value that falls off; shiftLeft discards it and fills the newly opened final slot with 0.
  • B is not correct: Counting only increments a counter during the traversal and never assigns to any array position.
  • D is not correct: A minimum search reads the values and keeps the smallest one; it leaves every element where it was.
Q8

Which task usually needs a conditional inside the traversal?

AAdding every value to a running total
BCounting values greater than a threshold
CPrinting every value in the array
DCopying every value into the same index of another array
Correct answer: B. Counting values greater than a threshold needs an if inside the loop so that only matching values increase the counter.
Explanation

Some algorithms treat every element the same way, and some must decide element by element. countEven and findMin both add a condition to the traversal, because the loop visits the values while the condition decides when to update the result.

  • A is not correct: Adding every value to a running total performs the same update for each element, so nothing has to be selected during the traversal.
  • C is not correct: Printing every value treats all elements alike, which means the loop body runs identically for each one.
  • D is not correct: Copying every value into the same index of another array happens once per element with no test to pass or fail.
Q9

Consider the following method. What does countPairs return for {4, 4, 1, 1, 1}?

public static int countPairs(int[] codes) {
    int count = 0;
    for (int i = 0; i < codes.length - 1; i++) {
        if (codes[i] == codes[i + 1]) {
            count++;
        }
    }
    return count;
}
A2
B3
C4
DNothing is returned; an out-of-bounds error occurs.
Correct answer: B. Of the four adjacent pairs, three hold equal values, so count finishes at 3.
Explanation

This is the consecutive-pair pattern joined to the count pattern: i runs from 0 up to codes.length - 2, each element is compared with its right neighbor, and the counter is returned only after the traversal ends.

  • A is not correct: 2 undercounts, because the run of three equal values at the end contributes two equal adjacent pairs by itself, in addition to the pair at the front.
  • C is not correct: 4 is the number of adjacent pairs in a five-element array, but one of those pairs holds two different values and does not increment the counter.
  • D is not correct: The loop stops while i is less than codes.length - 1, so codes[i + 1] never reaches past the last element.
Q10

Consider the following method, which should report whether any value appears more than once. Why does this method return an incorrect result?

public static boolean hasRepeat(int[] ids) {
    for (int i = 0; i < ids.length; i++) {
        for (int j = 0; j < ids.length; j++) {
            if (ids[i] == ids[j]) {
                return true;
            }
        }
    }
    return false;
}
AThe inner loop starts at 0, so every element is compared with itself.
BThe outer loop should stop at ids.length - 1.
CThe method returns false before every pair has been compared.
DAn out-of-bounds error occurs on the last iteration.
Correct answer: A. When j begins at 0, the loops eventually reach the case where i and j are equal and the element is compared with itself.
Explanation

hasDuplicates starts j at i + 1 for exactly this reason: it avoids comparing an element with itself and avoids checking the same pair twice. With j starting at 0, the very first comparison is ids[0] against ids[0], which is always equal.

  • B is not correct: The outer bound is not what breaks this method; even with a shorter outer loop, an element would still be compared with itself.
  • C is not correct: The final false is never reached at all, because the method returns true on its first comparison.
  • D is not correct: Both loops stop before ids.length, so every index used to read the array stays inside it.
Q11

Consider the following method. What does data contain after the call?

public static void moveRight(int[] a) {
    for (int i = a.length - 1; i > 0; i--) {
        a[i] = a[i - 1];
    }
    a[0] = 0;
}

int[] data = {3, 8, 5};
moveRight(data);
A{8, 5, 0}
B{5, 3, 8}
C{0, 3, 8}
D{0, 8, 5}
Correct answer: C. Each element from the end backward is replaced by its left neighbor, and then index 0 is set to 0.
Explanation

This is the right-moving pattern, so the loop must run backward; walking forward would overwrite a value before the next step could read it. The changes are made by assigning through an index, so data itself holds the new values after the call.

  • A is not correct: This is what shifting left and filling the final slot produces, and this method moves values in the opposite direction.
  • B is not correct: This wraps the last value around to the front, which a rotation does; this method writes 0 at index 0 instead of saving a displaced value.
  • D is not correct: This leaves the original values from index 1 onward, but every one of those positions is overwritten by its left neighbor.
Q12

Consider the following method, which should rotate the values one position to the left. For {4, 7, 1}, why does the method fail to produce {7, 1, 4}?

public static void cycleLeft(int[] a) {
    int first = a[0];
    for (int i = a.length - 1; i > 0; i--) {
        a[i - 1] = a[i];
    }
    a[a.length - 1] = first;
}
AThe value saved in first should be a[a.length - 1].
BThe loop moves backward, so a value is overwritten before it is read.
CThe assignment to the last element must come before the loop.
DThe loop should continue through index 0.
Correct answer: B. Values are being moved left while the loop walks backward, so each value is copied only after its destination has already been changed.
Explanation

Direction is not a detail in these algorithms. Moving values left is safe going forward, because each source value is read before that source position is overwritten; running the same left moves backward destroys values on the way.

  • A is not correct: For a left rotation the saved value is the first one, which is then placed at the last index, so this part of the method already matches the pattern.
  • C is not correct: Placing the saved value at the last index before the loop would only let the loop overwrite it again, and it would not repair the order in which values are copied.
  • D is not correct: Continuing through index 0 would evaluate a[i - 1] with i at 0, which reaches index -1 and is outside the array.
Q13

Consider the following method. What does flip produce for {2, 9, 4, 7}?

public static void flip(int[] a) {
    for (int i = 0; i < a.length / 2; i++) {
        int j = a.length - 1 - i;
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
A{7, 4, 9, 2}
B{9, 2, 7, 4}
C{4, 7, 2, 9}
D{2, 9, 4, 7}
Correct answer: A. Each iteration swaps the element at i with the element the same distance in from the other end, which reverses the array.
Explanation

This is the reversal pattern built from the three-assignment swap with a temporary variable. The loop stops once the two indexes have met in the middle, so each pair is swapped exactly once, the way {"p", "a", "w", "s"} becomes {"s", "w", "a", "p"}.

  • B is not correct: This swaps neighboring elements rather than elements taken from opposite ends, so the first and last values never trade places.
  • C is not correct: This rearranges the values but does not put the last element first, which any reversal must do.
  • D is not correct: The array does change, because the swaps assign through indexes rather than to an enhanced-for loop variable.
Q14

Consider the following code segment, which is meant to exchange two elements. What does marks contain after this code segment runs?

int[] marks = {9, 3, 6, 1};
int left = 1;
int right = 3;

marks[left] = marks[right];
marks[right] = marks[left];
A{9, 1, 6, 3}
B{1, 3, 6, 9}
C{9, 3, 6, 1}
D{9, 1, 6, 1}
Correct answer: D. The first assignment overwrites marks[left] before its old value is saved, so the second assignment copies that same new value back.
Explanation

An exchange needs the three assignments the section shows, with a temporary variable holding the first value while the copy is made. Without temp the displaced value is gone and both positions end up holding the same thing.

  • A is not correct: This is the true exchange, but producing it requires the temporary variable that this segment leaves out.
  • B is not correct: This is the whole array reversed, and the segment only ever assigns to indexes 1 and 3.
  • C is not correct: The array does not survive unchanged, because marks[left] is assigned a different value on the first line.