Iterating Arrays with Traditional for Loops
What you'll learn: How to visit every element in an array using a traditional for loop with an index counter.
The Core Pattern
Now that you know how to access individual array elements and understand traditional for loops, you can combine them to process every element in an array. The classic pattern uses the array's length as the loop boundary and an index variable to access each element sequentially.
Here's the fundamental structure:
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Why this works:
i = 0starts at the first valid indexi < numbers.lengthensures you never exceed the last valid index (since valid indices are 0 throughlength - 1)i++moves to the next element each iterationnumbers[i]accesses the current element
Why Use Traditional Loops Over Enhanced for Loops?
Traditional indexed loops give you positional information that enhanced for loops don't provide. Use them when you need to:
- Know the current index position
- Modify array elements in place
- Process elements in a non-sequential order
- Compare adjacent elements
// Doubling each element requires index access
int[] values = {5, 10, 15};
for (int i = 0; i < values.length; i++) {
values[i] = values[i] * 2; // Modifying the array
}
Key Takeaway: The traditional for loop with i < array.length is the standard pattern for array traversal when you need index control or must modify elements; it safely visits each element from index 0 to length - 1.