Welcome to Array Traversals!

In the previous chapter, "Array Creation and Access," we learned how to build an array and grab a single value from it. But what if you have an array of 1,000 high scores and you need to find the average? You wouldn't want to write 1,000 lines of code! That is where traversal comes in. Traversal is just a fancy word for "visiting every element in a data set one by one." It is the bread and butter of working with data in Computer Science.

1. The Standard for Loop Traversal

The most common way to move through an array is using a standard for loop. This gives you total control because you use an index (usually \( i \)) to point to each "slot" in the array.

The Anatomy of a Traversal

To visit every element from the start to the end, we set our loop to start at index \( 0 \) and continue as long as the index is less than the length of the array.

Example Code Structure:
for (int i = 0; i < myArray.length; i++) {
    // Do something with myArray[i]
}

Important Rules to Remember:

  • Zero-Based Indexing: Always start at \( i = 0 \). The first item is NOT at index 1!
  • The Boundary: The loop condition should be \( i < myArray.length \). Because arrays are zero-indexed, an array with a length of \( 5 \) has indices \( 0, 1, 2, 3, 4 \). There is no index \( 5 \).
  • The .length Property: Note that for arrays, \( length \) is a property, not a method. This means you do not use parentheses like you do with Strings (e.g., use \( arr.length \), not \( arr.length() \)).

Common Mistake: The Off-By-One Error
If you accidentally write \( i <= myArray.length \), your code will try to access an index that doesn't exist. This triggers the famous ArrayIndexOutOfBoundsException. Think of it like trying to go to the 6th floor of a 5-story building—there's nowhere to land!

Key Takeaway: The standard for loop is best when you need to know the index position or if you need to modify the values stored in the array.

2. The Enhanced for Loop (for-each)

Java provides a "shortcut" called the Enhanced for Loop (often called the for-each loop). It is designed to be simpler and harder to break.

Example Code Structure:
for (int element : myArray) {
    System.out.println(element);
}

Think of this as saying: "For every int (which we will call 'element') in myArray, do the following..."

When to use the Enhanced for Loop:

  • Read-Only Tasks: Use this when you just want to look at or "consume" the data (like printing or summing numbers).
  • No Indices Needed: Use this when you don't care where an item is, only what it is.

The "Trap" of Enhanced for Loops:

Don't worry if this seems tricky at first, but there is one major limitation: You cannot use an enhanced for loop to change the primitive values inside an array.

If you say \( element = 10; \) inside the loop, you are only changing a copy of the data, not the actual value inside \( myArray \). To change the actual values, you must use the standard for loop with indices.

Key Takeaway: The enhanced for loop is cleaner and prevents index errors, but it cannot modify primitive elements or track the current index.

3. Directional Traversals

You don't always have to go from left to right! Depending on the problem, you might need to move differently.

Reverse Traversal

To go backward from the end to the beginning, you start the index at the last valid position and count down.

Logic:
Start: \( i = myArray.length - 1 \)
End: \( i >= 0 \)
Step: \( i-- \)

Partial Traversal

Sometimes you only need to look at part of the data. For example, if you want to skip the first element, you start at \( i = 1 \). If you only want to look at the first half, your condition would be \( i < myArray.length / 2 \).

4. Informal Run-Time Analysis

In AP Computer Science A, you need to understand how "expensive" an algorithm is by counting how many times a statement executes. This is called Informal Run-Time Analysis.

If an array has \( n \) elements, a standard traversal loop will run the code inside the braces exactly \( n \) times. We often say the work is proportional to the number of elements in the array. If you double the size of the array, you double the amount of work the loop has to do!

Quick Review Checklist

  • Does your standard loop start at \( 0 \) and end at \( length - 1 \)?
  • Did you remember that \( myArray.length \) does not have parentheses?
  • Are you using an enhanced for loop only when you don't need to change the data or know the index?
  • Are you prepared for the ArrayIndexOutOfBoundsException if your loop goes too far?

Note: For more details on using these loops to find the maximum value or calculate an average, check out the next chapter: "Implementing Array Algorithms."