Topic 4.3 — Enhanced for Loop for Arrays

Goal: use the enhanced for loop (for-each loop) to traverse arrays, understand when it works best, and know its limitations compared to an indexed for loop.

The big idea

The enhanced for loop (also called for-each) is a clean way to visit every element in an array when you don’t need the index.

It’s perfect for reading values (sum, count, max), but it’s not ideal for changing elements in-place.

Syntax

for (type var : array) {
  // use var (the element value)
}

var becomes each element value, one at a time.

Example: print every value

int[] nums = {4, 8, 12};

for (int x : nums) {
  System.out.println(x);
}

This visits 4, then 8, then 12.

Great use: sum / count

int sum = 0;
for (int x : nums) {
  sum += x;
}

int countPos = 0;
for (int x : nums) {
  if (x > 0) countPos++;
}

Great use: max/min

int max = nums[0];
for (int x : nums) {
  if (x > max) max = x;
}

You’re comparing values; you don’t need indexes.

Limitation: you can’t update the array this way

Changing the loop variable does not change the array element.

for (int x : nums) {
  x = x + 1; // ❌ does NOT modify nums
}

If you need to modify the array, use an indexed for loop.

When you DO need the index

  • Updating values: arr[i] = ...
  • Swapping elements
  • Comparing neighbors: arr[i] and arr[i+1]
  • Tracking the location (index) of a max/min
for (int i = 0; i < nums.length; i++) {
  nums[i]++; // ✅ modifies array
}

Arrays of objects (works the same)

The enhanced for loop is also great for arrays of references (like String[]).

String[] words = {"AP", "CSA", "rocks"};

for (String w : words) {
  System.out.println(w.length());
}

Index translation (if you’re curious)

Conceptually, the enhanced for loop is like a normal loop that walks through the indexes.

for (int i = 0; i < nums.length; i++) {
  int x = nums[i];
  // use x
}

Don’t confuse “element” vs “index”

  • Enhanced for gives you the value.
  • Indexed for gives you the index (i), so you can do arr[i].

Quick self-check

  1. Write an enhanced for loop that computes the sum of an int[].
  2. Why can’t you reliably modify an array using for (int x : arr)?
  3. When should you use an indexed for loop instead?
  4. Does enhanced for work on String[]? What does the loop variable store?
  5. How would you find the index of the maximum value?

← Back to Unit 4 topics