Skip to content

Course navigation

For teachersTopic 4.4 · Lesson kit

Array Traversals

  • 3 class periods
  • 45 minutes each
  • Objective 4.4.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    3 periods of 45 minutes

  • Worksheet

    Puzzles, about 30 minutes

  • Worksheet key

    Answer key

  • Exit ticket

    End of the last period

  • Exit ticket key

    Answer key

Download all AP CSA teacher filesEvery topic's slides, lesson plan, worksheet, and exit ticket, with keys (.zip)

At a glance

Pacing
3 class periods of 45 minutes
Learning objectives
4.4.A
Essential knowledge
4.4.A.14.4.A.24.4.A.34.4.A.44.4.A.54.4.A.6
Materials
Projector and the Lily Pad Loops slide deckWhiteboard and markersMini whiteboards or scrap paper (trace tables)IDE on every computerPrinted Lily Pad Loops puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upfive temperatures, or five hundred? (slide 2)
  2. 0:05–0:1712 minDirect instructionthe loop counter is the index (slides 3–5)
  3. 0:17–0:236 minDirect instructionone step past the end (slide 6)
  4. 0:23–0:3512 minGuided practicewhich elements does each loop visit? (slide 7) and worksheet question 2
  5. 0:35–0:427 minIndependent practiceworksheet question 1
  6. 0:42–0:453 minClosuresay the header out loud

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:044 minWarm-upwrite three headers
  2. 0:04–0:1410 minDirect instructionbackward and while traversals (slides 8–9)
  3. 0:14–0:217 minDirect instructiona while loop that stops early (slide 10)
  4. 0:21–0:3110 minGuided practiceworksheet questions 4 and 8
  5. 0:31–0:398 minDirect instructionthe enhanced for loop (slides 11–12)
  6. 0:39–0:434 minIndependent practicestart worksheet question 3
  7. 0:43–0:452 minClosureelement or index?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Exit ticket
  1. 0:00–0:044 minWarm-upthe Think First prediction
  2. 0:04–0:139 minDirect instructionchanging the copy (slides 13–14)
  3. 0:13–0:185 minGuided practiceworksheet question 6
  4. 0:18–0:268 minDirect instructionarrays of objects (slides 15–16)
  5. 0:26–0:337 minGuided practicenew plants (slide 17) and worksheet question 7
  6. 0:33–0:385 minDirect instructionchoosing and rewriting (slides 18–21)
  7. 0:38–0:402 minClosurecopy or the real thing? (slide 22)
  8. 0:40–0:455 minExit ticket

Overview

Day 1 is the indexed for loop that visits every element (4.4.A.1, 4.4.A.2): the counter is the index, it starts at 0, and the test is i < arr.length because the last valid index is length - 1. Day 2 changes the start, test, and update to go backward, skip, or visit part of an array, writes the same traversals as while loops (including one that stops early with the bounds test first), and introduces the enhanced for loop (4.4.A.3). Day 3 is what the enhanced for loop variable really holds: assigning to it never changes the array (4.4.A.4), calling a mutator on it changes the object an element refers to but never the reference stored in the array (4.4.A.5), and any enhanced for loop can be rewritten as an indexed for or while loop (4.4.A.6).

Students created arrays, used arr[i], and met ArrayIndexOutOfBoundsException in Topic 4.3; they wrote while and for loops in Topics 2.7 and 2.8, short-circuit && in Topic 2.5, and classes with mutators and object references in Topics 3.3–3.6. Stay inside the topic boundary: the standard array algorithms (sum, average, minimum and maximum, counting, shifting, reversing in place) are Topic 4.5, and ArrayList and 2D arrays come later. Loop bodies today print, change elements one at a time, or call a mutator. If a student asks how to add up an array, say that is tomorrow’s topic.

Teacher note

The slides are the Lily Pad Loops deck (22 slides); slide numbers below refer to it. Day 1 uses slides 1–7, Day 2 uses slides 8–12, and Day 3 uses slides 13–22. The Lily Pad Loops puzzle worksheet (10 questions, about 30 minutes) is spread across the three days: questions 1 and 2 on Day 1, questions 4 and 8 in class on Day 2 with question 3 started as homework, questions 6 and 7 in class on Day 3, and questions 5, 9, and 10 as Day 3 homework.

Files whose names end in .snippet.java hold only the statements that go inside main; paste them into the main of a scratch class to run them. All files are in the topic’s examples/ folder.

  • Day 1 demonstrations: PrintTemps, DoublePoints, LengthParens.java (compile error), PastTheEnd (runtime error), TraceWords.
  • Day 2 demonstrations: Backward, BackwardWrong (runtime error), EveryOther, MiddleOnly, WhileTemps, UntilDone, GuardOrderWrong (runtime error), EnhancedTemps, EnhancedNames, ValueAsIndex (runtime error), WrongVarType.java (compile error).
  • Day 3 demonstrations: EnhancedAssign, ShoutNames, ShoutNamesFixed, TeamBonus.java, TeamReplace.java, TeamReplaceFixed.java, ThreeWays, RewriteWrong, RosterDay.java (optional extension).
  • Printed only (exit ticket): ExitHops, ExitNames, and ExitNamesWhile.

The deck’s code uses temps = {61, 64, 58, 70} (and a fifth value, 66, on slides 2 and 7); the guide’s files use {68, 71, 75, 70}. The behavior is the same; just warn students the numbers differ.

Day 1 · Warm-up: Five temperatures, or five hundred?

Show slide 2. Students write code to print every value of {61, 64, 58, 70, 66}, most likely five println statements, then answer the slide’s question with a partner: with 500 temperatures, what changes from one line to the next, and what stays the same? Collect the answer you want on the board: only the number in the brackets changes, and it goes 0, 1, 2, 3, … That is a counter, and Topic 2.8 gave them a loop built for counters.

Day 1 · Direct instruction: The loop counter is the index

  1. Goals (slide 3). Read the five goals; goal 1 is today, goals 2–4 are Day 2 and the start of Day 3, and goal 5 is Day 3.
  2. Traversal (4.4.A.1, slides 4–5). Define traversing an array: using a loop to reach all of its elements, or an ordered part of them, one after another. When the loop’s counter is used as the index, it is an indexed loop (4.4.A.2).
  3. The header (slide 5). Point to each part: start at 0 (the first index), test i < temps.length (the last index is length - 1), update i++ (one element at a time). Ask: “Why temps.length and not 4?” The same loop then works for an array of any length.
  4. Two jobs for i. Run PrintTemps and trace it on the board with columns i, i < 4?, temps[i], printed. i picks the element and is also printed as the day number. Point out the last row: when i is 4 the test is false, so temps[4] is never touched.
  5. Changing elements. Run DoublePoints: points[i] = points[i] * 2 reads the element, then stores back into the same slot. Tell students to remember this loop; on Day 3 a shorter loop will look like it does the same job and will not.
  6. No parentheses. Show LengthParens.java and ask students to predict before you compile. It does not compile: an array’s length is scores.length, while a String’s is length(). Then run TraceWords, which uses both in one line (words.length in the header, words[k].length() in the body).

Misconception: length() on an array

Students carry length() over from String. Arrays use length with no parentheses; it is not a method. The compiler catches this (cannot find symbol ... method length()), so it is quick to fix, but it costs time on paper. TraceWords is the contrast to keep on the board.

Day 1 · Direct instruction: One step past the end

Slide 6. Ask students to predict the output of the <= loop before revealing it. The first four passes print all four values; then i is 4, 4 <= 4 is true, and temps[4] throws an ArrayIndexOutOfBoundsException. Run PastTheEnd to show the same crash in the IDE. Stress that the code compiles; the error happens only when it runs, because the compiler does not track what value i will hold. i <= temps.length - 1 is correct and means the same as i < temps.length.

Misconception: The loop should go up to the length

Students read “4 elements” and write i <= temps.length. The length counts elements, but indexes start at 0, so the last index is length - 1. Give them a check for any header: “What is the last value of i that passes the test? Is it a valid index?”

Day 1 · Guided practice: Which elements does each loop visit?

  1. Slide 7. Pairs write what each loop prints for {61, 64, 58, 70, 66} on mini whiteboards, with a trace of i. Loop A starts at 4 and steps by 2: it prints 66, 58, 61 (then i is -2 and the test fails). Loop B starts at 1 and stops before length - 1: it prints 64, 58, 70. Say that changing the start, test, and update is still a traversal, an ordered part of the array; Day 2 looks at these loops properly.
  2. Worksheet question 2 (pencil check). Pairs list the indexes each loop visits on an array of length 6. Answers: 0 1 2 3 4 5; 1 3 5; 5 4 3; 0 3; and 0 to 5, then a crash at 6. For each row, ask: “Which value of i fails the test first?”

Teacher note

Slide 7 previews Day 2 on purpose. If students are slow with loop A, trace only loop B today and come back to loop A in the Day 2 warm-up.

Day 1 · Independent practice: Independent practice

Students do worksheet question 1 (you’re the JVM) alone. The answer is A, 8 1: pads.length - 1 is 5, so i is 1 and 3, and the loop stops at 5. Check for the three distractors: B (test read as i < pads.length), C (started at 0), and D (update read as i++).

Day 1 · Closure: Closure

Each student says, or writes on a sticky note, the standard header for visiting every element of an array named scores, and finishes the sentence “The test is < and not <= because …” Look for “the last index is length - 1.”

Day 2 · Warm-up: Write three headers

On mini whiteboards, students write a for header for an array named stops that (a) visits every element, (b) visits every other element starting at 0, and (c) skips the first and last elements. Answers: for (int i = 0; i < stops.length; i++), the same with i += 2, and for (int i = 1; i < stops.length - 1; i++). Check each against the rule from Day 1: every index the body uses must be from 0 to length - 1.

Day 2 · Direct instruction: Backward and while traversals

  1. Backward (slides 8–9). Show the backward loop on slide 9 and run Backward. Ask: “Why does it start at length - 1 and not length? Why >= 0 and not > 0?” Then run BackwardWrong: it starts at stops.length, so the very first pass reads stops[4] and the program crashes before printing anything.
  2. Other steps and parts. Run EveryOther (i is 0, 2, 4, then 6 fails the test) and MiddleOnly (start at 1, stop before length - 1). The test still protects the array: with an even-length array, i += 2 stops before a bad index.
  3. The while version (4.4.A.2, slide 9). A while traversal is still indexed: declare the index before the loop, test it in the condition, use it in brackets, update it at the end of the body. Run WhileTemps and match each of its lines to the parts of the for header.

Misconception: A backward loop starts at the length

Students think “start at the end” means arr.length. The length counts elements; the last index is one less. BackwardWrong crashes on its first pass, which makes the point quickly. The other half of the error is i > 0, which quietly skips index 0; worksheet question 8 is exactly that bug.

Misconception: Forgetting the update in a while loop

In a for loop the update sits in the header; in a while loop it is a separate statement that is easy to leave out. Without i++, i stays 0 and the loop prints the first element forever. Have students point to all three parts (start, test, update) in every while traversal they write.

Day 2 · Direct instruction: A while loop that stops early

Slide 10. The condition i < line.length && !line[i].equals("done") stops at the marker or at the end, whichever comes first, so it prints Ana and Ben. Run UntilDone, then ask: “What if there is no "done"?” Run GuardOrderWrong, which puts the marker test first: on a two-element array it prints wash and dry, then crashes reading tasks[2]. With the bounds test first, && short-circuits (Topic 2.5) and tasks[2] is never evaluated. Point out that i was declared before the loop, so it still exists afterward and can report where the loop stopped.

Misconception: The order of the two tests does not matter

Students know && means “both must be true” and assume order is irrelevant. With &&, Java skips the right side when the left side is false, so the bounds test protects the array only if it comes first. The decoy tile in worksheet question 4 is this exact error.

Day 2 · Guided practice: Worksheet questions 4 and 8

  1. Question 4 (code tiles). Pairs build showUntilZero: int i = 0;, then while (i < d.length && d[i] != 0) {, System.out.println(d[i]);, i++;, }. The decoy is the condition with d[i] != 0 first, which crashes on array b (no 0) when it reads d[2].
  2. Question 8 (one-token fix). The backward loop prints only 9 and 3. Change > to >= on line 2, so index 0 is visited and 7 prints.

Day 2 · Direct instruction: The enhanced for loop

  1. The header (4.4.A.3, slides 11–12). Read for (int t : temps) aloud as “for each int t in temps.” The variable in the header is the enhanced for loop variable; on each pass it is assigned a copy of the next element, without using an index. Walk through slide 12’s pass table, then run EnhancedTemps: no i, no .length, no brackets.
  2. What it cannot do. It always starts at the first element, always moves forward one element at a time, and never tells you the index. Because it never uses an index you could get wrong, it cannot run past the end.
  3. Any element type. Run EnhancedNames: the loop variable is a String, so guest.length() works on it. Then show WrongVarType.java and ask whether it compiles: no, the variable’s type must match the element type.
  4. The variable is the element. Run ValueAsIndex: temps[t] uses a temperature as an index and crashes at index 68.

Misconception: The loop variable is an index

Students used to indexed loops write temps[t]. In an enhanced for loop, t already holds the element. It crashes when the values are large (ValueAsIndex) and, worse, prints the wrong values silently when the values happen to be valid indexes. Ask: “On the first pass, what number is in t?”

Day 2 · Independent practice: Independent practice

Students start worksheet question 3 (you’re the compiler) and finish it as homework. Snippet 1 does not compile (a double element cannot be stored in an int variable); snippet 2 prints 2 then 3; snippet 3 does not compile (h.length()); snippet 4 prints 4 and 7, then crashes at h[2]; snippet 5 crashes at once, because x is 4 and h[4] is out of bounds. Snippets 4 and 5 compile because the compiler cannot know what index a variable will hold.

Day 2 · Closure: Closure

Write for (int x : nums) and for (int x = 0; x < nums.length; x++) on the board. Students hold up one finger if x is an element and two if it is an index, for each. Then: “Which one can print the position?”

Day 3 · Warm-up: The Think First prediction

Point students to the Think First box above worksheet question 2: int[] lily = {2, 4, 6}; and then for (int x : lily) { x = x * 10; }. Does lily now hold 20, 40, and 60? Take a show of hands and write the vote on the board without saying who is right. Today settles it.

Day 3 · Direct instruction: Changing the copy

  1. Slide 13 (4.4.A.4). Show both loops and ask for each one’s output before revealing it: the enhanced loop prints 61, the indexed loop prints 71. Assigning to t changes only t, a copy. Use the guide’s picture: copying a phone number onto a sticky note and scribbling on the note does not change the contact list. Connect it to Topic 3.5: a parameter gets a copy of its argument in the same way.
  2. Run EnhancedAssign. Inside the loop p really is doubled (p is now 6, …), but the second loop shows the array still holds 3, 5, 8. Compare it with DoublePoints from Day 1, the indexed loop that did store the doubles. Settle the warm-up vote: lily still holds 2, 4, 6.
  3. Slide 14 (pause and try). Students write the output alone, then compare with a partner. Answer: cat!, owl!, emu!, then cat. Inside the loop, w refers to the new string; the array element still refers to "cat". Run ShoutNames and ShoutNamesFixed to show the same bug with toUpperCase() and its indexed fix.

Misconception: An enhanced for loop can change the array's values

The bug is silent: no compile error and no crash, the array just stays the same. Students often check the variable inside the loop (which did change) instead of the array afterward. Have them always print the array with a separate loop after the change, and give them the rule: to store a new value, you need arr[i] =, and only an indexed loop has an i.

Day 3 · Guided practice: Worksheet question 6

Pairs match the four loops to what f holds afterward. Answers: 1 → S (1 2 3, only the copy changed), 2 → Q (10 20 30), 3 → P (1 20 30, the test i > 0 skips index 0), 4 → R (7 2 3). Loop 4 is the one to discuss: it assigns to f[0], an element, so the array does change, and x reads each element as its pass begins (1, then 2, then 3, so f[0] becomes 2, 4, then 7).

Day 3 · Direct instruction: Arrays of objects

  1. Slides 15–16 (4.4.A.5). Ask first: “If the elements are objects, what does the loop variable get a copy of?” A reference (Topic 3.6). So p is an alias of the object the element refers to. Trace slide 16 with two boxes for the Plant objects and arrows from the array: p.water() follows the arrow and changes the object (5 becomes 7, 8 becomes 10); p = new Plant(1) moves only p’s arrow. Output: 7 and 10.
  2. Run TeamBonus.java (a mutator through the loop variable: Ada 15, Bo 12) and TeamReplace.java (a new object assigned to p: Ada 10, Bo 7, unchanged). Extend the sticky-note picture: now the note holds a house address; painting the door at that address changes the house, but writing a new address on the note changes only the note.

Misconception: Objects in an enhanced for loop work the same as int values

After Day 3’s first half, some students overcorrect and say an enhanced for loop can never change anything. Calling a mutator on the loop variable does change the object, because the variable and the element refer to the same object. What it cannot change is which object each element refers to. Keep the two statements on slide 16 side by side.

Day 3 · Guided practice: New plants

  1. Slide 17. Both versions start from a fresh {new Plant(5), new Plant(8)}. Loop A prints 5: it moves only p. Loop B prints 1: garden[i] = new Plant(1) replaces the element. Run TeamReplaceFixed.java to show the indexed fix on the Player array (Rookie 0 twice).
  2. Worksheet question 7 (two truths and a lie). Claim 2 is the lie: pond[1] still refers to Bo. On each pass f.hop() changes the real Ada or Bo (claim 1 is true), then f = new Frog("Cy") moves only f, so the second f.hop() goes to a Cy that is lost when the pass ends (claim 3 is true).

Day 3 · Direct instruction: Choosing and rewriting

  1. One traversal, three ways (4.4.A.6, slides 18–19). The rewrite trick: make the first line of the body String p = pets[i]; and the rest of the body stays the same. The slide’s caption says pets[i]; in its while version the index is k, so it is pets[k] there. Run ThreeWays to show all three printing the same lines.
  2. Rewriting with the index by mistake. Run RewriteWrong: it prints 0, 1, 2 instead of the ages, because it prints i instead of ages[i].
  3. Which loop? (slide 20). Read the table. The direction to stress: every enhanced for loop can become an indexed loop, but not the reverse; tasks that need the position, a different order, part of the array, or a new value stored in a slot need an indexed for or while. Slide 21 lists the vocabulary; leave it up during the closure.

Misconception: Printing the counter instead of the element

When rewriting an enhanced loop, students replace the loop variable with i instead of arr[i]. The code compiles and runs, so nothing warns them. Teach the rewrite as “declare the old variable as the first line of the body,” which makes the mistake hard to make.

Teacher note

If time allows, or as an extension for fast finishers, have students predict the output of RosterDay.java, which uses an enhanced for loop with a mutator, an element assignment, an indexed loop, and a backward while loop on one array of objects.

Day 3 closure and homework

Slide 22: partners finish the sentence starter, “The loop variable only holds a copy, so to change the array I need an index (arr[i] = in an indexed loop).” Homework is worksheet questions 5 (snippet pool: 0, < jumps.length, jumps[i]), 9 (face-off), and 10 (wrap-up reflection), plus anything left of question 3.

Day 3 · Exit ticket: Exit ticket

Give the exit ticket for the last 5 minutes. Score each question separately: question 1 checks indexed traversals with a changed start and step and the enhanced for copy (4.4.A.2–4.4.A.4), question 2 checks objects in an enhanced for loop (4.4.A.5), and question 3 checks choosing the while loop that matches an enhanced for loop (4.4.A.6). Re-teach the weakest one at the start of Topic 4.5.

Exit ticket

Question 1 · Multiple choice

What does this code print?

int[] hops = {4, 9, 2, 7, 5};
for (int i = hops.length - 1; i > 0; i -= 2)
{
    hops[i] = hops[i] + 1;
}
for (int h : hops)
{
    h = h * 10;
}
for (int h : hops)
{
    System.out.print(h + " ");
}
System.out.println();
  1. 40 90 30 70 60
  2. 5 9 3 7 6
  3. 4 10 3 8 6
  4. 4 9 3 7 6
Check your reasoning

D. hops.length - 1 is 4, so the first loop starts at i = 4, then i = 2; at i = 0 the test 0 > 0 is false. It adds 1 to hops[4] (5 becomes 6) and hops[2] (2 becomes 3), so the array is {4, 9, 3, 7, 6}. The second loop assigns to h, which holds only a copy of each element, so the array does not change. The third loop prints each element followed by a space.

A treats h = h * 10 as changing the array, but the enhanced for loop variable is a copy. B lets the first loop reach index 0, but i > 0 is false when i is 0. C moves one index at a time (4, 3, 2, 1), but i -= 2 skips every other index.

Question 2 · Multiple choice

A Plant class has a constructor Plant(int h) that sets the height, a mutator water() that adds 2 to the height, and an accessor getHeight(). Each loop runs on a fresh array Plant[] garden = {new Plant(5), new Plant(8)};. After which loop does garden[0].getHeight() return 7?

  1. for (Plant p : garden) { p = new Plant(7); }
  2. for (Plant p : garden) { p.water(); }
  3. for (int i = 1; i < garden.length; i++) { garden[i].water(); }
  4. for (int i = garden.length - 1; i > 0; i--) { garden[i] = new Plant(7); }
Check your reasoning

B. Each pass, p holds a copy of an element’s reference, so it refers to the same object as the element. p.water() changes that object, and garden[0]’s plant grows from 5 to 7.

  • A is wrong: assigning a new object to p moves only p. The references stored in garden do not change, so garden[0] still has height 5.
  • C is wrong: the loop starts at index 1, so only the second plant is watered (8 becomes 10).
  • D is wrong: the test i > 0 stops before index 0. Only garden[1] is replaced by a plant of height 7; garden[0] still has height 5.

Question 3 · Multiple choice

Which while loop prints the same output as this enhanced for loop? Each choice comes right after the line that creates names.

String[] names = {"Ada", "Kenji", "Bo"};
for (String n : names)
{
    System.out.println(n + " " + n.length());
}
  1. int i = 0; while (i < names.length) { String n = names[i]; System.out.println(n + " " + n.length()); i++; }
  2. int i = 0; while (i <= names.length) { String n = names[i]; System.out.println(n + " " + n.length()); i++; }
  3. int i = 0; while (i < names.length) { String n = i; System.out.println(n + " " + n.length()); i++; }
  4. int i = 0; while (i < names.length) { String n = names[i]; System.out.println(n + " " + n.length()); }
Check your reasoning

A. The index starts at 0 before the loop, the condition i < names.length keeps it a valid index, names[i] takes the place of the loop variable, and i++ is the last statement of the body. Laid out as code:

String[] names = {"Ada", "Kenji", "Bo"};
int i = 0;
while (i < names.length)
{
    String n = names[i];
    System.out.println(n + " " + n.length());
    i++;
}

Both loops print Ada 3, Kenji 5, and Bo 2, each on its own line.

B uses <=, so after printing the three lines it reaches names[3] and throws an ArrayIndexOutOfBoundsException. C uses the index in place of the element: i is an int, not a name, so String n = i; does not compile. D never changes i, so i < names.length stays true and it prints Ada 3 forever.