Overview
This topic has one essential knowledge statement (4.5.A.1), and it is a list: the standard algorithms that traverse an array. The four days follow the deck’s four parts. Day 1 is the sum, the average, and the minimum or maximum, including the index where the best value is. Day 2 counts the elements with a property and decides whether at least one or all of them have it, first with a flag and then with an early return in a method. Day 3 visits every pair of neighbors and uses a loop inside a loop to look for a duplicate. Day 4 shifts, rotates, and reverses an array in place.
Much of this is a reunion. Students wrote accumulators, counters, flags, and best-so-far variables over a range of numbers in Topic 2.9, over the characters of a string in Topic 2.10, and nested loops in Topic 2.11. Say so early: the patterns are the same, and what is new is that the values come from an array, so every algorithm has two kinds of number in it, positions (i) and values (nums[i]). Most bugs this week come from mixing them up or from an index that runs off the end (Topic 4.3).
Stay inside the topic boundary: arrays, indexed and enhanced for loops (Topic 4.4), and methods that take an array and return a value (Topics 3.5 and 3.6). No text files (Topic 4.6), ArrayList (Topics 4.8 and 4.9), 2D arrays, searching, or sorting. If a student asks to sort, say that sorting algorithms come later in the unit.
Teacher note
The slides are the Array Workshop deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–7, Day 2 slides 8–10, Day 3 slides 11–14, and Day 4 slides 15–21. The Array Workshop puzzle worksheet (10 questions, about 30 minutes) is split across the four days: questions 1 and 3 in class on Day 1, the first four rows of question 2 as the Day 2 warm-up, question 4 in class on Day 2, questions 7 and 8 in class on Day 3 with the rest of question 2 as homework, questions 5 and 6 in class on Day 4, and questions 9 and 10 as 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. The other files are full programs. All files are in the topic’s examples/ folder.
- Day 1 demonstrations:
TotalSales,AverageChoicesArray,SumSkipsFirst,AboveAverage,WarmestDay,WarmestStartIndexZero,SmallestStartZeroChoices.java,CheapestIndex,MaxIndexMixup,MaxIndexFixed. - Day 2 demonstrations:
PassingCount,CountInsideLoop.java(compiler error),CountInsideLoopFixed.java,CountEvenBug,CountEvenFixed,AnyOverdrawn,AnyLongWord.java,AllPassing.java,AllPassingBug.java,AllPassingNoFinalReturn.java(compiler error). - Day 3 demonstrations:
StepIncreases,PairsOutOfBounds.java(run-time error),RepeatPairs,CountPeaks,InOrderCheck.java,TicketDuplicates,NoDuplicates,DuplicateSelfCompare,DuplicateBoundBug,DuplicateBoundFixed,NeighborsMissDuplicate. - Day 4 demonstrations:
ShiftLeft,ShiftRightForwardBug,ShiftRightFixed,RotateLeft,RotateRight,RotateLeftNoSave,ReverseInPlace,ReverseTwice,SwapNoTemp,SwapNoTempFixed,ReverseCopy, andQuizTracker.java(every algorithm in one program) if time allows. - Printed only (exit ticket):
ExitLowCount,ExitRotate, andExitHasDuplicate.
Day 1 · Warm-up: One array, many questions
Show slide 2: int[] scores = {72, 95, 88, 62, 93};. Pairs list at least four questions a teacher could answer about the array with one loop, and for each one, what they would keep track of and whether they could stop before the end. Collect answers on the board in two columns, “keep track of” and “stop early?”. Expect: the total and the average (a sum), the highest and lowest score and who got it (a best so far), how many scored 90 or more (a count), whether anyone failed or everyone passed (a flag), whether two scores are the same, and how often a score beat the one before it.
Leave the list up. Tell students it is this week’s plan: every question on it is one of the standard algorithms, and by Day 4 they will have written each one.
Day 1 · Direct instruction: Goals, sum, and average
- Goals (slide 3). Read the five goals; today is goal 1. Point back to the warm-up list and tick the questions goal 1 covers.
- The accumulator (4.5.A.1, slides 4–5). Same three parts as Topic 2.9: start it once, before the loop; add each element inside the loop; use it after the loop. An enhanced
forloop is the natural fit, because a sum needs every value and no index. Ask students to predict slide 5’s output before you reveal it: the sum is 317 and the average is 79.25. - The count is
length. The number of elements comes from the array, soscores.lengthis the divisor; nothing has to be counted by hand. RunTotalSales(91, then 18.2). - An average that lost its decimals (slide 7). Cover the output column and ask what each line prints:
sum / scores.lengthis int division, so 79;(double) sum / scores.lengthis 79.25. Then read the slide’s “also too late” line:double avg = sum / scores.length;stores 79.0, because the division happens before the value is widened. RunAverageChoicesArray, which shows all three placements (7, 7.0, 7.5) on another array. - Start at index 0. Run
SumSkipsFirstand ask why the total is 79 instead of 91. The loop starts ati = 1, so the first element is never added, and Java gives no error.AboveAverageis a good extension for a fast class: one loop finds the average, a second counts the temperatures above it (63.8, then 3).
Misconception: Starting the loop at index 1
Students who count from 1 start the index there. The code compiles and runs, and the first element is quietly left out (SumSkipsFirst prints 79, not 91). A traversal of every element starts at int i = 0, or uses an enhanced for loop, which cannot skip anything.
Misconception: Casting after the division
(double) (sum / scores.length) and double avg = sum / scores.length; both cast too late: the int division has already dropped the decimals. Cast one operand before dividing, as on slide 7: (double) sum / scores.length.
Day 1 · Direct instruction: Minimum, maximum, and the best index
- The best value (4.5.A.1). Start the best so far at the first element,
temps[0], then compare each later element and replace the best when it wins. RunWarmestDay(70). Ask: “Does it matter if the loop starts at 0 instead of 1?” RunWarmestStartIndexZero: same answer, because comparingtemps[0]with itself changes nothing. Starting at 1 just skips a wasted check. - Why not start at 0? Run
SmallestStartZeroChoices.java. Starting a minimum at 0 works when the data has a negative value, but for{3, 8, 5}it returns 0, a value that is not in the array. An element of the array is always a safe start. - Keep the index of the best (slide 6). The best index tells you where the best element is and what it is. Fill in the trace table on slide 6 with the class one row at a time:
bestmoves to 1 when 95 beats 72 and stays there. The output is1, then95. A minimum is the same loop with<; runCheapestIndex(index 1, price 35). Ask why it is not index 3, which is also 35:35 < 35is false, so a tie does not move the best. - Element or index? Run
MaxIndexMixupwithout saying what is wrong. It prints4and66, but the warmest day is index 3. Ask students to find the bug in pairs. The condition comparestemps[i]withmaxIndex, a temperature with a position; every temperature beats every index here, so the best moves on every pass.MaxIndexFixedcompares withtemps[maxIndex]and prints 3 and 70.
Misconception: Comparing an element with an index
When a loop keeps a best index, students write temps[i] > maxIndex instead of temps[i] > temps[maxIndex]. Both are int, so it compiles. Have students say each variable’s role aloud: i and maxIndex are positions; temps[i] and temps[maxIndex] are temperatures. Only like compares with like.
Misconception: Starting the best so far at 0
Students carry over “start at 0” from accumulators. A maximum started at 0 never changes when every value is negative, and a minimum started at 0 never changes when every value is positive; either way the answer is a value that is not in the array. Start at the first element (worksheet question 1 is exactly this bug).
Day 1 · Independent practice: Independent practice
Students do worksheet questions 1 and 3 alone, then compare with a partner. Question 1 is the maximum started at 0 on four negative temperatures: it prints 0 (choice A), which is not in the array. Question 3 keeps the index of the best lap count; the tie at index 3 does not move best, so it prints 1 52 (choice A). Choice B is what >= would print. Read question 1’s “Fair question” box aloud when you go over it.
Day 1 · Closure: Closure
Write best and scores[best] on the board. Ask: “Which is a position and which is a score? Which one does the if compare?” Students answer on a sticky note: best is a position, scores[best] is the value there, and the if compares scores[i] with scores[best], two values.
Day 2 · Warm-up: Question 2, first four rows
Students fill in the first four rows of worksheet question 2 for int[] v = {3, 8, 8, 1, 6};: the sum (26), sum / v.length (5), (double) sum / v.length (5.2), and the index of the minimum (3). Go over the second and third rows together; the contrast is yesterday’s slide 7 again. Students keep the worksheet; the other three rows come after Day 3.
Day 2 · Direct instruction: Counters and flags
- Goals (slide 3, goal 2; slide 8 opens Part 2). A counter is an accumulator that adds 1 only when an
iffinds the property. RunPassingCount(4 of the 6 scores are 65 or more). - Where the counter lives. Show
CountInsideLoop.javaand ask whether it compiles. It does not:shutoutsis declared inside the loop, so theprintlnafter the loop cannot see it (cannot find symbol). Even if it could, it would restart at 0 on every pass.CountInsideLoopFixed.javadeclares it before the loop. - At least one and all (slide 9). Read the left side first:
highcounts the scores of 90 or more and prints 2. Then the right side: two flags, opposite starts. “At least one” startsfalseand one failing score flips it totrue; “all” startstrueand one failing score flips it tofalse. Ask before revealing: with{72, 95, 88, 62, 93},anyFailistrueandallPassisfalse, both because of the 62. RunAnyOverdrawnfor a second example. - Say the rule. Write it on the board: “at least one” is proved by one element that has the property; “all” is disproved by one element that does not. Neither flag is ever switched back inside the loop.
Misconception: Declaring the counter inside the loop
A counter declared in the loop body is a new variable on every pass, and it does not exist after the loop, so the program does not compile (CountInsideLoop.java). Declare and start every accumulator, counter, and flag once, before the loop.
Day 2 · Guided practice: The evens or the even positions?
Show slide 10. Both counters compile; students write a and b on mini whiteboards before you reveal. a tests i % 2 == 0, the index, so it counts positions 0, 2, and 4: a is 3. b tests nums[i] % 2 == 0, the element, so it counts 8 and 6: b is 2. Run CountEvenBug (3) and CountEvenFixed (2) to confirm with the guide’s version of the same mistake.
Misconception: Testing the index instead of the element
In an indexed loop, i and nums[i] are both int, so testing the wrong one compiles and gives a believable number. Teach the habit from worksheet question 9’s “Watch out” box: read i aloud as “position” and nums[i] as “the value there”, and ask of every condition which one the question is about.
Day 2 · Direct instruction: At least one and all in a method
A method can stop as soon as it knows the answer.
- At least one. Show
AnyLongWord.javaand run it. Theprintlninside the loop shows how many words each call checks: for a limit of 5, it stops at “giraffe” and returnstrue; for a limit of 8, it checks all four words and only then returnsfalse. Atruecan come from inside the loop; afalseonly after the loop has seen everything. - All.
AllPassing.javais the mirror image: one failing score returnsfalseat once, andreturn truewaits until after the loop. Ask what the empty arraynoScoresreturns and why:true, because no element fails. - The tempting bug. Show
AllPassingBug.java, which returns in both branches. Ask students to traceteamB. The first score, 88, passes, so theelsereturnstrueand the method never sees the 50. Then ask: “If the loop always returns, why does the method still needreturn trueafter it?” RunAllPassingNoFinalReturn.java: the compiler reportsmissing return statement, because it knows the loop might not run at all.
Misconception: Returning from both branches inside the loop
Students write if (fails) return false; else return true; inside the loop, so the method decides after one element. Only the answer that one element can prove may return early; the other answer goes after the loop. Delete the else.
Day 2 · Independent practice: Independent practice
Students do worksheet question 4 (snippet pool) alone: allPositive fills its holes with n <= 0, false, and true. When you go over it, ask why n < 0 is wrong (0 is not positive, so {2, 0, 5} would wrongly give true) and why nums[n] is wrong (it uses a value as an index).
Day 2 · Closure: Closure
Ask: “For ‘all scores pass’, which answer can one score prove: true or false?” (False.) “For ‘any score is perfect’?” (True.) Students write which one goes inside the loop and which one goes after it.
Day 3 · Warm-up: How many times did it get warmer?
Write slide 12’s temperatures on the board, 60 62 61 65 67, without the code. Students count how many times the temperature went up from one day to the next and how many comparisons they made. The answers are 3 rises and 4 comparisons. Ask: “Why 4 comparisons for 5 days?” The answer is today’s first idea.
Day 3 · Direct instruction: Consecutive pairs
- Neighbors (4.5.A.1, slides 11–12). A pair is
temps[i]andtemps[i + 1]. An array of length n has n − 1 neighbor pairs, so the loop stops ati < temps.length - 1. Walk the up/down arrows on slide 12; the output is 3. RunStepIncreases(3). - One pair too far. Show
PairsOutOfBounds.java, which uses the ordinaryi < steps.length, and ask students to predict before you run it. It crashes withArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5and prints nothing. On the last passiis 4, andi + 1is 5. Rule: whenever the body usesi + 1, stop one index earlier. - Other neighbor jobs.
RepeatPairscounts rolls that match the roll after them (3).InOrderCheck.javacombines pairs with “all”: it looks back withvalues[i - 1], so its loop starts at 1, and it returnsfalseat the first pair that goes down.CountPeakschecks both neighbors, so it runs from 1 tolength - 2; use it only if the class is moving quickly.
Misconception: Running one pair too far
Students reuse the traversal header i < a.length with a body that reads a[i + 1], and the last pass throws ArrayIndexOutOfBoundsException. Have them check the last pass every time: plug in the last value of i and ask whether every index in the body exists. For a look-back with a[i - 1], check the first pass instead (worksheet question 7).
Day 3 · Direct instruction: Duplicates with a nested loop
- Every pair, once (4.5.A.1, slide 13). To find a repeat anywhere, every element must be compared with every other element, not just its neighbor. The outer loop picks
names[i]; the inner loop compares it with every later element, starting atj = i + 1. Fill in the slide’s table of pairs with the class: (0,1) (0,2) (0,3), then (1,2) (1,3), then (2,3). Strings are compared with.equals, not==. The output istrue, from pair (1,3). - Run
TicketDuplicates(printsMatch at 1 and 3, thentrue) andNoDuplicates, which also counts its comparisons:false, and 6 comparisons for 4 elements. - Why neighbors are not enough. Run
NeighborsMissDuplicate:{4, 1, 4}printsfalse, because the two 4s are not next to each other. Pairs answer questions about order; duplicates need every pair. - The inner bound. Run
DuplicateBoundBug:{6, 2, 6}printsfalse, becausej < ids.length - 1never reaches the last element. The neighbor-pair bound does not belong here;DuplicateBoundFixedusesj < ids.length.
Misconception: Starting the inner loop at 0
Students think the inner loop should cover the whole array, so they start j at 0. Then i and j are equal once per pass, an element is compared with itself, and every array “has a duplicate” (DuplicateSelfCompare prints true for {5, 9, 2, 7}). Starting at j = i is the same bug. Start at j = i + 1: no element meets itself, and no pair is checked twice.
Misconception: Checking only neighbors for a duplicate
A neighbor-pair loop finds a repeat only when the two copies sit side by side. NeighborsMissDuplicate misses the 4s in {4, 1, 4}. A duplicate check needs the nested loop.
Day 3 · Guided practice: How many checks?
Show slide 14. Pairs count the comparisons for a 5-element array. Loop A makes 4 (one per neighbor pair). Loop B makes 4 + 3 + 2 + 1 = 10, one per pair of different indices. For the bonus, if B starts j at 0 it makes 25 comparisons, 5 of them an element against itself, so it always finds a “duplicate”, and every real pair is checked twice.
Day 3 · Independent practice: Independent practice
Students do worksheet questions 7 and 8 alone. Question 7 (one-token fix): the look-back loop crashes on rolls[-1] at i = 0; change the 0 in line 3 to 1, and it prints 3. Question 8 (two truths and a lie): claim 3 is the lie, because starting j at i still compares each element with itself; the fix is i + 1. For homework, students finish worksheet question 2 (the last three rows: 3 elements greater than 5, 2 rising pairs, and true for the two 8s).
Day 3 · Closure: Closure
Ask: “Did any two days have the same temperature?” and “Did the temperature ever stay the same two days in a row?” Students say which question needs every pair (the first: a nested loop) and which needs only neighbors (the second: one loop that stops at length - 1).
Day 4 · Warm-up: Rotate four chairs
Put four students in four chairs at the front, holding cards A, B, C, D. Tell them: “Everyone move one seat to the right, and whoever falls off the end goes to seat 0. One person moves at a time, and nobody may sit in an occupied chair until its owner has left.” Let the class direct the moves. They will discover that D has to stand up first (be saved), then C moves into D’s seat, B into C’s, A into B’s, and finally D sits in seat 0. Write the order of moves on the board; it is slide 16’s algorithm.
Teacher note
If moving students around does not suit your room, do the same thing with four sticky notes on the board, and allow only one free spot to hold a note while it moves.
Day 4 · Direct instruction: Shift and rotate
- Shift left (4.5.A.1, slide 15). Each element copies the value to its right, front to back:
line[i] = line[i + 1]fori < line.length - 1. The last spot keeps its old value unless the code fills it. RunShiftLeft, which puts a 0 there:20 30 40 50 0. - Shift right needs the opposite direction. Run
ShiftRightForwardBugfirst and ask why it prints0 10 10 10 10: the first pass copies 10 over the 20 before the 20 has moved, and that 10 is copied again on every pass.ShiftRightFixedloops from the back toward the front and prints0 10 20 30 40. Rule: loop in the direction opposite to the way the elements travel. - Rotate right (slide 16): save, shift, place. Walk the three steps on the slide: save
last = 12; shift back to front (3 3 6 9); placeq[0] = last(12 3 6 9). Connect each step to the chair warm-up. RunRotateRight(50 10 20 30 40), thenRotateLeft(6 9 12 3), which saves the first element and shifts forward. - Forgetting to save (slide 17). Ask what the slide’s code prints before revealing it:
9 3 6 9. The 12 was overwritten on the first pass, soq[q.length - 1]holds 9 by the time it is copied.RotateLeftNoSaveis the same mistake rotating left (20 30 40 50 20).
Misconception: Shifting right while looping forward
Students reuse the forward loop from shift left and change only the copy. Each copy overwrites the value the next pass needs, so one value spreads across the array (ShiftRightForwardBug, and loop 2 in worksheet question 6). Ask, “Has this value been moved yet?” before every overwrite; moving right means starting at the back.
Misconception: Forgetting to save the element that falls off
In a rotation, one element is overwritten by the shift. If it is not saved in a variable before the loop, it is gone (slide 17). Save first, shift, then place.
Day 4 · Direct instruction: Reverse in place
- Swap the ends, stop halfway (4.5.A.1, slide 18). Swap
c[0]withc[4], thenc[1]withc[3]; the middle element stays. The mirror of indexiisc.length - 1 - i. Fill in the slide’sicolumn: with length 5,c.length / 2is 2, so the loop runs fori= 0 and 1. The output isblue teal gold tan red. RunReverseInPlace(Eli Dee Cal Ben Ava). - The swap needs a temp. Run
SwapNoTempand ask why it prints4 3 3 4: afternums[i] = nums[mirror], the oldnums[i]is gone, so the second copy writes back the value it just copied.SwapNoTempFixedsaves it intempfirst and prints4 3 2 1. - Stop halfway. Ask, “What if the loop runs over every index?” Run
ReverseTwice:1 4 9 16, the original order. The second half of the loop swaps every pair back. This is loop 4 in worksheet question 6. - Another way.
ReverseCopyfills a new array from the back and leaves the original unchanged. Show it only briefly; the in-place swap is the one to practice.
Misconception: Swapping all the way to the end
Students loop i < a.length because that is how every traversal so far has looked. Each pair is swapped twice and the array ends where it started. Reversing stops at i < a.length / 2; for an odd length, the middle element does not move.
Misconception: Swapping without a temporary variable
a[i] = a[j]; a[j] = a[i]; copies one value over the other and then copies it back, so both spots hold the same value (SwapNoTemp). A swap needs three statements and a temp.
Day 4 · Guided practice: Rotate the letters
Show slide 19. Students write what w holds after the code: d a b c. Ask which element had to be saved first: "d", the last one, because the first copy (w[3] = w[2]) overwrites it. Ask a fast pair to say how the code changes to rotate left instead (save w[0], loop forward with w[i] = w[i + 1], place it at the end).
Day 4 · Independent practice: Independent practice
Students do worksheet questions 5 and 6. Question 5 (code tiles) rotates row left: save first, loop from i = 1 with row[i - 1] = row[i], then place first at the end. The decoy header that starts at 0 crashes on row[-1]. Question 6 (match-up) answers are 1–Q, 2–S, 3–P, 4–R; ask a student to explain why loop 4 leaves the array unchanged. Questions 9 (who am I) and 10 (wrap-up reflection) are homework.
Day 4 · Closure: Closure
Show slide 20 and read the six vocabulary words; ask students to match each one to a question from the Day 1 warm-up list still on the board. Then slide 21: partners name the algorithm for each question and what it starts with before the loop. The class average is a sum started at 0, divided by length with a cast. “Did anyone score below 65?” is “at least one”, a flag started at false. “Did two students get the same score?” is a duplicate check, a flag started at false with a nested loop whose inner index starts at i + 1.
Teacher note
If time remains before the exit ticket, run QuizTracker.java: one program with an average, a best index, a count, a
pairs count, a duplicate check, and a reverse, each as its own method. Ask students to name each method’s algorithm
from its loop alone.
Day 4 · Exit ticket: Exit ticket
Give the exit ticket for the last 5 minutes. Score each question separately: question 1 checks the minimum index and a count (Day 1 and Day 2), question 2 a rotation (Day 4), and question 3 the duplicate check (Day 3). Re-teach the weakest one at the start of Topic 4.6, using the matching worksheet question: 3 for the best index, 8 for duplicates, or 6 for shifting and rotating.