Unit 4 Cycle 1 Day 27: Mixed Array and Loop Algorithms

Unit 4 Foundation (Cycle 1) Day 27 of 28 Foundation

Mixed Array and Loop Algorithms

Section Mixed — Review: Algorithms

Key Concept

Mixed array and loop algorithm problems combine array traversal with complex conditional logic, accumulators, and sometimes secondary data structures. A common AP exam pattern processes an array and builds an ArrayList of results, or vice versa. These problems test multiple skills simultaneously: correct indexing, proper loop bounds, condition evaluation, and accumulator management. The key is to break the problem into steps and trace each step separately.

Consider the following code segment.

int[] arr = {4, 7, 2, 9, 1, 5}; int first = arr[0]; int second = arr[0]; for (int val : arr) { if (val > first) { second = first; first = val; } else if (val > second && val != first) { second = val; } } System.out.println(first + " " + second);

What is printed?

Answer: (A) 9 7

Trace: first=4,second=4. val=4: skip. val=7: 7>4, second=4,first=7. val=2: skip. val=9: 9>7, second=7,first=9. val=1: skip. val=5: 5>7? no. 5>7? no. Final: 9 7.

Why Not the Others?

(B) 7 is the second largest, not 5.

(C) These would be results from an incomplete trace.

(D) 7 is larger than 4 and is the correct second value.

Common Mistake

Finding top two: when updating first, save old first to second BEFORE overwriting. Order of assignment matters.

AP Exam Tip

Finding top-2 values: when updating first, save the old first to second first. The else-if handles values between first and second.

Review this topic: Section Mixed — Review: Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.