Unit 2 Day 10: For-Each Loop Limitation

Unit 2: Selection & Iteration
Day 10 Practice - Section 2.10
Focus: For-Each Loop Limitations

Practice Question

Consider the following code segment intended to double all values in an array:
int[] nums = {2, 4, 6, 8};

for (int val : nums)
{
 val = val * 2;
}

System.out.println(nums[0] + " " + nums[2]);
What is printed as a result of executing this code segment?
Difficulty: Medium - Time: 2-3 minutes - AP Skill: 2.B - Determine output
What This Tests: This question tests a critical limitation of for-each loops: you cannot use them to modify array elements. The loop variable is a copy of each element, not a reference to it.

Why the Array Doesn't Change

In a for-each loop, the loop variable val receives a copy of each array element. When you modify val, you're only changing the copy - the original array remains untouched.

Iteration val (copy) val after val = val * 2 nums array
1 2 4 {2, 4, 6, 8} - unchanged!
2 4 8 {2, 4, 6, 8} - unchanged!
3 6 12 {2, 4, 6, 8} - unchanged!
4 8 16 {2, 4, 6, 8} - unchanged!

Output: 2 6 (original values at indices 0 and 2)

How to Actually Modify Array Elements

To modify array elements, you must use an indexed for loop:

for (int i = 0; i < nums.length; i++)
{
 nums[i] = nums[i] * 2; // This DOES modify the array
}
// nums is now {4, 8, 12, 16}

Common Mistakes

Mistake: Answer A (4 12)

This assumes the for-each loop successfully modified the array. It didn't - val is just a copy of each element.

Mistake: Answer E (compile-time error)

The code compiles and runs fine - it just doesn't do what you might expect. Assigning to the loop variable is legal, but pointless for primitives.

AP Exam Strategy

For-Each Loop Rules

Use for-each when: Reading/accessing all elements without modification

Use indexed for loop when:

  • You need to modify array elements
  • You need the index value
  • You need to traverse in reverse or skip elements

Want More Practice?

Master AP CSA with guided practice and expert help

Schedule 1-on-1 Tutoring Practice FRQs
Back to blog

Leave a comment

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