Skip to main content

Unit 4 · Topic 4.4

4.4 Array Traversals

Traversing an array means using a loop to visit its elements. This topic covers indexed for and while loops, the enhanced for loop, and the rule that trips up many students: changing an enhanced for variable doesn't change the array.

Key terms

  • traversal
  • enhanced for loop
  • indexed loop
  • loop variable copy

Indexed traversals

The standard traversal uses a for loop over the indexes, from 0 to length - 1:

for (int i = 0; i < prices.length; i++) { System.out.println(prices[i]); }

With an index you can read elements, change them (prices[i] = 0;), look at neighbors like prices[i + 1], go backward, or skip some. A while loop with an index variable works the same way.

The enhanced for loop

An enhanced for loop visits every element in order without using indexes:

for (double p : prices) { System.out.println(p); }

Read the header as "for each double p in prices". On each pass, the enhanced for variable p is assigned a copy of the next element. It's shorter and you can't go out of bounds, but there's no index, so you can't easily tell where you are, look at neighbors, or go backward.

Every enhanced for loop can be rewritten as an indexed for or while loop. The reverse isn't always possible.

Traversing part of an array

A traversal doesn't have to visit every element from front to back. Change the loop header to visit an ordered sequence of elements: start at index 1 to skip the first element, use i += 2 to visit every other one, or start at arr.length - 1 and count down with i-- to go backward. Each of these needs an indexed loop, since an enhanced for always visits every element in order.

Whatever pattern you use, check the first index and the last index the loop will touch. Both must be between 0 and length - 1.

The copy rule

Because the enhanced for variable is a copy, assigning a new value to it does not change the array. n = n + 100; inside an enhanced for changes only the copy, which is thrown away at the end of the pass. To change elements, use an indexed loop.

Arrays of objects work a bit differently. The copy is a copy of a reference, so it refers to the same object as the array element. Calling a mutator on the loop variable, like c.click(), changes that object, and the change shows through the array. What you still can't do is replace the object in the array by assigning to the loop variable.

Worked examples

Try each one yourself first, then open the solution.

  1. Example 1

    Indexed versus enhanced

    What does this code print?int[] nums = {3, 7, 2}; for (int i = 0; i < nums.length; i++) { nums[i] = nums[i] * 2; } for (int n : nums) { n = n + 100; } for (int n : nums) { System.out.print(n + " "); } System.out.println();

    Show the solution
    1. Step 1: The first loop uses indexes, so nums[i] = nums[i] * 2 really changes the array: it becomes 6, 14, 4.
    2. Step 2: The second loop assigns to n, which is only a copy of each element. The array doesn't change.
    3. Step 3: The third loop prints the elements as they really are.

    Answer: It prints 6 14 4 (with a trailing space).

  2. Example 2

    Objects in an enhanced for loop

    Counter has a click method that adds 1 to its count and a getCount method. What does this code print?Counter[] counters = {new Counter(), new Counter()}; for (Counter c : counters) { c.click(); c.click(); } System.out.println(counters[0].getCount() + " " + counters[1].getCount());

    Show the solution
    1. Step 1: Each pass, c gets a copy of the reference stored in the array, so it refers to the actual Counter object.
    2. Step 2: c.click() twice changes that object's count to 2.
    3. Step 3: Both counters get clicked twice, and the array still refers to them.

    Answer: It prints 2 2.

  3. Example 3

    A while loop that skips

    What does this code print?int[] temps = {61, 58, 70, 66}; int i = temps.length - 1; while (i >= 0) { System.out.print(temps[i] + " "); i -= 2; } System.out.println();

    Show the solution
    1. Step 1: i starts at the last index, 3, so it prints temps[3], 66.
    2. Step 2: i becomes 1, which is still at least 0, so it prints temps[1], 58.
    3. Step 3: i becomes -1, the condition is false, and the loop ends.

    Answer: It prints 66 58 .

Common mistakes

  • Trying to change array elements by assigning to the enhanced for variable. Use an indexed loop.
  • Using <= in i <= arr.length, which goes one past the end.
  • Using an enhanced for loop when you need the index, such as to compare neighbors or report a position.

On the exam

  • A common multiple-choice question asks whether a loop changes the array. Check whether it assigns to arr[i] or only to a loop variable.

Connected topics

Videos

  • AP Computer Science A - Topic 4.4 - Part 1: Array Traversals

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • AP CSA – Unit 6: Array – Lesson 4: The Enhanced For Loop

    Goldie's Math EmporiumWatch on YouTube (opens in a new tab)

  • Traversing an Array (Java Tutorial)

    Bill BarnumWatch on YouTube (opens in a new tab)

  • AP Computer Science A - Topic 4.4 - Part 2: Array Traversals

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • java for-each loop 🔃

    Bro CodeWatch on YouTube (opens in a new tab)

Check yourself

4 questions on 4.4 Array Traversals. Pick an answer to see if you got it, and why.

Question 1 of 4

Consider the following code segment.int[] nums = {1, 2, 3}; for (int n : nums) { n *= 2; }What are the contents of nums after the code segment executes?

Question 2 of 4

Consider the following class.public class Tally { private int count; public void add(int n) { count += n; } public int getCount() { return count; } }What is printed as a result of executing the following code segment?Tally[] list = {new Tally(), new Tally(), new Tally()}; for (Tally t : list) { t.add(2); } list[1].add(5); int total = 0; for (Tally t : list) { total += t.getCount(); } System.out.println(total);

Question 3 of 4

Assume words is an array of String objects. Consider the following code segment.for (String w : words) { System.out.print(w.length() + " "); }Which of the following code segments produces the same output for every such array?

Question 4 of 4

Consider the following code segment.int[] vals = {4, 7, 1, 8, 5, 2}; int i = vals.length - 1; String s = ""; while (i >= 0) { s += vals[i]; i -= 2; } System.out.println(s);What is printed as a result of executing the code segment?

0 of 4 answered