ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.4

Array Traversals

Skill 2.BSkill 3.BSkill 3.D

Big idea: Traversing means visiting elements with a loop. Use an indexed loop when you need positions or want to change elements; use an enhanced for loop when you just need each value.

Learning objectives
  • Develop code used to traverse the elements in a 1D array and determine the result of these traversals.

Indexed for loop

Code
int[] nums = {4, 8, 15, 16};
for (int i = 0; i < nums.length; i++) {
  nums[i] = nums[i] * 2;
}
for (int i = nums.length - 1; i >= 0; i--) {
  System.out.print(nums[i] + " ");
}
System.out.println();
Output
32 30 16 8

Enhanced for loop

for (int n : nums) gives n a copy of each element in order, with no index. Assigning to n doesn't change the array.

Code
int[] nums = {2, 4, 6};
int sum = 0;
for (int n : nums) {
  sum += n;
  n = 0;            // changes only the copy
}
System.out.println(sum + " " + nums[0]);
Output
12 2

Objects in an enhanced for loop

When the array holds objects, the loop variable is a copy of the reference, so calling a mutator on it does change the object.

Code
Counter[] cs = {new Counter(), new Counter()};
for (Counter c : cs) {
  c.increment();
}
System.out.println(cs[0].getCount() + " " + cs[1].getCount());
Output
1 1
Key points
  • Traversing accesses all elements, or an ordered subset, with a loop.
  • Indexed for/while loops use the index.
  • The enhanced for variable gets a copy of each element; assigning to it doesn't change the array.
  • With objects, calling methods on the enhanced for variable can change the objects.
  • Any enhanced for loop can be rewritten as an indexed loop.
Watch out
  • Use an indexed loop when you need to change elements, need the index, or need to look at neighbors.
Quick check
Which loop do you need to replace every negative element with 0?
Show answer
An indexed loop, so you can assign nums[i] = 0.