Unit 4 Cycle 1 Day 5: Enhanced For Loop
Share
Enhanced For Loop
Section 4.2 — Traversing Arrays
Key Concept
The enhanced for loop (for-each) provides a simpler syntax for traversing arrays: for (int val : arr). The loop variable val receives a copy of each element in order. This means you cannot modify the original array through the loop variable — val = 10 changes only the local copy. The enhanced for loop is ideal when you need to read every element without knowing its index. On the AP exam, it is preferred for simple traversals but cannot be used for algorithms that require the index.
Consider the following code segment.
What is printed?
Answer: (B) APCSA
The enhanced for loop visits each element: "AP", "CS", "A". Concatenation without spaces: "" + "AP" + "CS" + "A" = "APCSA".
Why Not the Others?
(A) No spaces are added between elements. String concatenation joins them directly.
(C) "A" is the last element, but all three are concatenated.
(D) "AP" is only the first element.
Common Mistake
The enhanced for loop gives you each element directly (not the index). String concatenation with += builds the result without any separators.
AP Exam Tip
Enhanced for: for (Type var : array). You cannot modify the array or access indices. Use a standard for loop if you need the index.