Skip to content

Course navigation

For teachersTopic 4.13 · Lesson kit

Implementing 2D Array Algorithms

  • 4 class periods
  • 45 minutes each
  • Objective 4.13.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    4 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
4 class periods of 45 minutes
Learning objectives
4.13.A
Essential knowledge
4.13.A.1
Materials
Projector and the Work the Grid slide deckWhiteboard and markersMini whiteboards or scrap paper (trace tables)IDE on every computer (Days 1 and 3)Printed Work the Grid 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-upquestions about a grid (slide 2)
  2. 0:05–0:1712 minDirect instructionfix one index, loop the other (slides 3–5)
  3. 0:17–0:2710 minDirect instructiona row total, a column average, a column bound bug (slides 6–7)
  4. 0:27–0:358 minGuided practiceaim the loops at a region in the IDE
  5. 0:35–0:427 minIndependent practiceworksheet questions 1 and 2
  6. 0:42–0:453 minClosurewhich length is the bound?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upthe warmest winter reading
  2. 0:05–0:1712 minDirect instructionthe best so far, and where it was (slides 8–9)
  3. 0:17–0:3013 minDirect instructionflags and counters (slides 10–11)
  4. 0:30–0:377 minGuided practiceshut or open? and the flag reset (slides 12–13)
  5. 0:37–0:425 minIndependent practiceworksheet question 7
  6. 0:42–0:453 minClosurewhere does the counter start?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upworksheet question 6, versions 1 and 2
  2. 0:05–0:1712 minDirect instructionneighbor pairs stop one early (slides 14–15)
  3. 0:17–0:2912 minDirect instructionduplicates in a row, a column, or the whole array (slide 16)
  4. 0:29–0:356 minGuided practicecount before you code (slide 17)
  5. 0:35–0:427 minIndependent practiceworksheet questions 3 and 8
  6. 0:42–0:453 minClosurepairs or every later element?

Day 445 minutes

  • Warm-up
  • Direct instruction
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upthe worksheet's Think First
  2. 0:05–0:1712 minDirect instructionshift and rotate (slides 18–19)
  3. 0:17–0:258 minDirect instructionreverse a row or column (slide 20)
  4. 0:25–0:3510 minIndependent practiceworksheet questions 4 and 5
  5. 0:35–0:405 minClosurevocabulary and which elements, then what? (slides 21–22)
  6. 0:40–0:455 minExit ticket

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

  1. 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.
  2. The whole array (4.13.A.1). Run TotalAll: the total starts at 0 before both loops and gains scores[r][c] inside both, so it prints Total: 96. The average divides by the number of elements, grid.length * grid[0].length (12 here), with a cast first: Average: 8.0. Then run TotalEnhanced (Total: 45, Average: 7.5): when positions do not matter, nested enhanced loops from Topic 4.12 do the same job.
  3. The cast (Topic 1.5). Show AverageIntDivision and ask for a prediction before running it. Storing in a double is not enough: 45 / 6 is already 7 before it is stored, so it prints Average: 7.0.
  4. 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 c runs to grid[row].length. One column: the column index stays fixed and r runs to grid.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.
  5. 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

  1. 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 / 3 is 9.0. Run RowAndColumn for the same moves on the quiz array (Student 1 total: 33, Quiz 2 average: 8.0).
  2. Watch out (slide 7). Cover the error box and ask what the program prints. sales[0].length is 4, the number of columns, but the column holds only 3 elements. Passes 0–2 work; r = 3 asks for sales[3][1] and throws ArrayIndexOutOfBoundsException, before the println, so nothing prints. Run ColumnWrongBound for the same crash on the quiz array.
  3. Ask the question that fixes it: “Which index does r stand 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

  1. 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, save r and c in the same if, at the same moment. Trace slide 9 with the class: 340 is replaced by 560, then 720, then 810, so it prints Best: 810 and Row 2, col 1.
  2. 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).
  3. Another region and direction. Run MaxAll (Highest: 66, City 2, day 0), then MinColumn: the coldest reading in one column starts at temps[0][2], the first element of that column, and flips > to < (Lowest on day 2: 50).
  4. Back to the warm-up. Change MaxStartZero to start at winter[0][0]; it prints Highest: -1. Integer.MIN_VALUE also 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

  1. Three questions, three starts (slide 10). “Does at least one?” is a boolean that starts false and switches to true. “Do all of them?” starts true and one failure switches it to false. “How many?” is an int that starts at 0 and adds 1. A flag is switched only when one element decides the answer, and never switched back.
  2. Run AnyEmpty (seats are Strings, so the test uses equals): Any empty seat: true. Then AllPassed, an “all” question about one column: 9, 8, then 5 fails, so it prints Everyone passed quiz 3: false.
  3. 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 if int count = 0; moves above the outer loop?” (2, 5, 5: a running total.) CountPerRow does both at once, a count per week and a grand total of 5.
  4. A non-rectangular region. Run CountDiagonal (X on the diagonal: 2). Then show AntiDiagonalCrash: board.length - i asks for column 3 on the first pass. The other diagonal is board[i][board.length - 1 - i]; AntiDiagonalFixed prints X 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

  1. 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 switches colShut; row 1 holds 0, 0, 1, and the 1 switches rowOpen to true. colShut is an “all” question (are all shut?); rowOpen is an “any” question.
  2. Watch out (slide 13). Ask for a prediction first. Row 0 has an open locker, so anyOpen becomes true, but the reset at the top of the outer loop wipes it out for row 1, which has nothing open. It prints Any open: false. Run FlagPerRow for 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

  1. Consecutive pairs (4.13.A.1, slides 14–15). In a row, the neighbor of grid[r][c] is grid[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 prints Drops: 1.
  2. Run StepIncreases, which prints each pair it compares, so students can see four pairs for five days (Increases: 2; the last pair is equal, and 6000 > 6000 is false). Then ColumnMatches turns the pairs vertical: Matching pairs in column 1: 2.
  3. One too far. Show PairsTooFar and ask what happens on the last pass. The four pairs print, then c = 4 asks for steps[0][5] and the program throws ArrayIndexOutOfBoundsException before Increases: prints.
  4. Only the index with + 1 loses one. If the code compares grid[r][c] with grid[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

  1. Every later element (4.13.A.1, slide 16). Fix the row, loop i over its positions, and loop j from i + 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 prints Row 0 repeats: true. Starting at i + 1 skips comparing an element with itself and skips pairs already checked.
  2. Run RowDuplicates (Row 0 has a duplicate: true) and ask which row of the bingo card has none (row 1).
  3. The whole array. Show WholeDuplicates: copy every element into a 1D array in row-major order, then run the 1D check. It prints Any duplicate: true because 17 appears in both rows, even though neither row repeats on its own. The region you check changes the answer.
  4. Starting j at 0. Run DuplicateSelf: row 1 has no repeats, but it prints true, because the first comparison is an element with itself. DuplicateSelfFixed prints false.

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

  1. 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 4 shifted left is 2 3 4 0, rotated left is 2 3 4 1.
  2. 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. Run RotateRowLeft (ALE!S) for a row of strings.
  3. 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.
  4. Wrong direction. Show RotateRightWrong and 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. Run RotateRightFixed (!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

  1. Swap the first half (4.13.A.1, slide 20). The partner of position r in a line of n is n - 1 - r. Each swap uses temp (Topic 4.5). Column 1 is 9, 8, 7, 6; with n = 4 the loop runs for r = 0 and r = 1, so the output column reads 6, 7, 8, 9.
  2. Run ReverseRow (5 7 2 9 4): with an odd length, len / 2 rounds down and the middle element stays where it is. Run ReverseColumn for an even-length column.
  3. All the way across. Run ReverseTwice: it prints the original row, because every pair is swapped twice and two swaps cancel out. The bound is len / 2.
  4. No temp. Show NoTempReverse and 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 why temp is 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.

Exit ticket

Question 1 · Multiple choice

What does this code print?

int[][] scores = { {7, 3, 9},
                   {4, 8, 2},
                   {6, 5, 1},
                   {9, 2, 6} };
int col = 2;
int total = 0;
int high = 0;
for (int r = 0; r < scores.length; r++)
{
    total += scores[r][col];
    if (scores[r][col] > 5)
    {
        high++;
    }
}
System.out.println(total + " " + high + " " + (double) total / scores.length);
  1. 18 2 4
  2. 18 2 4.0
  3. 18 2 6.0
  4. 18 2 4.5
Check your reasoning

D. col is fixed at 2, so the loop walks down column 2 and visits 9, 2, 1, 6. total is 9 + 2 + 1 + 6 = 18. Two of those values are greater than 5 (9 and 6), so high is 2. The column has one element per row, so the average divides by scores.length, 4; the cast is on total, so it is 18.0 / 4, which is 4.5.

A divides two int values, but the cast makes total a double first, so the result is a double. B casts after dividing, as if the code were (double) (total / scores.length); the cast applies only to total. C divides by scores[0].length, 3, the number of columns, but a column has one element per row, and there are 4 rows.

Question 2 · Multiple choice

What does this code print?

int[][] g = { {1, 2, 3, 4},
              {5, 6, 7, 8} };
int row = 1;
int len = g[row].length;
int last = g[row][len - 1];
for (int c = len - 1; c > 0; c--)
{
    g[row][c] = g[row][c - 1];
}
g[row][0] = last;
for (int value : g[row])
{
    System.out.print(value + " ");
}
System.out.println();
  1. 6 7 8 5
  2. 8 5 6 7
  3. 8 5 5 5
  4. 0 5 6 7
Check your reasoning

B. The code saves the last element of row 1 (8), copies each element from its left-hand neighbor starting at the right end (row 1 becomes 5 5 6 7), and puts the saved 8 in spot 0. That is a rotate right by one spot.

  • A is wrong: that is a rotate left. Each spot here copies from c - 1, the spot to its left, so the values move right.
  • C is wrong: that smear happens when a right move copies left to right, so the 5 is read again after it has already been copied. This loop starts at the right end, so every value is read before it is overwritten.
  • D is wrong: that is a shift right, which fills the open spot with 0. This code saved the 8 and put it back, so nothing is lost.

Question 3 · Multiple choice

temps is a rectangular 2D array of int, and col is a valid column index. Which code sets allOver to true if every element in column col is greater than 50, and to false otherwise?

  1. boolean allOver = false; for (int r = 0; r < temps.length; r++) { if (temps[r][col] > 50) { allOver = true; } }
  2. boolean allOver = true; for (int r = 0; r < temps[0].length; r++) { if (temps[r][col] <= 50) { allOver = false; } }
  3. boolean allOver = true; for (int r = 0; r < temps.length; r++) { if (temps[r][col] <= 50) { allOver = false; } }
  4. boolean allOver = true; for (int r = 0; r < temps.length; r++) { if (temps[r][col] <= 50) { allOver = false; } else { allOver = true; } }
Check your reasoning

C. For an “all” question, the flag starts true (assume yes until one fails). One loop goes over the rows, r from 0 while r < temps.length, because a column has one element per row, and the first value that is not over 50 sets the flag to false. Nothing sets it back. With the sample array below, column 0 holds 55, 52, and 58, so it prints true; with col = 1 it would print false (49 is not over 50).

int[][] temps = { {55, 61, 48},
                  {52, 70, 66},
                  {58, 49, 63} };
int col = 0;
boolean allOver = true;
for (int r = 0; r < temps.length; r++)
{
    if (temps[r][col] <= 50)
    {
        allOver = false;
    }
}
System.out.println(allOver);

A answers “is any element over 50?”: one value over 50 makes it true, so column 1 (61, 70, 49) gives true. B uses temps[0].length, the number of columns, as the bound for a walk down a column; when the grid has more columns than rows, it throws an ArrayIndexOutOfBoundsException, and when it has fewer, it misses rows. D adds an else that sets the flag back to true, so only the last row counts: column 1 ends with 49 and gives false, but a column of 49, 70, 66 would give true.