Unit 4 Cycle 1 Day 5: Enhanced For Loop

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

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.

String[] words = {"AP", "CS", "A"}; String result = ""; for (String w : words) { result += w; } System.out.println(result);

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.

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.