Skip to content

Course navigation

For teachersTopic 4.12 · Lesson kit

2D Array Traversals

  • 3 class periods
  • 45 minutes each
  • Objective 4.12.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.12.A
Essential knowledge
4.12.A.14.12.A.2
Materials
Projector and the Every Box, In Order slide deckWhiteboard and markersMini whiteboards or scrap paper (visit-order grids)IDE on every computer (Days 1 to 3)Printed Every Box, In Order puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Activity
  1. 0:00–0:055 minWarm-upread the whole table aloud (slide 2)
  2. 0:05–0:2015 minDirect instructiontwo loops, row-major order (slides 3–6)
  3. 0:20–0:277 minDirect instructioneach loop gets its own length (slide 7)
  4. 0:27–0:325 minActivityDay 1 pause and try — stars and visits (slide 8)
  5. 0:32–0:4210 minGuided practicepredict, then run row-major traversals in the IDE
  6. 0:42–0:453 minClosurewhich length bounds which loop?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Activity
  1. 0:00–0:055 minWarm-upworksheet question 8, the one-token fix
  2. 0:05–0:1712 minDirect instructioncolumn-major order, swap the loops not the brackets (slides 9–11)
  3. 0:17–0:2710 minDirect instructionbackward, one row, one column (slides 12–14)
  4. 0:27–0:325 minActivityDay 2 pause and try — one index, both brackets (slide 15)
  5. 0:32–0:4210 minGuided practicerewrite one traversal three ways, then worksheet question 1
  6. 0:42–0:453 minClosureacross or down?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upworksheet question 2 and the type of a row
  2. 0:05–0:1712 minDirect instructionnested enhanced for loops (slides 16–17)
  3. 0:17–0:2710 minDirect instructionchanging the copy, not the array (slide 18)
  4. 0:27–0:358 minGuided practicewhich loop for which job? (slide 19)
  5. 0:35–0:405 minClosurevocabulary and sentence starter (slides 20–21)
  6. 0:40–0:455 minExit ticket

Overview

Topic 4.12 has one learning objective (4.12.A: write traversals of a 2D array and determine their results) and two essential knowledge statements. Day 1 is row-major order with nested indexed for loops: the outer loop picks a row, the inner loop walks across it (4.12.A.1). Day 2 is column-major order and other orders the programmer defines: backward, one row, one column, a diagonal (4.12.A.1). Day 3 is the nested enhanced for loop: the outer variable is a row, so its type is a 1D array, the inner variable is an element, and assigning to the inner variable never changes the array (4.12.A.2).

Keep one rule running through all three days: the first bracket is always the row. The order of the loops decides the visit order; it never changes what grid[r][c] means. Almost every bug in this topic (swapped bounds, swapped indexes, the wrong loop variable type) comes from losing track of that rule.

Students know nested loops (Topic 2.11), 1D array traversals with indexed and enhanced for loops, including the copy rule for the enhanced loop variable (Topic 4.4), reference aliases (Topic 3.6), and 2D array creation, grid.length, grid[0].length, and access (Topic 4.11). Stay inside the topic boundary: traversals here print, count visits, or change every element. Standard algorithms on 2D arrays (sums, averages, minimum and maximum, counting matches, searching) are Topic 4.13; if a student asks for a row total, say it is next topic’s job.

Teacher note

The slides are the Every Box, In Order deck (21 slides); slide numbers below refer to it. Day 1 uses slides 1–8, Day 2 slides 9–15, Day 3 slides 16–21. The deck’s running array is games, a 2-by-3 table of scores (rows are teams, columns are games); the study guide’s is tickets (rows are days, columns are showtimes). Same shape, same values pattern: point out the match when students move between them.

The Every Box, In Order puzzle worksheet (9 questions, about 30 minutes) is split across the three nights: question 8 after Day 1; questions 1–4 after Day 2; questions 5, 6, 7, and 9 after Day 3. The worksheet’s Think First prediction (how many times each loop body runs) is settled by question 1.

IDE demonstrations are in the topic’s examples/ folder (.snippet.java files hold only the statements for main): Day 1: RowMajorPrint, RowMajorUpdate, BoundsSwapped, TemperatureRows, CountVisits. Day 2: ColumnMajorPrint, ShowtimeColumns, IndexesSwapped, IndexesSwappedFixed, ColumnLetters, BackwardPrint, BackwardOffByOne, OneRowOneColumn, ColumnsRightToLeft, SnakeOrder. Day 3: EnhancedPrint, EnhancedSeats, OuterTypeWrong, MenuHeaders, MenuHeadersFixed, InnerTypeWrong, EnhancedNoChange, RowReference, ThreeWays, ValueAsIndex, GardenGrid. Printed only (exit ticket): ExitBins, ExitTiles, ExitSeats.

Day 1 · Warm-up: Read the whole table aloud

Show slide 2. Partners take turns reading every number in the table aloud, then answer the slide’s two questions. Almost everyone reads left to right, then down: 3, 1, 4, 2, 0, 5. For “just the scores from game 2,” they read down column 2: 4, 5. Ask: “What changed?” Listen for “I went down instead of across” and “I only needed one number to move.” Write both readings on the board and keep them: Day 1 is the first reading, and Day 2 is the second.

Day 1 · Direct instruction: Two loops, row-major order

  1. Goals (slide 3). Goal 1 is today; goals 2 and 3 are Day 2; goals 4 and 5 are Day 3.
  2. Why two loops (slide 5; 4.12.A.1). A 1D array needed one index, so one loop (Topic 4.4). A 2D array element needs two indexes, so the traversal needs two loops, one inside the other. Recall the Topic 2.11 rule: the inner loop finishes all of its passes before the outer loop moves on. So while the outer loop holds r still, the inner loop walks c across the whole row.
  3. Each piece has a job (slide 5). Read the table: r < grid.length gives every row index (the outer array’s length is the number of rows); c < grid[0].length gives every column index (row 0 is a 1D array, and its length is the number of columns); grid[r][c] is row first, always. Point at the visit-order grid: 1st through 3rd across row 0, then 4th through 6th across row 1. Name it: visiting across each row before moving down is row-major order, the same order as the warm-up’s first reading.
  4. Worked example (slide 6). Before revealing the output, ask: “How many times does the Team label print? How many times does the inner print run?” The label is in the outer body, so it runs once per row (2); the inner print runs once per element (2 × 3 = 6); println() sits after the inner loop’s closing brace, so it ends each row. Reveal Team 0: 3 1 4 and Team 1: 2 0 5.
  5. Optional demo. Run RowMajorPrint and walk its trace table from the guide: the column index changes fastest. Then run RowMajorUpdate: the same loops with tickets[row][col] += 2 change every element, because the code names an actual array location.

Misconception: The inner body runs as many times as the two lengths added

Students add the loop counts (2 + 3) instead of multiplying, because they picture each loop running once. The inner loop starts over for every pass of the outer loop. Ask for the count before every trace today: inner body = rows × columns, outer body = rows. Slide 8 and CountVisits (4 rows × 6 columns = 24, not 10) check it.

Day 1 · Direct instruction: Each loop gets its own length

Show slide 7 with the output covered. Ask: “The outer loop uses games[0].length and the inner uses games.length. What prints?” Then reveal: 3 1, 2 0, then an ArrayIndexOutOfBoundsException. Walk it: r is allowed up to 2 because there are 3 columns, but there are only 2 rows, so games[2] does not exist. Point out the second clue: each printed line is missing its last column, because the inner loop stops at 2. Run BoundsSwapped to show the same crash with tickets.

Misconception: Either length works for either loop

Students treat grid.length and grid[0].length as interchangeable, and on a square array they are, which is why the bug hides. Teach a matching rule instead of memorizing: the variable in the first bracket loops to grid.length; the variable in the second bracket loops to grid[0].length. Have students draw a line on their code from each loop variable to its bracket and then to its bound. Test every traversal on a non-square array.

Day 1 pause and try: stars and visits

Show slide 8. Students write the exact output on mini whiteboards, plus how often each statement runs. Answer: *** 12. new int[3][4] has 3 rows and 4 columns, so the * in the outer body prints 3 times, all on one line, and visits++ in the inner body runs 3 × 4 = 12 times. The final println prints a space, then 12. Diagnose wrong answers aloud: **** 12 swapped rows and columns; *** 7 added instead of multiplied; twelve stars put the * in the inner body.

Day 1 · Guided practice: Predict, then run

Students open the IDE. First, TemperatureRows: predict the three lines on paper (Day 0: 61 64, Day 1: 58 70, Day 2: 66 59), then run it. Then each student changes the array to 3 rows and 4 columns of their own numbers, predicts, and runs again; the loops must work without any change to the headers. Students who finish early change RowMajorUpdate to multiply every element by 10 and print the whole array after.

Teacher note

Walk the room and look at the headers. Any student who typed a number (r < 3) instead of a length should change it to grid.length and rerun with a different-sized array. The point of the lengths is that one loop works for every size.

Day 1 · Independent practice: Independent practice

Puzzle worksheet question 8 (the one-token fix) is homework. Its bug, r++ in the inner loop header, is a row-major traversal that never moves c, so it fits today. Students who finish can read guide section 4.12.1.

Day 1 · Closure: Closure

Cold-call: “In grid[r][c], which loop’s bound is grid.length?” (The one whose variable is in the first bracket, r.) “How many times does the inner body run for a 5-by-2 array?” (10.)

Day 2 · Warm-up: Worksheet question 8

Students check question 8 with a partner. The fix is line 4: r++ becomes c++. Ask one student to explain the output before the crash: c stays 0 while r climbs, so it prints g[0][0] (a), then g[1][0] (d), then asks for row 2. Point out that the code accidentally walked down column 0, which is today’s topic.

Day 2 · Direct instruction: Column-major order

  1. Swap the loops (slide 10; 4.12.A.1). Return to the warm-up’s second reading from Day 1. To read down each column, the outer loop must pick the column and the inner loop must walk down the rows, so the inner loop finishes a whole column before the outer loop moves right. Name it: column-major order. Point at the visit-order grid: 1st and 2nd down column 0, then 3rd and 4th down column 1.
  2. What does not change (slide 10). Have students compare slide 10’s headers with slide 6’s. The headers traded places, but each loop still uses its own length (c to games[0].length, r to games.length), and the element is still games[r][c]. Before revealing the output, ask how many lines print and how many numbers are on each (3 lines, 2 numbers: Game 0: 3 2, Game 1: 1 0, Game 2: 4 5).
  3. Optional demo. Run ColumnMajorPrint and then ShowtimeColumns, and put the two visit sequences for the ticket table side by side on the board: row-major 12 5 9 7 3 10, column-major 12 7 5 3 9 10. Same six values, different order.
  4. Swapping the indexes too (slide 11). Show the code, cover the output, and ask what prints. Reveal 3 1, 2 0, then the exception. games[c][r] uses c as the row index, so when c is 0 it reads part of row 0, not column 0, and when c reaches 2 it asks for row 2. Run IndexesSwapped, then IndexesSwappedFixed.

Misconception: Column-major means writing grid[col][row]

Because the column loop moves outside, students move the column variable to the first bracket too. The brackets describe a location, not a loop order: the first index is always the row. Have students say it aloud with the slide 11 title: “Swap the loops, not the brackets.” Worksheet question 3’s decoy tile g[c][r] and question 2’s choice D come back to this.

Day 2 · Direct instruction: Backward, one row, one column

  1. You choose the order (slide 13; 4.12.A.1, “a uniquely defined order”). Three choices control any traversal: which loop is outside, where each loop starts, and which way it counts. Show slide 13. To count backward, start at the last valid index, length - 1, and keep going while >= 0 so index 0 is still visited. Have students call out the output before the reveal: 5 0 2 4 1 3. It is still row-major (a whole row before the next), just in reverse.
  2. Starting at the length. Ask: “What if the outer loop started at games.length?” The first visit asks for row 2, which does not exist. Run BackwardOffByOne: nothing prints before the crash.
  3. One row or one column (slide 14). Only one index changes, so only one loop is needed. Hold the row at 1 and loop the columns (bounded by games[0].length): 2 0 5. Hold the column at 2 and loop the rows (bounded by games.length): 4 5. The bound belongs to the index that moves. Optionally run OneRowOneColumn.

Misconception: A backward loop starts at the length

Counting up, students write < grid.length, so counting down they write r = grid.length. The length is one past the last index. Teach the pair together: counting up stops before the length; counting down starts one below it. Worksheet question 4 tests both ends: the decoys t.length (crashes) and r > 0 (skips row 0).

Day 2 pause and try: one index, both brackets

Show slide 15. Students shade the boxes the loop visits in the grid and write the output. Answer: map. k takes 0, 1, 2, and sq[k][k] visits [0][0], [1][1], [2][2], the diagonal from top left to bottom right. Ask: “Why is the bound sq.length safe here?” (The array is square, 3 by 3, so the last row index and the last column index are both 2.) Stretch: “Which change visits the other diagonal?” (sq[k][sq.length - 1 - k], which prints xax.)

Day 2 · Guided practice: One traversal, three ways

In the IDE, students start from ColumnMajorPrint and change it three times, running after each change and recording the output:

  1. Columns right to left (compare with ColumnsRightToLeft in the guide).
  2. Rows bottom to top, each row left to right.
  3. Only the last column, with a single loop.

Then students start worksheet question 1 (pencil check) in class; it covers every order from Days 1 and 2 and settles the Think First prediction.

Teacher note

Students who finish early can trace SnakeOrder (even rows left to right, odd rows right to left) before running it. It is a uniquely defined order built from the same pieces, and it previews the kind of order an AP question may invent.

Day 2 · Independent practice: Independent practice

Puzzle worksheet questions 1–4 are homework: the pencil check of every order (finish it if not done in class), you’re the JVM (column-major spells hopper), the code tiles for printing each column with a label, and the snippet pool for printing rows bottom to top.

Day 2 · Closure: Across or down?

Write int[][] g = { {1, 2, 3}, {4, 5, 6} }; on the board. Students hold up one finger for row-major or two for column-major as you read a visit sequence: 1 4 2 5 3 6 (column-major), 1 2 3 4 5 6 (row-major), 3 6 2 5 1 4 (column-major, columns right to left). For the last one, ask which header changed.

Day 3 · Warm-up: Worksheet question 2 and the type of a row

Check worksheet question 2 with a show of hands (B, hopper). Then write int[][] games on the board and ask: “What is games[0]? What is its type?” (Row 0, a 1D array, int[].) “What is games[0][1]?” (One score, an int.) Keep the answers on the board; today’s loop headers use exactly those two types.

Day 3 · Direct instruction: Nested enhanced for loops

  1. The outer variable is a whole row (slide 17; 4.12.A.2). A 2D array is an array of arrays (Topic 4.11). An enhanced for loop over the outer array hands out its elements, which are rows, so the outer variable’s type is the type of a row, a 1D array. The inner loop goes through that row, so its variable has the element type. Read slide 17’s table: menu is String[][], day is String[], dish is String. Each header drops one pair of brackets.
  2. Always row-major (slide 17). The outer loop always goes through the rows first to last, and the inner loop always goes across a row first to last, so a nested enhanced for loop can only produce row-major order. Ask the worksheet’s Fair Question: “Could an enhanced for loop print the rows bottom to top?” (No; backward and column-major need indexes.)
  3. Optional demo. Run EnhancedPrint, which prints the ticket table with no indexes, then EnhancedSeats (a String[][], printing initials with substring). The shape is the same for any element type; only the types in the headers change.
  4. Wrong types don’t compile. Run OuterTypeWrong (int for the outer variable: int[] cannot be converted to int), then MenuHeaders, which tries three wrong outer headers at once: String, String[][], and String[] over menu[0]. Read each compiler message with the class, then run MenuHeadersFixed.

Misconception: The outer variable has the element type

The array holds int values, so students write for (int row : grid). The outer array’s elements are rows, each an int[], and an int variable cannot hold an array. The reverse slip, int[] for the inner variable, fails the same way with the types flipped (InnerTypeWrong, with String). Point back to the warm-up board: outer = type of grid[0], inner = type of grid[0][0]. Worksheet question 6, snippets 2 and 3, tests both directions.

Day 3 · Direct instruction: Changing the copy, not the array

  1. The copy rule from Topic 4.4 (slide 18; 4.12.A.2). Show only the left side. Ask: “Does stock[0][0] print 4 or 10?” Take a vote, then reveal 4. The inner variable n holds a copy of each element; n = 10 changes the copy, and the next pass gets a fresh copy. The array is never assigned to.
  2. Through the row, it changes (slide 18, right side). Reveal the right side: 10. The outer variable row holds a copy of a reference to the real row array, the alias idea from Topic 3.6, so row[i] = 10 assigns to an element of the shared row. Summarize on the board: assigning to an element location (grid[r][c] or row[i]) changes the array; assigning to the inner enhanced variable never does.
  3. Optional demo. Run EnhancedNoChange (adding 2 to count six times leaves 12 10), then RowReference (the same bonus through day[col] gives 14 12). Finish with ThreeWays: the same += 1 done three ways prints 1 4, 2 5, 2 5. Ask students to say which of the three lines comes from the enhanced inner variable before you run it.

Misconception: Assigning to the enhanced for variable changes the array

value += 2; looks like it changes the element, and the code compiles and runs without complaint, so students trust it. Students who learned the rule in Topic 4.4 often decide the opposite for 2D arrays and treat the outer variable as a copy too. Use both sides of slide 18 and ThreeWays to settle both: the inner variable is a copy of a value, the outer variable is a copy of a reference. Worksheet question 7 (claim 3 is the lie) and question 6, snippet 5, check it.

Misconception: Using an element's value as an index

Students who want a position write row[value] inside for (int value : row). An enhanced loop hands out values, not positions, so row[value] reads the wrong element or crashes. Run ValueAsIndex (Index 12 out of bounds for length 3). If you need positions, use indexed loops. The WATCH OUT after worksheet question 5 repeats this.

Day 3 · Guided practice: Which loop for which job?

Show slide 19 with the right column covered. Pairs fill in “Use” for each job on mini whiteboards, then reveal. Push on the reason for each indexed row: changing elements needs an assignment to an array location; column-major and backward need control of the indexes; positions need indexes because an enhanced loop gives values.

Then show GardenGrid from the guide’s Putting It Together and ask pairs to name, before running it, which kind of loop each of its three traversals should use and why: indexed row-major to replace "-" with "beans" (it changes elements), nested enhanced for to print by row (read only, row-major), indexed column-major to print by column (an order the enhanced loop cannot produce). Run it to confirm the output.

Day 3 · Independent practice: Independent practice

Puzzle worksheet questions 5, 6, 7, and 9 are homework: the Indexed for and Enhanced for face-off, you’re the compiler (five nested enhanced loop snippets), two truths and a lie (the copy versus the row reference), and who am I.

Day 3 · Closure: Closure and exit ticket

Show slide 20 (vocabulary) for a quick read-through, then slide 21: partners use the sentence starter to explain how to turn a row-major traversal into a column-major one (“I swap the loops, but the brackets stay grid[row][col]”). Then give the exit ticket (about five minutes). Score each question separately: question 1 checks tracing a column-major traversal whose inner loop counts backward (4.12.A.1), question 2 the copy rule versus the row reference (4.12.A.2), and question 3 choosing a nested enhanced for loop with the right types (4.12.A.2). Re-teach the weakest one at the start of Topic 4.13, which builds standard algorithms on these traversals.

Exit ticket

Question 1 · Multiple choice

What does this code print?

int[][] bins = { {5, 8, 2}, {9, 4, 6} };
for (int c = 0; c < bins[0].length; c++)
{
    System.out.print("Bin " + c + ":");
    for (int r = bins.length - 1; r >= 0; r--)
    {
        System.out.print(" " + bins[r][c]);
    }
    System.out.println();
}
  1. Three lines: Bin 0: 9 5, then Bin 1: 4 8, then Bin 2: 6 2
  2. Three lines: Bin 0: 5 9, then Bin 1: 8 4, then Bin 2: 2 6
  3. Two lines: Bin 0: 2 8 5, then Bin 1: 6 4 9
  4. Bin 0:, then an ArrayIndexOutOfBoundsException, because bins.length - 1 is 2 and there is no row 2
Check your reasoning

A. bins has 2 rows and 3 columns. The outer loop goes through the columns (c from 0 to 2), so this is column-major order: one line per column. For each column, the inner loop starts at the last row, bins.length - 1, which is 1, and counts down to 0, so the bottom value prints first. Column 0 holds 5 (row 0) and 9 (row 1), so it prints 9 5; column 1 prints 4 8; column 2 prints 6 2.

Bin 0: 9 5
Bin 1: 4 8
Bin 2: 6 2

B reads each column top to bottom, but the inner loop counts down from the last row. C treats the outer loop as going through the rows, but c runs to bins[0].length and is used as the column index in bins[r][c]. D takes bins.length as the number of columns, but it counts the rows, 2, so the inner loop starts at row 1.

Question 2 · Multiple choice

What does this code print?

int[][] tiles = { {2, 5}, {8, 3} };
for (int[] row : tiles)
{
    for (int t : row)
    {
        t *= 10;
    }
    row[1] = row[0] + 1;
}
System.out.println(tiles[0][1] + " " + tiles[1][1]);
  1. 5 3
  2. 21 81
  3. 3 9
  4. 50 30
Check your reasoning

C. t *= 10; changes only t, a copy of each element, so the inner loop changes nothing in tiles. row[1] = row[0] + 1; is different: row refers to the real row array, so it assigns to an element of tiles. Row 0 becomes {2, 3} and row 1 becomes {8, 9}, so it prints 3 9.

  • A is wrong: it treats row as a copy too, so nothing changes. The outer variable is a copy of a reference, and assigning through row[1] reaches the real row.
  • B is wrong: it believes t *= 10 multiplied every element (row[0] would be 20 and 80) before line 8 ran.
  • D is wrong: it believes t *= 10 changed the array and ignores line 8.

Question 3 · Multiple choice

String[][] seats holds student names, one row per table. Which nested enhanced for loop prints every name followed by a space, with each row on its own line?

  1. for (String row : seats) { for (String name : row) { System.out.print(name + " "); } System.out.println(); }
  2. for (String[] row : seats) { for (String name : seats) { System.out.print(name + " "); } System.out.println(); }
  3. for (String[] row : seats) { for (String name : row) { System.out.print(name + " "); System.out.println(); } }
  4. for (String[] row : seats) { for (String name : row) { System.out.print(name + " "); } System.out.println(); }
Check your reasoning

D. The outer variable is a String[] because the outer loop goes through seats, whose elements are rows, and each row is a 1D array of String. The inner variable is a String because the inner loop goes through one row, whose elements are single names. The println() comes after the inner loop and inside the outer loop, so it ends each row. Laid out with two tables:

String[][] seats = { {"Ava", "Ben", "Cy"}, {"Dee", "Eli", "Fay"} };
for (String[] row : seats)
{
    for (String name : row)
    {
        System.out.print(name + " ");
    }
    System.out.println();
}

It prints Ava Ben Cy and Dee Eli Fay on two lines.

A gives the outer variable the element type of one name, but each element of seats is a row, so it does not compile (String[] cannot be converted to String). B has the inner loop go through seats again, whose elements are rows, not names, so it does not compile either. C puts the println() inside the inner loop, so every name prints on its own line.