5.3 Traversing with for
Looping Through an Array in Java
Unit 5: Arrays · Lesson 5.3 · about 25 minutes · no coding experience needed
One loop shape gets used for the rest of this course and the whole of Unit 6. Learn it as a unit rather than as four separate decisions.
What you will be able to do
- Write the standard array traversal
- Explain why the condition uses length rather than a number
- Fill an array inside a loop
Words you will need
- Traverse
- In plain words Visit every element in turn.
- More precisely Iterate over the full index range of an array.
Build it step by step
Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.
-
Step 1
On your screen The standard traversal loop with the index used inside the body.
int[] lanes = {3, 7, 2, 9}; for (int i = 0; i < lanes.length; i++) { addObject(new Coin(), lanes[i], 0); }This is the shape. Commit it to memory as one thing:
`for (int i = 0; i < a.length; i++)`
Start at 0 because that is the first index. Stop BEFORE length because the last index is length minus one. Step by one to visit each in turn.
Inside, `lanes[i]` is the element at this pass.
-
Step 2
On your screen A traversal that hardcodes the size and misses an element after the array is changed.
int[] lanes = {3, 7, 2, 9, 5}; // now five for (int i = 0; i < 4; i++) // still says four { // the 5 is never visited }Why `lanes.length` rather than 4? Because arrays change during development.
Add a fifth value and this loop silently misses it. No error, just an element that is never processed. Write `<= 4` instead and you get the opposite failure, an exception.
`i < a.length` is correct at every size, forever, and needs no maintenance.
-
Step 3
On your screen A loop filling an array with computed values.
int[] squares = new int[5]; for (int i = 0; i < squares.length; i++) { squares[i] = i * i; } // {0, 1, 4, 9, 16}Filling rather than reading. Same loop, with the assignment the other way round.
And here is the counter-in-a-calculation idea from 4.7 again: `i * i` turns the index into a value. Unit 6 uses exactly this to turn an index into a screen position.
Mistakes almost everyone makes here
These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.
Common wrong idea `i <= a.length` visits everything.
What is actually true It goes one past the end and throws. Use `<`.
Why it matters The most common array loop bug, and the exception names an index equal to the length.
Common wrong idea Hardcoding the size is fine if you know it.
What is actually true It goes stale the moment the array changes, silently.
Why it matters A loop that misses the last element produces no error at all.
Common wrong idea The loop variable must be called i.
What is actually true Convention only. In Unit 6 you will use row and col, which read far better.
Why it matters Meaningful names matter more in nested loops, which is where this is going.
Common wrong idea You cannot change the array while traversing it.
What is actually true Changing VALUES is fine. Arrays cannot change SIZE, so the list problem from 4.5 does not arise.
Why it matters Students over-apply the ConcurrentModificationException rule to arrays, where it cannot happen.
Check your understanding
Answer these before moving on. They are graded instantly and you can retry.
-
1. What is the standard array traversal condition?
-
2. An array has 5 elements and the loop uses `i <= a.length`. What happens?
-
3. Why write `a.length` rather than the number?
-
4. After `for (int i = 0; i < 4; i++) { a[i] = i * 3; }` what is a?
Fill in the code
Fill an array called heights so that each slot holds twice its own index, and do it in a way that stays correct if the array size changes.
for (int i = 0; i heights.; i++)
{
heights[i] = * 2;
}
Stuck? Open a hint for each blank
- Blank 1: Stop one before the end. One character.
- Blank 2: How many slots. Remember: no parentheses on an array.
- Blank 3: The loop counter, which is also the slot number.
Lesson quiz
This one counts toward your progress. Take it when the section above makes sense.
-
1. Which loop safely visits every element of any array a?
-
2. A loop uses a hardcoded 4 and someone adds a fifth element. What happens?
-
3. Inside the traversal, `a[i]` is:
-
4. Can you change the values in an array while traversing it?
The short version
- `for (int i = 0; i < a.length; i++)` is the shape. Learn it as one thing.
- `<` not `<=`, because the last index is length minus one.
- Use `a.length`, never a typed number that can go stale.
- `a[i] = something` fills; `something = a[i]` reads.
If you get stuck
These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]