Fiveable
Fiveable
AP Computer Science A

💻ap computer science a review

6.2 Traversing Arrays

Verified for the 2025 AP Computer Science A examLast Updated on June 18, 2024

When working with arrays, we often need to process all the elements, one by one. This process of visiting each element in an array is called "traversing" the array. In this guide, we'll learn different ways to safely and efficiently go through all the elements in an array.

What Does It Mean to Traverse an Array?

Traversing an array means visiting each element in the array, usually to perform some operation like:

  • Reading or displaying each value
  • Updating each value
  • Finding a specific value
  • Calculating statistics (like a sum or average)

Ways to Traverse an Array

There are two main approaches to traverse arrays in Java:

1. Using an Indexed For Loop

This is the most common way to traverse an array when you need to know the position (index) of each element:

int[] numbers = {10, 20, 30, 40, 50};

// Traverse using a standard for loop with index
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Element at position " + i + ": " + numbers[i]);
}

Key points:

  • The loop variable i represents the current position (index)
  • We start at position 0 (the first element)
  • We continue as long as i is less than the array's length
  • We can access the current element using numbers[i]

2. Using an Enhanced For Loop (For-Each Loop)

When you only need the values and don't care about the positions:

int[] numbers = {10, 20, 30, 40, 50};

// Traverse using enhanced for loop (for-each)
for (int value : numbers) {
    System.out.println("Value: " + value);
}

Key points:

  • Simpler syntax - no need to manage indices

  • The loop variable (value) directly holds each element

  • You don't know which position you're at (no index)

  • You can't modify the array structure during traversal

3. Using a While Loop

Sometimes you might want to use a while loop for traversal:

int[] numbers = {10, 20, 30, 40, 50};
int i = 0;

// Traverse using a while loop
while (i < numbers.length) {
    System.out.println(numbers[i]);
    i++;
}

When to Use Each Approach

ApproachUse When You Need To
Indexed For LoopAccess or change elements based on their position
Keep track of position numbers
Only process certain elements (like only even indices)
Enhanced For LoopSimply process every element without needing position information
Write cleaner, more readable code
Avoid "off-by-one" errors
While LoopExit early based on a condition
Use more complex stepping logic

Avoiding Common Errors

The ArrayIndexOutOfBoundsException

When you try to access a position that doesn't exist in the array, Java throws an ArrayIndexOutOfBoundsException. This commonly happens when:

  1. Your loop condition goes too far:

    // Error: i will eventually become 5, which is invalid
    for (int i = 0; i <= numbers.length; i++) { ... }
    
  2. You start at the wrong index:

    // Error: starting at position 1 skips the first element
    for (int i = 1; i <= numbers.length; i++) { ... }
    
  3. You use the wrong comparison operator:

    // Error: using <= instead of <
    for (int i = 0; i <= numbers.length; i++) { ... }
    

The "Off-By-One" Error

Since array indices start at 0 and end at length-1, it's easy to make "off-by-one" errors:

int[] scores = {85, 92, 78, 95, 88};

// INCORRECT: This will cause ArrayIndexOutOfBoundsException
for (int i = 0; i <= scores.length; i++) {
    System.out.println(scores[i]);  // Error when i = 5
}

// CORRECT version
for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

Remember:

  • Use < (less than), not <= (less than or equal to)
  • The last valid index is always length - 1

Common Array Traversal Patterns

Traversing Only Part of an Array

int[] values = {10, 20, 30, 40, 50, 60, 70};

// Traverse just the first 3 elements
for (int i = 0; i < 3; i++) {
    System.out.println(values[i]);
}

// Traverse just the last 3 elements
for (int i = values.length - 3; i < values.length; i++) {
    System.out.println(values[i]);
}

Finding a Value in an Array

int[] numbers = {4, 7, 2, 9, 6, 8};
int searchFor = 9;
boolean found = false;

for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] == searchFor) {
        System.out.println("Found at position: " + i);
        found = true;
        break;  // Exit the loop once found
    }
}

if (!found) {
    System.out.println("Value not found in the array");
}

Computing a Sum or Average

int[] scores = {85, 92, 78, 95, 88};
int sum = 0;

for (int score : scores) {
    sum += score;  // Add each score to the sum
}

double average = (double) sum / scores.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);

Finding the Minimum or Maximum Value

int[] values = {12, 5, 22, 9, 18, 3, 14};
int min = values[0];  // Start with the first element
int max = values[0];

for (int i = 1; i < values.length; i++) {
    if (values[i] < min) {
        min = values[i];
    }
    if (values[i] > max) {
        max = values[i];
    }
}

System.out.println("Minimum value: " + min);
System.out.println("Maximum value: " + max);

Summary

Traversing arrays is a fundamental skill in programming. We've learned how to visit each element in an array using indexed for loops, enhanced for loops, and while loops. We've also covered common traversal patterns and how to avoid the dreaded ArrayIndexOutOfBoundsException by understanding how array indices work. Remember that array indices start at 0 and end at length-1, so always be careful with your loop conditions to prevent "off-by-one" errors.

Key Terms to Review (8)

ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException is an exception that occurs when trying to access an invalid index position in an array. It is thrown to indicate that the index used to access an array is either negative or greater than or equal to the size of the array.
Array.length: The property "length" in an array refers to the number of elements it contains.
Constructor: A constructor is a special method within a class that is used to initialize objects of that class. It is called automatically when an object is created and helps set initial values for its attributes.
Limited Traversal: Limited traversal refers to the process of accessing only a portion of a data structure, such as an array or list, instead of traversing through the entire structure. It allows for efficient retrieval and manipulation of specific elements within the data structure.
Reverse Traversal: Reverse traversal involves accessing elements in reverse order, starting from the last element and moving towards the first element in a collection or data structure.
Subsection: A subsection is a smaller part or division of a larger section. In programming, it refers to breaking down a complex problem into smaller, more manageable parts.
Traversing: Traversing refers to the process of accessing each element in a data structure, such as an array or linked list, and performing some operation on it.
While loop: A while loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true.