Unit 4 Cycle 2 Day 2: I/II/III: Array Traversal Patterns
Share
I/II/III: Array Traversal Patterns
Section 4.2 — Traversing Arrays
Key Concept
I/II/III array traversal pattern questions present different loop structures and ask which correctly implement a specific algorithm. Common variations: standard for loop vs enhanced for loop, forward vs backward traversal, and loops that skip elements (step by 2). Each pattern has different capabilities: enhanced for loops cannot modify elements or access indices, backward loops enable safe removal, and step-by-2 loops process alternating elements. Evaluate each statement by tracing with a sample array.
Consider the following code segments that process int[] arr = {1, 2, 3, 4, 5}.
Which segments produce the same sum?
Answer: (B) II and III only
I: Visits indices 0, 2, 4: sum = 1+3+5 = 9.
II: Visits all backwards: sum = 5+4+3+2+1 = 15.
III: Visits all forward: sum = 1+2+3+4+5 = 15.
II and III both sum to 15.
Why Not the Others?
(A) I sums only even-indexed elements (9). II sums all (15).
(C) I sums 9, III sums 15. They differ.
(D) I only sums every other element.
Common Mistake
i += 2 skips every other element. Both forward and backward FULL traversals produce the same sum because addition is commutative.
AP Exam Tip
Step size matters: i++ visits all, i+=2 visits every other. Direction does not affect sum.