1. 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.

2. LxD Cycle Process

Empathize: Students often confuse an array’s length with its last valid index. In a leaderboard, that mistake can skip a player or cause an ArrayIndexOutOfBoundsException.

Define:

  • POV: CSA students need to connect array length, valid indices, and loop conditions because every complete traversal visits indices from 0 through length - 1.
  • Learning Goal: Students will traverse a one-dimensional array with standard for, while, and enhanced for loops.

Ideate:

  • HMW Question: How might we help students visualize a leaderboard’s length and last valid rank?
  • HMW Question: How might we show when an index-based loop is necessary and when an enhanced for loop is clearer?
  • Activity: Print leaderboard scores, demonstrate the <= error, and use an enhanced for loop to display values.

Prototype & Test: Read-only examples introduce the traversal patterns before students apply them in the two editable runners. The Popcorn Hack practices all three loop forms; the Homework Hack combines traversal, analysis, and array updates.

3. 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.

4. 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 (5 minutes)

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. Save the runners you want to submit with their 💾 buttons; all saved runners from this lesson can be submitted together.


5. Runnable Code Examples

Run these examples to see their output. You may edit and save them too; saved example runners are included with your assignment submission.

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 ...

6. Hacks & Practice Tasks

Complete and Submit Your Homework

Complete the Popcorn Hack and Homework Hack in the Java code runners on this lesson page. You do not need to create a separate notebook. Run each runner and save every runner you changed with its 💾 button. In the Submit Assignment section at the bottom of the lesson, submit your saved code. Put your written explanation in the submission Notes field.

Popcorn Hack (In-Class)

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. In the submission Notes, explain the valid index range, why the loop condition uses < instead of <=, and why an enhanced for loop is not the right choice for changing the stored array elements.

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 ...

Grading Plan (1 Point Total)

Part Points What earns the points
Popcorn traversals 0.2 Indexed for, while, and enhanced for each visit the array correctly for their stated purpose.
Indexed traversal 0.2 Homework prints ranks and correctly finds minimum and maximum using valid indexes.
while traversal 0.2 Homework totals each score once, advances the index, and calculates the average.
Enhanced traversal and update 0.2 Homework counts passing scores with enhanced for and updates stored values with an indexed loop.
Explanation and testing 0.2 Submission Notes explain valid indexes, < vs. <=, and loop choice; a different array length also works.
Total 1.0  

Quick Validation Checklist

  • Every runner is a complete Java class with main.
  • Every runner declares its own variables and prints visible output.
  • All six Java activities are code runners and end with ClassName.main(null);.
  • Example runners show visible output and can be saved for submission.
  • The Popcorn Hack uses indexed for, while, and enhanced for traversals.
  • The Homework Hack prints ranks, finds minimum/maximum, totals and averages, counts passing scores, and updates array elements.
  • Every traversal uses valid indexes and adapts to a changed array length.
  • Submission Notes explain the valid range, why < is used, and why indexed loops are needed to update elements.

7. Lesson Revisions

Revision Made: The lesson now keeps four reference examples as read-only Java snippets and uses only the Popcorn Hack and Homework Hack as editable code runners. The two runners ask students to apply indexed for, while, and enhanced for traversals to analyze and update arrays.


8. Feedback Evidence

Feedback Received: The assessed practice needs to be runnable and submittable from the lesson page, rather than being demonstrated only by examples. The two hack runners now provide the editable evidence for the assignment.


9. References

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

Submit Assignment

This submits the code from this lesson's code runner(s) below as a Gist for automatic review. Save each runner with its 💾 button before submitting.

    Need to update a submission later? Open the submissions dashboard.