Unit 4 Cycle 1 Day 27: Mixed Array and Loop Algorithms
Share
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.
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.