Array Traversals
| English | Chinese | Pinyin |
|---|---|---|
| traversal | 遍历 | biàn lì |
| enhanced for loop | 增强for循环 | zēng qiáng for xún huán |
Visiting every element
- A traversal 遍历 visits every element of an array, usually in order.
- The standard indexed loop:
for (int i = 0; i < a.length; i++) { ... a[i] ... } isteps from0tolength - 1, soa[i]reaches each element once.- Traversal is the foundation of every array algorithm.
The for-each loop
- The enhanced for loop (for-each) 增强for循环 visits each value without an index:
for (int x : a) { ... x ... }—xtakes each element's value in turn.- Cleaner when you only need the values, not their positions.
- But it can't change the array or use the index.
Indexed vs. for-each
- Use the indexed loop when you need the position
i, or to modify elements. - Use the for-each loop when you just need to read each value.
a[i] = 0;needs the indexed loop; summing values can use for-each.- Both visit every element — pick the one that fits the task.
Bounds again
- The indexed loop's condition
i < a.lengthkeepsivalid. i <= a.lengthoverruns by one → ArrayIndexOutOfBoundsException.- The for-each loop can't go out of bounds — it handles the range for you.
- When you write the index yourself, you own the bounds.
The for-each loop reads values but can't assign back into the array. for (int x : a) { x = 0; } changes only the local copy x, not a — to zero out the array you need the indexed loop a[i] = 0;. Use for-each to read, the indexed loop to modify or when you need the position i.
Two ways to sum an array:
- Indexed:
for (int i = 0; i < a.length; i++) { sum += a[i]; } - For-each:
for (int x : a) { sum += x; } - Both give the same total; for-each is cleaner when the index isn't needed.
A traversal visits every element. The indexed loop (for (int i = 0; i < a.length; i++)) gives the position i and can modify a[i]; the for-each loop (for (int x : a)) cleanly reads each value but can't change the array or use an index. Choose by whether you need the index or to modify.
Traversing an array to sum it
i visits each index; sum accumulates a[i] (here a = {10,20,30}).
The correct condition to traverse an array a with an index is...
Valid indices are 0..length-1, so i < a.length.
Which loop should you use if you need to MODIFY the array elements?
for-each can't assign back; use a[i] = ... with the indexed loop.
In for (int x : a) { x = 0; }, the array a is set to all zeros.
x is a local copy; the array is unchanged.
The for-each loop for (int x : a) is best when you only need to...
for-each cleanly reads values without an index.
Visiting every element of an array is called a ___ (one word).
A traversal visits each element.