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
- Goals (slide 3). Goal 1 is today; goals 2 and 3 are Day 2; goals 4 and 5 are Day 3.
- 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
rstill, the inner loop walkscacross the whole row. - Each piece has a job (slide 5). Read the table:
r < grid.lengthgives every row index (the outer array’s length is the number of rows);c < grid[0].lengthgives 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. - Worked example (slide 6). Before revealing the output, ask: “How many times does the
Teamlabel print? How many times does the innerprintrun?” The label is in the outer body, so it runs once per row (2); the innerprintruns once per element (2 × 3 = 6);println()sits after the inner loop’s closing brace, so it ends each row. RevealTeam 0: 3 1 4andTeam 1: 2 0 5. - Optional demo. Run
RowMajorPrintand walk its trace table from the guide: the column index changes fastest. Then runRowMajorUpdate: the same loops withtickets[row][col] += 2change 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
- 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.
- 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 (
ctogames[0].length,rtogames.length), and the element is stillgames[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). - Optional demo. Run
ColumnMajorPrintand thenShowtimeColumns, and put the two visit sequences for the ticket table side by side on the board: row-major12 5 9 7 3 10, column-major12 7 5 3 9 10. Same six values, different order. - 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]usescas the row index, so whencis 0 it reads part of row 0, not column 0, and whencreaches 2 it asks for row 2. RunIndexesSwapped, thenIndexesSwappedFixed.
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
- 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>= 0so 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. - 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. RunBackwardOffByOne: nothing prints before the crash. - 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 bygames.length):4 5. The bound belongs to the index that moves. Optionally runOneRowOneColumn.
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:
- Columns right to left (compare with
ColumnsRightToLeftin the guide). - Rows bottom to top, each row left to right.
- 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
- 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
forloop 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:menuisString[][],dayisString[],dishisString. Each header drops one pair of brackets. - 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
forloop 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.) - Optional demo. Run
EnhancedPrint, which prints the ticket table with no indexes, thenEnhancedSeats(aString[][], printing initials withsubstring). The shape is the same for any element type; only the types in the headers change. - Wrong types don’t compile. Run
OuterTypeWrong(intfor the outer variable:int[] cannot be converted to int), thenMenuHeaders, which tries three wrong outer headers at once:String,String[][], andString[]overmenu[0]. Read each compiler message with the class, then runMenuHeadersFixed.
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
- 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 variablenholds a copy of each element;n = 10changes the copy, and the next pass gets a fresh copy. The array is never assigned to. - Through the row, it changes (slide 18, right side). Reveal the right side: 10. The outer variable
rowholds a copy of a reference to the real row array, the alias idea from Topic 3.6, sorow[i] = 10assigns to an element of the shared row. Summarize on the board: assigning to an element location (grid[r][c]orrow[i]) changes the array; assigning to the inner enhanced variable never does. - Optional demo. Run
EnhancedNoChange(adding 2 tocountsix times leaves12 10), thenRowReference(the same bonus throughday[col]gives14 12). Finish withThreeWays: the same+= 1done three ways prints1 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.