Skip to content

Course navigation

For teachersTopic 4.5 · Lesson kit

Implementing Array Algorithms

  • 4 class periods
  • 45 minutes each
  • Objective 4.5.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.5.A
Essential knowledge
4.5.A.1
Materials
Projector and the Array Workshop slide deckWhiteboard and markersMini whiteboards or scrap paper (trace tables)Four chairs at the front of the room (Day 4 warm-up)IDE on every computerPrinted Array Workshop puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Independent practice
  • Closure
  1. 0:00–0:066 minWarm-upone array, many questions (slide 2)
  2. 0:06–0:2014 minDirect instructiongoals, sum, and average (slides 3–5 and 7)
  3. 0:20–0:3212 minDirect instructionminimum, maximum, and the best index (slide 6)
  4. 0:32–0:4210 minIndependent practiceworksheet questions 1 and 3
  5. 0:42–0:453 minClosurevalue or index?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upworksheet question 2, first four rows
  2. 0:05–0:1712 minDirect instructioncounters and flags (slides 8–9)
  3. 0:17–0:258 minGuided practicecount the evens or the even positions? (slide 10)
  4. 0:25–0:3510 minDirect instructionat least one and all in a method, with an early return
  5. 0:35–0:427 minIndependent practiceworksheet question 4
  6. 0:42–0:453 minClosurewhich answer can one element prove?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-uphow many times did it get warmer?
  2. 0:05–0:1712 minDirect instructionconsecutive pairs (slides 11–12)
  3. 0:17–0:2912 minDirect instructionduplicates with a nested loop (slide 13)
  4. 0:29–0:356 minGuided practicehow many checks? (slide 14)
  5. 0:35–0:427 minIndependent practiceworksheet questions 7 and 8
  6. 0:42–0:453 minClosureneighbors or every pair?

Day 445 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:044 minWarm-uprotate four chairs
  2. 0:04–0:1713 minDirect instructionshift and rotate (slides 15–17)
  3. 0:17–0:258 minDirect instructionreverse in place (slide 18)
  4. 0:25–0:305 minGuided practicerotate the letters (slide 19)
  5. 0:30–0:377 minIndependent practiceworksheet questions 5 and 6
  6. 0:37–0:403 minClosurewhich algorithm is it? (slides 20–21)
  7. 0:40–0:455 minExit ticket

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, and QuizTracker.java (every algorithm in one program) if time allows.
  • Printed only (exit ticket): ExitLowCount, ExitRotate, and ExitHasDuplicate.

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

  1. 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.
  2. 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 for loop 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.
  3. The count is length. The number of elements comes from the array, so scores.length is the divisor; nothing has to be counted by hand. Run TotalSales (91, then 18.2).
  4. An average that lost its decimals (slide 7). Cover the output column and ask what each line prints: sum / scores.length is int division, so 79; (double) sum / scores.length is 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. Run AverageChoicesArray, which shows all three placements (7, 7.0, 7.5) on another array.
  5. Start at index 0. Run SumSkipsFirst and ask why the total is 79 instead of 91. The loop starts at i = 1, so the first element is never added, and Java gives no error. AboveAverage is 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

  1. 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. Run WarmestDay (70). Ask: “Does it matter if the loop starts at 0 instead of 1?” Run WarmestStartIndexZero: same answer, because comparing temps[0] with itself changes nothing. Starting at 1 just skips a wasted check.
  2. 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.
  3. 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: best moves to 1 when 95 beats 72 and stays there. The output is 1, then 95. A minimum is the same loop with <; run CheapestIndex (index 1, price 35). Ask why it is not index 3, which is also 35: 35 < 35 is false, so a tie does not move the best.
  4. Element or index? Run MaxIndexMixup without saying what is wrong. It prints 4 and 66, but the warmest day is index 3. Ask students to find the bug in pairs. The condition compares temps[i] with maxIndex, a temperature with a position; every temperature beats every index here, so the best moves on every pass. MaxIndexFixed compares with temps[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

  1. Goals (slide 3, goal 2; slide 8 opens Part 2). A counter is an accumulator that adds 1 only when an if finds the property. Run PassingCount (4 of the 6 scores are 65 or more).
  2. Where the counter lives. Show CountInsideLoop.java and ask whether it compiles. It does not: shutouts is declared inside the loop, so the println after the loop cannot see it (cannot find symbol). Even if it could, it would restart at 0 on every pass. CountInsideLoopFixed.java declares it before the loop.
  3. At least one and all (slide 9). Read the left side first: high counts the scores of 90 or more and prints 2. Then the right side: two flags, opposite starts. “At least one” starts false and one failing score flips it to true; “all” starts true and one failing score flips it to false. Ask before revealing: with {72, 95, 88, 62, 93}, anyFail is true and allPass is false, both because of the 62. Run AnyOverdrawn for a second example.
  4. 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.

  1. At least one. Show AnyLongWord.java and run it. The println inside the loop shows how many words each call checks: for a limit of 5, it stops at “giraffe” and returns true; for a limit of 8, it checks all four words and only then returns false. A true can come from inside the loop; a false only after the loop has seen everything.
  2. All. AllPassing.java is the mirror image: one failing score returns false at once, and return true waits until after the loop. Ask what the empty array noScores returns and why: true, because no element fails.
  3. The tempting bug. Show AllPassingBug.java, which returns in both branches. Ask students to trace teamB. The first score, 88, passes, so the else returns true and the method never sees the 50. Then ask: “If the loop always returns, why does the method still need return true after it?” Run AllPassingNoFinalReturn.java: the compiler reports missing 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

  1. Neighbors (4.5.A.1, slides 11–12). A pair is temps[i] and temps[i + 1]. An array of length n has n − 1 neighbor pairs, so the loop stops at i < temps.length - 1. Walk the up/down arrows on slide 12; the output is 3. Run StepIncreases (3).
  2. One pair too far. Show PairsOutOfBounds.java, which uses the ordinary i < steps.length, and ask students to predict before you run it. It crashes with ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 and prints nothing. On the last pass i is 4, and i + 1 is 5. Rule: whenever the body uses i + 1, stop one index earlier.
  3. Other neighbor jobs. RepeatPairs counts rolls that match the roll after them (3). InOrderCheck.java combines pairs with “all”: it looks back with values[i - 1], so its loop starts at 1, and it returns false at the first pair that goes down. CountPeaks checks both neighbors, so it runs from 1 to length - 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

  1. 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 at j = 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 is true, from pair (1,3).
  2. Run TicketDuplicates (prints Match at 1 and 3, then true) and NoDuplicates, which also counts its comparisons: false, and 6 comparisons for 4 elements.
  3. Why neighbors are not enough. Run NeighborsMissDuplicate: {4, 1, 4} prints false, because the two 4s are not next to each other. Pairs answer questions about order; duplicates need every pair.
  4. The inner bound. Run DuplicateBoundBug: {6, 2, 6} prints false, because j < ids.length - 1 never reaches the last element. The neighbor-pair bound does not belong here; DuplicateBoundFixed uses j < 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

  1. Shift left (4.5.A.1, slide 15). Each element copies the value to its right, front to back: line[i] = line[i + 1] for i < line.length - 1. The last spot keeps its old value unless the code fills it. Run ShiftLeft, which puts a 0 there: 20 30 40 50 0.
  2. Shift right needs the opposite direction. Run ShiftRightForwardBug first and ask why it prints 0 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. ShiftRightFixed loops from the back toward the front and prints 0 10 20 30 40. Rule: loop in the direction opposite to the way the elements travel.
  3. 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); place q[0] = last (12 3 6 9). Connect each step to the chair warm-up. Run RotateRight (50 10 20 30 40), then RotateLeft (6 9 12 3), which saves the first element and shifts forward.
  4. 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, so q[q.length - 1] holds 9 by the time it is copied. RotateLeftNoSave is 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

  1. Swap the ends, stop halfway (4.5.A.1, slide 18). Swap c[0] with c[4], then c[1] with c[3]; the middle element stays. The mirror of index i is c.length - 1 - i. Fill in the slide’s i column: with length 5, c.length / 2 is 2, so the loop runs for i = 0 and 1. The output is blue teal gold tan red. Run ReverseInPlace (Eli Dee Cal Ben Ava).
  2. The swap needs a temp. Run SwapNoTemp and ask why it prints 4 3 3 4: after nums[i] = nums[mirror], the old nums[i] is gone, so the second copy writes back the value it just copied. SwapNoTempFixed saves it in temp first and prints 4 3 2 1.
  3. 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.
  4. Another way. ReverseCopy fills 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.

Exit ticket

Question 1 · Multiple choice

What does this code print?

int[] pts = {14, 9, 21, 9, 17};
int low = 0;
for (int i = 1; i < pts.length; i++)
{
    if (pts[i] < pts[low])
    {
        low = i;
    }
}
int big = 0;
for (int p : pts)
{
    if (p > 15)
    {
        big++;
    }
}
System.out.println(low + " " + pts[low] + " " + big);
  1. 3 9 2
  2. 9 9 2
  3. 1 9 2
  4. 1 9 38
Check your reasoning

C. low holds the index of the smallest element so far. It moves to 1 when 9 < 14. At index 3, 9 < 9 is false, so the tie does not move it, and low ends at 1; pts[low] is the value there, 9. The second loop counts the elements greater than 15: 21 and 17, so big is 2.

A moves low on the tie, which would need <=. B prints the smallest value where the index belongs: low is an index, and pts[low] is the value. D adds the values greater than 15 (21 + 17) instead of counting them, but big++ adds 1 each time.

Question 2 · Multiple choice

What does this code print?

int[] a = {5, 10, 15, 20};
int last = a[a.length - 1];
for (int i = a.length - 1; i > 0; i--)
{
    a[i] = a[i - 1];
}
a[0] = last;
for (int value : a)
{
    System.out.print(value + " ");
}
System.out.println();
  1. 10 15 20 5
  2. 20 5 10 15
  3. 15 5 10 15
  4. 20 5 5 5
Check your reasoning

B. The code rotates right by one. It saves the last element (20), copies each element one spot to the right from the back toward the front (5 5 10 15), then puts the saved 20 in index 0. A is a rotation to the left. C is what happens without the saved copy: after the shift, a[a.length - 1] holds 15, not 20. D is a shift right with a forward loop, which copies the 5 into every spot; this loop runs backward, so each value is copied before it is overwritten.

Question 3 · Multiple choice

ids is an int array. Which code segment sets hasDup to true if any value appears in ids more than once, and to false otherwise, for any length of array?

  1. boolean hasDup = false; for (int i = 0; i < ids.length; i++) { for (int j = 0; j < ids.length; j++) { if (ids[i] == ids[j]) { hasDup = true; } } }
  2. boolean hasDup = false; for (int i = 0; i < ids.length - 1; i++) { if (ids[i] == ids[i + 1]) { hasDup = true; } }
  3. boolean hasDup = false; for (int i = 0; i < ids.length; i++) { for (int j = i + 1; j < ids.length; j++) { if (ids[i] == ids[j]) { hasDup = true; } else { hasDup = false; } } }
  4. boolean hasDup = false; for (int i = 0; i < ids.length; i++) { for (int j = i + 1; j < ids.length; j++) { if (ids[i] == ids[j]) { hasDup = true; } } }
Check your reasoning

D. The outer loop picks each element; the inner loop compares it with every later element, starting at j = i + 1, so no element is compared with itself and no pair is compared twice. The flag starts false before both loops and is set to true only when a match is found. Laid out with a sample array (the two 8s, at indices 1 and 3):

int[] ids = {31, 8, 15, 8, 2};
boolean hasDup = false;
for (int i = 0; i < ids.length; i++)
{
    for (int j = i + 1; j < ids.length; j++)
    {
        if (ids[i] == ids[j])
        {
            hasDup = true;
        }
    }
}
System.out.println(hasDup);

It prints true.

A starts j at 0, so when j equals i it compares an element with itself and reports a duplicate for every array that has any elements. B checks only neighbors, so it misses repeats that are not side by side: for {31, 8, 15, 8, 2} it reports false. C sets the flag back to false on every mismatch, so only the last comparison counts: for the same array, the last pair (8 and 2) does not match, and it reports false.