Reference Guide

Key Topics

Term Definition Example
Array Fixed-size collection of values with the same type. int[] scores = {980, 900};
Index Position of an element in an array. scores[0]
Length Number of elements in an array. scores.length
Traversal Visiting every element in an array. for (int i = 0; i < scores.length; i++)
Bounds error Attempting to access an invalid index. scores[scores.length]
Enhanced for loop Loop that visits each element directly. for (int score : scores)

Loop Patterns

Loop type Syntax / pattern Fits when
Standard for for (int i = 0; i < scores.length; i++) You need the index or rank, or need to update array elements.
while int i = 0; while (i < scores.length) { ...; i++; } You need manual control of the index or stopping condition.
Enhanced for for (int score : scores) You only need each value and do not need its index.

Choosing a Loop

  • Need the rank or index? Use a standard for loop.
  • Need to update elements? Use a standard for loop.
  • Need manual condition control? Use a while loop.
  • Only need each score? Use an enhanced for loop.

College Board Requirements

AP CSA Unit 4, Topic 4.4: Array Traversals. The official 2025 Course and Exam Description is listed in References (College Board, 2025).

  • TODO (College Board, 2025, p. TODO): Add the exact Topic 4.4 learning objective ID and quoted wording.
  • TODO (College Board, 2025, p. TODO): Add each applicable Topic 4.4 essential knowledge ID and its exact quoted wording.

Lesson Plan

Learning Objective: Use standard for, while, and enhanced for loops to access every element in a one-dimensional array.

Success Criteria: You can traverse an entire array, explain why valid indices range from 0 to length - 1, repair a <= bounds error, choose an appropriate loop, and explain why an enhanced for loop cannot modify array elements by changing its loop variable.

Tech Talk

An array is a numbered row of values that all have the same type. Each value is stored at an index, and indexes start at 0, so the first score is scores[0]. A traversal means visiting every element in order, usually with a loop. If an array has length 4, it has four elements at indexes 0, 1, 2, and 3; therefore, the last valid index is length - 1. Asking for index 4 goes past the end of the array and causes an ArrayIndexOutOfBoundsException.

Our running scenario is a game leaderboard with scores stored in an integer array. A complete index-based traversal checks each position from 0 up to, but not including, scores.length.

A while loop can traverse the same leaderboard when you control the index yourself. An enhanced for loop is useful when you only need each value and not its index. Index 0 is displayed as Rank 1 because people count from 1, while arrays count from 0.

The loop condition must be rank < scores.length, not rank <= scores.length, because scores.length is one position past the final valid index.

Code Runner Challenge

Run the examples in Section 5 to see each traversal pattern’s output. Then complete the Popcorn Hack and Homework Hack runners in Section 6.


Runnable Code Examples

Run these examples to see their output.

A. Standard for Loop Traversal

Code Runner Challenge

Run the indexed for loop and inspect the leaderboard output

View IPYNB Source
// CODE_RUNNER: Run the indexed for loop and inspect the leaderboard output
public class LeaderboardTraversal {
    public static void main(String[] args) {
        int[] scores = {982, 915, 877, 844};

        for (int rank = 0; rank < scores.length; rank++) {
            System.out.println("Rank " + (rank + 1) + ": " + scores[rank]);
        }
    }
}

LeaderboardTraversal.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

B. while Traversal and Enhanced for

Code Runner Challenge

Run the while and enhanced for traversals

View IPYNB Source
// CODE_RUNNER: Run the while and enhanced for traversals
public class LeaderboardLoopChoices {
    public static void main(String[] args) {
        int[] scores = {982, 915, 877, 844};
        String[] playerNames = {"Avery", "Blair", "Casey", "Drew"};

        System.out.println("While loop with ranks:");
        int rank = 0;
        while (rank < scores.length) {
            System.out.println("Rank " + (rank + 1) + ": " + scores[rank]);
            rank++;
        }

        System.out.println("Enhanced for loop with player names:");
        for (String playerName : playerNames) {
            System.out.println(playerName);
        }
    }
}

LeaderboardLoopChoices.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

C. Compare < and <=

Code Runner Challenge

Compare the safe < condition with the failing <= condition

View IPYNB Source
// CODE_RUNNER: Compare the safe < condition with the failing <= condition
public class LeaderboardBoundsComparison {
    public static void main(String[] args) {
        int[] scores = {982, 915, 877, 844};

        System.out.println("Using <:");
        for (int rank = 0; rank < scores.length; rank++) {
            System.out.println("Rank " + (rank + 1) + ": " + scores[rank]);
        }

        System.out.println("Using <=:");
        try {
            for (int rank = 0; rank <= scores.length; rank++) {
                System.out.println("Rank " + (rank + 1) + ": " + scores[rank]);
            }
        } catch (ArrayIndexOutOfBoundsException error) {
            System.out.println("Java error: " + error.getMessage());
        }
    }
}

LeaderboardBoundsComparison.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

D. Enhanced for Loop Limitation

Code Runner Challenge

Compare changing an enhanced for variable with updating array values by index

View IPYNB Source
// CODE_RUNNER: Compare changing an enhanced for variable with updating array values by index
public class LeaderboardUpdateChoices {
    public static void main(String[] args) {
        int[] scores = {700, 800, 900};

        System.out.println("After changing the enhanced loop variable:");
        for (int score : scores) {
            score += 50;
        }
        for (int score : scores) {
            System.out.println(score);
        }

        System.out.println("After changing elements with an index-based loop:");
        for (int index = 0; index < scores.length; index++) {
            scores[index] += 50;
        }
        for (int score : scores) {
            System.out.println(score);
        }
    }
}

LeaderboardUpdateChoices.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hacks & Practice Tasks

Popcorn Hack

Use all three loop forms on the same six-player leaderboard. Replace the sample values, complete every TODO, and run the code: use an indexed for loop for rank and score, a while loop to total the scores, and an enhanced for loop to count scores at or above 900. Check that the total and count match your data.

Code Runner Challenge

Complete the three traversal TODOs and run your leaderboard

View IPYNB Source
// CODE_RUNNER: Complete the three traversal TODOs and run your leaderboard
public class LeaderboardPopcorn {
    public static void main(String[] args) {
        int[] scores = {760, 845, 912, 688, 934, 801};

        System.out.println("Ranked players:");
        // TODO: Use an indexed for loop to print every rank and score.

        int total = 0;
        int index = 0;
        // TODO: Use a while loop to add every score to total and advance index.
        System.out.println("Total score: " + total);

        int highScoreCount = 0;
        // TODO: Use an enhanced for loop to count scores >= 900.
        System.out.println("Scores at least 900: " + highScoreCount);
    }
}

LeaderboardPopcorn.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack

Complete the TODOs in the runner to analyze the leaderboard. Use a standard indexed for loop to print each rank and score and find the minimum and maximum; use a while loop to calculate the total and average; use an enhanced for loop to count passing scores; then use an indexed loop to add the bonus to every array element and print the updated values. Use scores.length so the solution still works if the array size changes.

Test your program with at least one different array length and verify that every traversal still visits exactly the valid elements.

Code Runner Challenge

Complete the traversals, calculations, and array update

View IPYNB Source
// CODE_RUNNER: Complete the traversals, calculations, and array update
public class LeaderboardHomework {
    public static void main(String[] args) {
        int[] scores = {710, 865, 903, 947, 981, 824};

        int minimum = scores[0];
        int maximum = scores[0];
        System.out.println("Leaderboard:");
        // TODO: Use an indexed for loop to print ranks and find min and max.
        System.out.println("Lowest score: " + minimum);
        System.out.println("Highest score: " + maximum);

        int total = 0;
        int index = 0;
        // TODO: Use a while loop to total all scores and advance index.
        double average = (double) total / scores.length;
        System.out.println("Average score: " + average);

        int passingCount = 0;
        // TODO: Use an enhanced for loop to count scores >= 900.
        System.out.println("Passing scores: " + passingCount);

        // TODO: Use an indexed for loop to add 10 to every stored score.
        System.out.println("Scores after bonus:");
        for (int score : scores) {
            System.out.println(score);
        }
    }
}

LeaderboardHomework.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

References

College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025].

All Java lessons