Iterating Through Arrays
What you'll learn: How to use loops to visit every element in an array from beginning to end.
Now that you know what arrays are and how to access individual elements by index, you need a systematic way to process all elements without writing repetitive code. This is where iteration comes in—using loops to step through each array element sequentially.
The Core Idea
Think of an array like a row of mailboxes. Instead of manually opening each one ("check box 0, check box 1, check box 2..."), you walk down the row with a simple rule: start at the first box, check it, move to the next, and repeat until you reach the end.
In code, you combine what you've learned about for loops and array indexing. A typical pattern looks like this:
for i from 0 to (array length - 1):
access array[i]
The loop control variable (i) serves as your index, automatically stepping through 0, 1, 2, ... up to the last valid position.
Why This Matters
Without loops, processing a 100-element array would require 100 separate lines of code! Iteration lets you write the logic once and apply it to every element, whether your array has 5 items or 5 million.
You can use iteration to:
- Print all values
- Find the maximum or minimum
- Calculate a sum or average
- Search for a specific value
- Transform each element
The key is remembering that arrays are zero-indexed (start at 0) and that the last valid index is always (length - 1).
Key Takeaway: Iterating through arrays means using a loop with an index variable that visits each element from index 0 to length-1, letting you process entire collections with compact, reusable code.