Unit 4 Cycle 2 Day 2: I/II/III: Array Traversal Patterns

Unit 4 Advanced (Cycle 2) Day 2 of 28 Advanced

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}.

// Segment I int s1 = 0; for (int i = 0; i < arr.length; i += 2) s1 += arr[i]; // Segment II int s2 = 0; for (int i = arr.length - 1; i >= 0; i--) s2 += arr[i]; // Segment III int s3 = 0; for (int val : arr) s3 += val;

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.

Review this topic: Section 4.2 — Traversing Arrays • Unit 4 Study Guide
Back to blog

Leave a comment

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