These notes recap Topic 4.4. Full explanations and worked examples are in the study guide.
Recap
- Traversing an array uses repetition to access all, or an ordered sequence of, elements.
- An indexed
forloop or awhileloop accesses elements by index. The standard forward loop isfor (int i = 0; i < a.length; i++). - An enhanced
forloop (for (int v : a)) assigns the loop variable a copy of each element, with no index. - Assigning a new value to the enhanced for variable does not change the array.
- For an array of objects, calling a method on the loop variable can change the object’s state; it does not change the references stored in the array.
- An enhanced for loop can always be rewritten as an indexed for loop or a while loop.
Key relationships
| Goal | Loop |
|---|---|
| Every element, first to last | for (int i = 0; i < a.length; i++) |
| Every other element | for (int i = 0; i < a.length; i += 2) |
| Last to first | for (int i = a.length - 1; i >= 0; i--) |
| Read each element, no index needed | for (int v : a) |
| Change stored primitive values | indexed loop with a[i] = ... |
| Stop early on a condition | while loop with k < a.length && ... |
Results to remember
With a = {3, 8, 1, 6}: the full sum is 18; the sum of every other element is 4; printing backward gives 6 1 8 3; the number of elements above 5 is 2; doubling inside an enhanced for leaves 3 8 1 6; doubling with a[i] = a[i] * 2 gives 6 16 2 12.
Off-by-one checklist
- Does the first iteration use the first index you want (usually 0)?
- Does the last iteration use the last index you want (usually
a.length - 1)? - Is the test
<withlength, not<=? - Does a
whileloop change its index inside the body? - For a
whileloop with two conditions, is the index test written first?
Mistakes to avoid
- Using
<=witha.length. - Starting at 1 when the first element must be included.
- Believing the enhanced for variable is the array element itself.
- Forgetting
i++in awhileloop. - Using an enhanced for loop when the position is needed.
Quick self-check
- How many times does
for (int i = 0; i < a.length - 1; i++)run for an array of length 4? Answer: 3. - After
for (int x : a) { x = 0; }what is ina? Answer: unchanged. - An array of
Counterobjects is traversed withfor (Counter c : cs) c.bump();. Do the counters change? Answer: Yes, each object’s state changes. - Which loop style gives the index of each element? Answer: the indexed for loop (or a while loop with an index).