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.
- Develop code used to traverse the elements in a 1D array and determine the result of these traversals.
Indexed for loop
Codeint[] 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();Output32 30 16 8Enhanced 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.
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]);Output12 2Objects 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.
CodeCounter[] cs = {new Counter(), new Counter()};
for (Counter c : cs) {
c.increment();
}
System.out.println(cs[0].getCount() + " " + cs[1].getCount());Output1 1- Traversing accesses all elements, or an ordered subset, with a loop.
- Indexed
for/whileloops 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.
- Use an indexed loop when you need to change elements, need the index, or need to look at neighbors.
Which loop do you need to replace every negative element with 0?
Show answer
An indexed loop, so you can assign nums[i] = 0.