Overview
This topic has one learning objective (4.13.A) and one essential knowledge statement (4.13.A.1), which lists the standard 2D array algorithms: minimum and maximum; sum and average; “at least one” and “all”; how many; consecutive pairs; duplicates; shifting and rotating a row or column; and reversing a row or column. Each one can apply to the whole array or to a designated row, column, or other region. Every algorithm is the 1D version from Topic 4.5. What is new is choosing which elements the loops visit. The day split follows the deck’s four parts:
- Day 1: aim the loops: whole array, one row, one column, a rectangle, the main diagonal. Totals and averages.
- Day 2: the best so far (minimum and maximum with its location), flags for “any” and “all”, and counters, with one answer for the whole array or one per row.
- Day 3: consecutive pairs (stop one early) and duplicates (compare with every later element).
- Day 4: shift, rotate, and reverse one row or column, then the exit ticket.
Students already know 2D array creation and access (Topic 4.11), nested and enhanced traversals in row-major and column-major order (Topic 4.12), the 1D algorithms (Topic 4.5), and integer division and casting (Topics 1.3 and 1.5). Stay inside the topic boundary: no linear or binary search by name (Topic 4.14), no sorting (Topic 4.15), and no recursion. Every array in the deck, the worksheet, and the exit ticket is rectangular.
One sentence runs through all four days, and it is the deck’s closure (slide 22): first pick which elements to visit, then pick what to do with each one. The guide ends on the same two decisions, so students who read it will recognize them.
Teacher note
The slides are the Work the Grid deck (22 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–7, Day 2 uses slides 8–13, Day 3 uses slides 14–17, and Day 4 uses slides 18–22. The Work the Grid puzzle worksheet (10 questions, about 30 minutes) is spread across the four days: questions 1 and 2 on Day 1, question 7 on Day 2, questions 6 (versions 1 and 2), 3, and 8 on Day 3, and questions 4 and 5 on Day 4. Questions 6 and 9 are homework after Day 2 (version 1 and 2 of question 6 are reviewed in the Day 3 warm-up); question 10 and anything unfinished are homework after Day 4.
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:
TotalAll,TotalEnhanced,AverageIntDivision,RowAndColumn,SecondHalf,ColumnWrongBound(run-time error). - Day 2 demonstrations:
MaxStartZero,MaxAll,MinColumn,AnyEmpty,AllPassed,FlagPerRow,CountPerRow,CountDiagonal,AntiDiagonalCrash(run-time error),AntiDiagonalFixed. - Day 3 demonstrations:
StepIncreases,ColumnMatches,PairsTooFar(run-time error),RowDuplicates,WholeDuplicates,DuplicateSelf,DuplicateSelfFixed. - Day 4 demonstrations:
RotateRowLeft,ShiftColumnDown,RotateRightWrong,RotateRightFixed,ReverseRow,ReverseColumn,ReverseTwice,NoTempReverse. - Printed only (exit ticket):
GridExitColumn,GridExitRotate,GridExitAllOver.
Day 1 · Warm-up: Questions about a grid
Show slide 2: a theater with 4 rows of 6 seats and three questions. Pairs have two minutes to say which seats they would need to look at for each one. Collect answers: (1) only row 2, so one loop across that row; (2) only column 0, so one loop down that column; (3) every seat, so nested loops. Write “Which elements?” on the board and leave it up all week: the question decides the elements before anyone writes code.
Day 1 · Direct instruction: Fix one index, loop the other
- Goals (slide 3). Read the five goals; Day 1 is goal 1, Day 2 goals 2 and 3, Day 3 goal 4, Day 4 goal 5. Tell students that every algorithm on the list is one they wrote for a 1D array in Topic 4.5.
- The whole array (4.13.A.1). Run
TotalAll: the total starts at 0 before both loops and gainsscores[r][c]inside both, so it printsTotal: 96. The average divides by the number of elements,grid.length * grid[0].length(12 here), with a cast first:Average: 8.0. Then runTotalEnhanced(Total: 45,Average: 7.5): when positions do not matter, nested enhanced loops from Topic 4.12 do the same job. - The cast (Topic 1.5). Show
AverageIntDivisionand ask for a prediction before running it. Storing in adoubleis not enough:45 / 6is already7before it is stored, so it printsAverage: 7.0. - Fix one index, loop the other (slides 4–5). Walk the table on slide 5 top to bottom. One row: the row index stays fixed and
cruns togrid[row].length. One column: the column index stays fixed andrruns togrid.length. The main diagonal of a square array: one variable in both places,grid[i][i]. Repeat the bound rule: a row has one element per column; a column has one element per row. - Any rectangle. Run
SecondHalf(Quizzes 2 and 3 total: 46): the row loop covers every row, and the column loop starts at 2 instead of 0. Moving a loop’s start or its bound aims the algorithm at any rectangle.
Misconception: Storing the average in a double keeps the fraction
Students believe double avg = total / count; gives a decimal answer. Java divides the two int values first and drops the fraction; only then is the result widened. AverageIntDivision prints 7.0 instead of 7.5. Cast one operand before dividing: (double) total / count.
Day 1 · Direct instruction: A row total, a column average, a column bound bug
- Worked example (slide 6). Rows are days, columns are bake-sale items. Row 2 is 10 + 5 + 13 + 9 = 37. Column 1 is 8 + 14 + 5 = 27, and a column has one element per row, so the average divides by
sales.length:27.0 / 3is9.0. RunRowAndColumnfor the same moves on the quiz array (Student 1 total: 33,Quiz 2 average: 8.0). - Watch out (slide 7). Cover the error box and ask what the program prints.
sales[0].lengthis 4, the number of columns, but the column holds only 3 elements. Passes 0–2 work;r = 3asks forsales[3][1]and throwsArrayIndexOutOfBoundsException, before theprintln, so nothing prints. RunColumnWrongBoundfor the same crash on the quiz array. - Ask the question that fixes it: “Which index does
rstand for?” A row index, so its bound is the number of rows.
Misconception: A column loop stops at the number of columns
Working on a column, students reach for “columns” and write grid[0].length as the bound for r. On a square array the bug hides; on any other shape it crashes or skips elements. Have students say the index’s job out loud (“r is a row number”) before they write its bound. The worksheet’s Watch Out box after question 3 says the same thing.
Day 1 · Guided practice: Aim the loops at a region
In the IDE, students paste RowAndColumn into a scratch class and make three changes, running after each: total row 2 instead of row 1 (29); average quiz 0 instead of quiz 2 (8.0); total quizzes 0 and 1 for students 1 and 2 only, by changing where both loops start (6 + 9 + 10 + 7 = 32). Partners check each other’s loop headers against the slide 5 table before running.
Teacher note
If computers are not available, do the same three changes on mini whiteboards: students write only the loop headers and the element expression, and you check them against the slide 5 table.
Day 1 · Independent practice: Independent practice
Hand out the puzzle worksheet. Students do questions 1 and 2 alone. Question 1 (you’re the JVM) walks down column 1: 4 + 8 + 9 + 2 = 23 over 4 rows, so the output is 5 5.75, choice A; D is the student who divides by the 3 columns. Question 2 (pencil check) has six loop headers; check the diagonal row (3 2 4) and the last row (0 4 2, which reads each right-hand neighbor and previews Day 3).
Day 1 · Closure: Closure
Ask: “A loop walks down column 3. What is its bound?” (grid.length.) “A loop walks across row 3?” (grid[3].length.) Students write both on an exit slip or in their notes.
Day 2 · Warm-up: The warmest winter reading
Put the MaxStartZero array on the board without the code: every reading is below 0. Ask: “If highest starts at 0, what does the program print?” Run it: Highest: 0, a value that is not in the array. Leave the question open; slide 9 answers it.
Day 2 · Direct instruction: The best so far, and where it was
- The pattern (4.13.A.1, slides 8–9). Start the best-so-far at a real element of the region (
scores[0][0]), compare every element, and replace it when a bigger one appears. To remember where, saverandcin the sameif, at the same moment. Trace slide 9 with the class: 340 is replaced by 560, then 720, then 810, so it printsBest: 810andRow 2, col 1. - Ties. The test is
>, so a tie keeps the first location in row-major order. Ask what would change with>=(the last tie would win). - Another region and direction. Run
MaxAll(Highest: 66,City 2, day 0), thenMinColumn: the coldest reading in one column starts attemps[0][2], the first element of that column, and flips>to<(Lowest on day 2: 50). - Back to the warm-up. Change
MaxStartZeroto start atwinter[0][0]; it printsHighest: -1.Integer.MIN_VALUEalso works for a maximum.
Misconception: Starting the best-so-far at 0
Students start a maximum or minimum at 0 because totals start at 0. It gives the right answer often enough to survive: a maximum fails only when every value is negative, a minimum only when every value is positive. Start at an element of the region being searched. Worksheet question 9 is this bug in a submarine log.
Misconception: Saving the value but not the location
Students update best inside the if but set bestR and bestC outside it, or not at all, so the location belongs to the last element visited. All three variables change together, in the same if.
Day 2 · Direct instruction: Flags and counters
- Three questions, three starts (slide 10). “Does at least one?” is a
booleanthat startsfalseand switches totrue. “Do all of them?” startstrueand one failure switches it tofalse. “How many?” is anintthat starts at 0 and adds 1. A flag is switched only when one element decides the answer, and never switched back. - Run
AnyEmpty(seats areStrings, so the test usesequals):Any empty seat: true. ThenAllPassed, an “all” question about one column: 9, 8, then 5 fails, so it printsEveryone passed quiz 3: false. - Where the start goes decides the scope (slides 10–11). Before all the loops: one answer for the whole region. At the top of the outer loop: one answer per row. Slide 11 counts reading days over 30 minutes per week:
2,3,0. Ask the slide’s question: “What prints ifint count = 0;moves above the outer loop?” (2, 5, 5: a running total.)CountPerRowdoes both at once, a count per week and a grand total of 5. - A non-rectangular region. Run
CountDiagonal(X on the diagonal: 2). Then showAntiDiagonalCrash:board.length - iasks for column 3 on the first pass. The other diagonal isboard[i][board.length - 1 - i];AntiDiagonalFixedprintsX on the other diagonal: 2.
Misconception: An else that switches the flag back
Students write if (found) { flag = true; } else { flag = false; }, which makes the flag describe only the last element checked. Once a flag is switched, nothing switches it back. Point at the “Changes when” column on slide 10: there is only one change.
Misconception: Starting an all flag at false
Students start every flag at false. For an “all” question, nothing can ever make it true. Worksheet question 7 is exactly this, and the fix is one token on line 2. Say the start as a sentence: “All are fine until one is not.”
Day 2 · Guided practice: Shut or open? and the flag reset
- Pause and try (slide 12). Students write the one line of output and say which question each flag answers. Answer:
true true. Column 1 holds 0 and 0, so nothing switchescolShut; row 1 holds 0, 0, 1, and the 1 switchesrowOpentotrue.colShutis an “all” question (are all shut?);rowOpenis an “any” question. - Watch out (slide 13). Ask for a prediction first. Row 0 has an open locker, so
anyOpenbecomestrue, but the reset at the top of the outer loop wipes it out for row 1, which has nothing open. It printsAny open: false. RunFlagPerRowfor the same bug with theater seats. Contrast with slide 11, where the reset is correct because each row gets its own answer, used before the next row starts.
Misconception: Resetting the whole-array flag in the outer loop
Students copy the per-row counter pattern and put flag = false; at the top of the outer loop. The final value then describes only the last row. Ask: “One answer for the whole array, or one per row?” One answer means the start goes once, before both loops.
Day 2 · Independent practice: Independent practice
Students do worksheet question 7 (one-token fix) alone: line 2, false becomes true. Check that no one changes the false on line 5; with no 0 in the array that line never runs. Questions 6 (match-up) and 9 (two truths and a lie) are homework.
Day 2 · Closure: Closure
Ask: “You want the number of rainy days in each week. Where does int count = 0; go, and where does the println go?” (Both inside the outer loop: the start at the top, the print at the bottom, after the inner loop.)
Day 3 · Warm-up: Question 6, versions 1 and 2
Students compare their homework answers for worksheet question 6 with a partner, then you confirm versions 1 and 2: version 1 (start at A, print at D) counts the whole grid once, 3; version 2 (start at B, print at C) gives one count per row, 1 2 0. Take one question about versions 3 and 4 if there is time: version 3 never resets, so it prints a running total (1 3 3); version 4 does not compile, because count declared inside the outer loop does not exist at spot D (scope, Topic 3.8).
Day 3 · Direct instruction: Neighbor pairs stop one early
- Consecutive pairs (4.13.A.1, slides 14–15). In a row, the neighbor of
grid[r][c]isgrid[r][c + 1]; in a column,grid[r + 1][c]. Because each pair reaches one step ahead, the loop stops one early: 4 rows have only 3 neighbor pairs. Trace slide 15: column 0 reads 61, 64, 59, 66, and only 64 to 59 is a drop, so it printsDrops: 1. - Run
StepIncreases, which prints each pair it compares, so students can see four pairs for five days (Increases: 2; the last pair is equal, and6000 > 6000is false). ThenColumnMatchesturns the pairs vertical:Matching pairs in column 1: 2. - One too far. Show
PairsTooFarand ask what happens on the last pass. The four pairs print, thenc = 4asks forsteps[0][5]and the program throwsArrayIndexOutOfBoundsExceptionbeforeIncreases:prints. - Only the index with
+ 1loses one. If the code comparesgrid[r][c]withgrid[r + 1][c]for every column, only the row loop stops early; the column loop still covers every column.
Misconception: Visiting every element when comparing neighbors
Students copy the usual traversal header and leave the bound at the full length. The last element has no neighbor, so the code reaches past the end. Have students count the pairs before writing the loop: a line of n elements has n - 1 pairs.
Day 3 · Direct instruction: Duplicates in a row, a column, or the whole array
- Every later element (4.13.A.1, slide 16). Fix the row, loop
iover its positions, and loopjfromi + 1. Row 0 is 7, 3, 9, 3; the pairs checked are (0,1), (0,2), (0,3), (1,2), (1,3), (2,3), and positions 1 and 3 match, so it printsRow 0 repeats: true. Starting ati + 1skips comparing an element with itself and skips pairs already checked. - Run
RowDuplicates(Row 0 has a duplicate: true) and ask which row of the bingo card has none (row 1). - The whole array. Show
WholeDuplicates: copy every element into a 1D array in row-major order, then run the 1D check. It printsAny duplicate: truebecause 17 appears in both rows, even though neither row repeats on its own. The region you check changes the answer. - Starting
jat 0. RunDuplicateSelf: row 1 has no repeats, but it printstrue, because the first comparison is an element with itself.DuplicateSelfFixedprintsfalse.
Misconception: Comparing each element with every element
Starting j at 0 feels thorough, but it compares each element with itself, so every row “has a duplicate.” The face-off in worksheet question 8 argues this exact point. j starts at i + 1.
Day 3 · Guided practice: Count before you code
Slide 17: one row has 6 elements. Students write two numbers on mini whiteboards: how many neighbor pairs (5) and how many comparisons the duplicate check makes (5 + 4 + 3 + 2 + 1 = 15). Ask a student to explain the 15: i = 0 compares with 5 later positions, i = 1 with 4, and so on. Students who want to check can run a loop that counts its passes in the IDE.
Day 3 · Independent practice: Independent practice
Students do worksheet questions 3 (you’re the compiler) and 8 (face-off) alone. In question 3, snippet 1 is Day 1’s column bound bug (prints 7 and 3, then crashes), snippet 2 is a neighbor-pair loop that stops correctly (7, then -6), snippet 3 does not compile because an array’s length has no parentheses, and snippet 4 walks a diagonal of a 2 × 3 array (prints 4 and 9, then crashes). Ask why snippets 1 and 4 compile: the compiler cannot know how big g is.
Day 3 · Closure: Closure
Ask: “A neighbor-pairs loop and a duplicate check both compare two elements. What is the difference?” (Pairs compare each element with the next one; the duplicate check compares it with every later one.)
Day 4 · Warm-up: The worksheet’s Think First
Read the Think First box before worksheet question 5: a column of blocks drops down one row. Which value gets overwritten first, the top one or the bottom one? Students guess in the margin and keep the guess; question 5 settles it later today.
Day 4 · Direct instruction: Shift and rotate
- Two words (4.13.A.1, slides 18–19). Both move every element one spot. A shift loses the element pushed off the end and fills the open spot (often with 0). A rotate saves it first and puts it in the open spot. Point to the slide’s table:
1 2 3 4shifted left is2 3 4 0, rotated left is2 3 4 1. - Three steps (slide 19). Save the element that falls off (rotate); copy, starting at the end the elements move toward; fill the open spot. Trace slide 19’s row 0: 3 8 1 6 4 becomes 8 1 6 4, then the saved 3 goes last, so it prints
8 1 6 4 3. RunRotateRowLeft(ALE!S) for a row of strings. - A column moving down. Run
ShiftColumnDown: the values arrive from above, so the copying starts at the bottom and works up; the top becomes 0 and the bottom 9 is lost. - Wrong direction. Show
RotateRightWrongand ask for a prediction. It moves right but copies left to right, so the first letter is copied over every other one before they are read:!SSSS. RunRotateRightFixed(!SALE) with the loop running from the right end.
Misconception: Copying in the same direction no matter which way the elements move
Students learn left-to-right copying for a left rotate and use it for every move. When elements move right (or down), that order overwrites each value before it is read and smears one value across the line. Ask: “Which end are the elements moving toward?” Start copying at that end. The worksheet’s Think First and question 5’s decoy tile test this.
Misconception: Rotating without saving the end element
Students write the copy loop and then put the “first” element in the open spot, reading it after it has already been overwritten. The result is a shift with a duplicate. Save the element that falls off before the copy loop.
Day 4 · Direct instruction: Reverse a row or column
- Swap the first half (4.13.A.1, slide 20). The partner of position
rin a line ofnisn - 1 - r. Each swap usestemp(Topic 4.5). Column 1 is 9, 8, 7, 6; withn = 4the loop runs forr = 0andr = 1, so the output column reads 6, 7, 8, 9. - Run
ReverseRow(5 7 2 9 4): with an odd length,len / 2rounds down and the middle element stays where it is. RunReverseColumnfor an even-length column. - All the way across. Run
ReverseTwice: it prints the original row, because every pair is swapped twice and two swaps cancel out. The bound islen / 2. - No temp. Show
NoTempReverseand ask what it prints before running it (5 7 2 7 5). The first assignment erased the value the second one needed. The worksheet’s Fair Question box after question 4 explains whytempis required.
Misconception: Reversing by swapping every position
The loop runs to len because “reverse every element” sounds like “visit every element.” Each pair is swapped back on the second half of the loop. Have students list the swaps for a row of 5 (0 with 4, 1 with 3) and see that the loop needs only 2 passes.
Misconception: A swap without a temporary variable
Students write a = b; b = a; and expect a trade. After the first line, the old a is gone, so both spots end up with b. Save one value first.
Day 4 · Independent practice: Independent practice
Students do worksheet questions 4 (snippet pool: len / 2, len - 1 - c, temp) and 5 (code tiles: save the bottom 6, copy from the bottom up with for (int r = end; r > 0; r--), then put the saved value on top) alone. When they finish question 5, ask them to check their Think First guess: the bottom value is overwritten first, which is why it is saved before the loop. The decoy tile copies top-down and prints a column of 6, 2, 2.
Day 4 · Closure: Closure
Slides 21 and 22. Review the vocabulary cards: point to a card and ask for the line of code that matches it. Then partners use slide 22’s sentence starter with the theater from Day 1: “First I pick __ to visit, so my loops __. Then I pick __ to do with each one.” Cold-call two pairs. Question 10 (who am I?) is homework.
Day 4 · Exit ticket: Exit ticket
Give the exit ticket for the last 5 minutes. Score each question separately: question 1 checks a column region with an accumulator, a counter, and an average; question 2 checks rotating a row and the copy direction; question 3 checks choosing a correct “all” flag for one column. Re-teach the weakest one before Topic 4.14.