Skip to content

Course navigation

For teachersTopic 4.16 · Lesson kit

Recursion

  • 3 class periods
  • 45 minutes each
  • Objective 4.16.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    3 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
3 class periods of 45 minutes
Learning objectives
4.16.A
Essential knowledge
4.16.A.14.16.A.24.16.A.3
Materials
Projector and the Calls All the Way Down slide deckWhiteboard and markersMini whiteboards or scrap paper (call tables and call stacks)Sticky notes (Day 2 call stack demonstration)IDE on every computerPrinted Calls All the Way Down puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:077 minWarm-upwhat place are you in line? (slide 2)
  2. 0:07–0:2215 minDirect instructiona method that calls itself (slides 3–6)
  3. 0:22–0:3210 minDirect instructiona base case you can jump over (slide 7)
  4. 0:32–0:4210 minGuided practicewhich starts reach the base case? (slide 8)
  5. 0:42–0:453 minClosuretwo parts of every recursive method

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-updoes it stop?
  2. 0:05–0:1712 minDirect instructionthe call stack (slides 9–10)
  3. 0:17–0:258 minGuided practicein, middle, out (slide 11)
  4. 0:25–0:338 minIndependent practiceworksheet question 4
  5. 0:33–0:4310 minDirect instructionreturning values on the way back (slides 12–13)
  6. 0:43–0:452 minClosurewho finishes first?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upworksheet question 1 review
  2. 0:05–0:138 minGuided practicetrace mystery(14) (slide 14)
  3. 0:13–0:2512 minDirect instructionrecursion and loops (slides 15–17)
  4. 0:25–0:3510 minIndependent practiceworksheet questions 8 and 3
  5. 0:35–0:405 minClosurehow does it ever stop? (slides 18–19)
  6. 0:40–0:455 minExit ticket

Overview

Day 1 introduces the idea: a recursive method is a method that calls itself, with at least one base case that halts the recursion and at least one recursive call, and recursion is another form of repetition (4.16.A.1). Students learn that a base case only helps if every call moves toward it, and see the StackOverflowError when it never arrives. Day 2 is the call stack: every call has its own parameters and local variables, so code after a recursive call runs newest-first on the way back (4.16.A.2), and a returning method builds its answer on the way back up. Day 3 compares recursion with loops: the parameters capture the progress the way a loop control variable does (4.16.A.2), and any recursive solution can be written with a loop and vice versa (4.16.A.3).

This topic is about reading recursion. The CED excludes writing recursive code from the course and exam, so every activity asks students to trace, predict, find a base case, judge whether a call ends, or match a recursive method to a loop. Students may write loops (Unit 2) but are never asked to write a recursive method from scratch; the worksheet’s code tiles and snippet pool have them assemble or complete one from given pieces, which is still reading.

Students know if/else (Topic 2.3), while and for loops and infinite loops (Topics 2.7 and 2.8), integer division and % (Topic 1.3), and how a method call pauses the caller and gets fresh copies of its arguments (Topics 3.5 and 3.8). Stay inside the boundary: recursive searching and sorting, including binary search and merge sort, are Topic 4.17. Do not trace a recursive method over an array or a String today; small int parameters are enough.

Teacher note

The slides are the Calls All the Way Down deck (19 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–8, Day 2 uses slides 9–13, and Day 3 uses slides 14–19. The Calls All the Way Down puzzle worksheet (9 questions, about 30 minutes) is spread across the days: question 4 in class on Day 2, questions 1, 2, and 9 as Day 2 homework, questions 3 and 8 in class on Day 3, and questions 5, 6, and 7 as Day 3 homework.

All demonstration files are full programs in the topic’s examples/ folder.

  • Day 1 demonstrations: LaunchLoop, LaunchRecursive, LaunchStarts, NoBaseCase, LapCounter, ClimbCheck. NoBaseCase and LapCounter end in a StackOverflowError; let students predict before you run them, and scroll to the top of the long error to find its first line.
  • Day 2 demonstrations: CountUp, DownAndUp, SumTo, SumToIgnored.
  • Day 3 demonstrations: AddRange, DigitSum, PowerBothWays, DigitSumLoopBug, AddRangeStuck.
  • Printed only (exit ticket): ExitBounce and ExitScore.

Day 1 · Warm-up: What place are you in line?

Show slide 2. Students are in a line and can talk only to the person directly in front of them. Pairs get two minutes to decide what to ask and who can answer without asking anyone. Take answers, then act it out with five volunteers: each asks the person in front “What place are you?” and waits. The person at the front just knows: “First.” The answer travels back, and each person adds 1 before passing it on.

Name the three things the class just did and write them on the board: the same small question asked again, someone who just knows the answer, and an answer built on the way back. Those are today’s recursive call, base case, and returned value.

Teacher note

Keep the volunteers standing until each has said their number out loud. Students will refer back to “the person who had to wait” on Day 2, when the call stack makes that waiting precise.

Day 1 · Direct instruction: A method that calls itself

  1. Goals (slide 3). Read the five goals; goals 1 and 2 are today’s, 3 and 4 are Day 2’s, and 5 is Day 3’s.
  2. Recursion is repetition (4.16.A.1). Run LaunchLoop: a while loop prints 3, 2, 1, Liftoff!. Then ask how you would explain a countdown to a friend without the word “repeat”: “Say 3, then count down from 2.” Each step hands a smaller copy of the same job to the next step.
  3. The two parts (4.16.A.1, slide 5). A recursive method is a method that calls itself; the call inside its own body is the recursive call. The base case is a path that finishes without calling again; here n == 0 prints Liftoff! and stops. Every recursive method needs at least one of each. Open LaunchRecursive in the IDE and have students point to the if (line 5) and the recursive call (line 12) before you run it.
  4. Trace call by call (slide 6). Walk the staircase: countdown(3) prints 3 and calls countdown(2), down to countdown(0), which prints Liftoff! and makes no call. Ask: “How many calls happened, and who made them?” Four: one from main and three the method made itself. The parameter shrinks by 1 each call, so it must reach 0.
  5. The argument decides how many times (LaunchStarts). Ask students to predict countdown(5) and countdown(0) before you run it. countdown(0) prints only Liftoff!: the if decides on every call whether to call again, including the first.

Misconception: No loop, so it runs once

Students see countdown(3) in main, find no while or for, and predict that only 3 prints. Point at line 12 of LaunchRecursive and ask what a method call does: it runs the whole method. That call runs countdown again with 2, which runs it again with 1. Tell students to treat every recursive call as a brand-new call they must follow all the way through, and to write one row per call in a table.

Day 1 · Direct instruction: A base case you can jump over

  1. No base case at all. Ask what countdown would do without the if. Run NoBaseCase after students predict: it prints 3, 2, 1, 0, −1, … and then crashes with java.lang.StackOverflowError.
  2. Why it crashes instead of running forever. A call that has made a recursive call is not finished; it is waiting, and Java must remember every waiting call. With no way out, the waiting calls pile up until Java runs out of the memory set aside for them, the call stack. Day 2 draws that stack; today it is enough to say that waiting calls take space.
  3. A base case you can jump over (slide 7). The same countdown, now calling countdown(n - 2). Ask for the output before revealing it: 3, 1, −1, −3, … and a StackOverflowError. The base case exists, but the calls step right over 0. Stress the slide’s first line: it compiles, because Java checks types, not whether the calls ever reach a base case.
  4. The fix (LapCounter). laps(6) reaches 0, but laps(5) goes 5, 3, 1, −1. Ask for a one-token fix: remaining == 0 becomes remaining <= 0, so −1 is caught by the base case.

Misconception: Having a base case means it will stop

Students check that an if with no recursive call exists and stop there. A base case only helps if the recursion reaches it. Give students a two-part check for every recursive method: Is there a path with no recursive call? Does every recursive call’s argument move toward that path without being able to skip past it? The worksheet’s Watch Out box after question 6 states the same rule with n == 10 and n + 4.

Misconception: It compiled, so the recursion is fine

Students expect the compiler to reject a method that never reaches its base case. The compiler checks types and that a non-void method returns on every path; it does not check whether the calls end. A missing or unreachable base case shows up only at run time, as a StackOverflowError.

Day 1 · Guided practice: Which starts reach the base case?

Show slide 8. Students copy the table onto mini whiteboards and write “done” or “crash” for each start, then compare with a partner before you reveal. step(0) goes 0, 3, 6, 9, 12 and prints done. step(3) prints done. step(5) goes 5, 8, 11, 14, …, jumps over 12, and crashes. step(12) is the base case right away and prints done. step(15) moves away from 12 and crashes.

Ask the class for the rule: the start must be 12 or less and a multiple of 3 away from 12. Then run ClimbCheck, which steps by 1 toward 10, and ask which starts work there (every start of 10 or less): with a step of 1, the argument cannot jump over the target, so only the direction matters.

Teacher note

These conditions on the starting value are what the CED’s skill 4.B calls the initial conditions a method needs to work as intended. AP questions often ask, “For which values of the parameter does this call finish?”

Day 1 · Closure: Closure

Each student writes, for LaunchRecursive, the line number of the base case and of the recursive call, and one sentence on what would happen if the recursive call were countdown(n + 1). Look for: line 7 (or the n == 0 branch), line 12, and “it moves away from 0, so it crashes with a StackOverflowError.”

Day 2 · Warm-up: Does it stop?

Write this method on the board: if (n >= 20) prints stop; otherwise it calls itself with n * 2. Students decide which of go(3), go(25), and go(0) print stop. go(3) doubles 3, 6, 12, 24 and stops. go(25) stops at once. go(0) stays 0 forever (0 × 2 is 0) and crashes. Moving “toward” the base case has to actually change the argument.

Day 2 · Direct instruction: The call stack

  1. Each call has its own variables (4.16.A.2). Ask: “When countdown(3) calls countdown(2), does the new call overwrite the first call’s n?” No. From Topic 3.5, every call gets fresh parameters with copies of the arguments, and from Topic 3.8, they last only while that call runs. The rule does not change when a method calls itself.
  2. The sticky-note stack (slide 10). Each new call puts a sticky note on top of the board with its own n. Only the top note runs; the notes below are paused at their recursive call. When the top call finishes, its note comes off and the call below resumes exactly where it paused. Build the stack for stairs(3) with real sticky notes as you trace: four notes, stairs(0) on top.
  3. Work after the call runs backwards. Ask for the output of stairs(3) before revealing it: step 1, step 2, step 3. The print comes after the recursive call, so no call can print until the call it made has finished. The deepest call prints first. Run CountUp for the same pattern with a base case that prints.
  4. Local variables too (DownAndUp). Each call computes its own doubled before the recursive call and prints it again afterward. When echo(1) resumes, its doubled is still 2 even though echo(0) made a doubled of 0. They were never the same variable.

Misconception: The base case ends the program

For CountUp, students predict only Start, because “the base case stops the recursion.” Reaching the base case stops new calls, but every paused call still resumes and finishes its remaining lines. Point at the sticky notes still on the board after the top one comes off: each is a call with work left to do.

Misconception: All the calls share one n

Students picture one variable n that each call changes, so after the recursion they expect every print to show the last value (0 or 1). Each call has its own copy. Have students write each call’s n on its own sticky note and read the value from that note, never from the note above it. Worksheet question 9’s lie (claim 3) is exactly this error.

Day 2 · Guided practice: In, middle, out

Show slide 11. Students write the exact output of visit(2) on mini whiteboards using the slide’s hint. Reveal: in 2, in 1, middle, out 1, out 2. Ask a student to explain why out 1 comes before out 2 using the stack: visit(1) was on top of visit(2), so it finished first.

Day 2 · Independent practice: Independent practice

Students do worksheet question 4 (code tiles) on their own. The correct else branch is the dig print, then dig(n - 1), then the up print. Circulate and ask anyone who chose "up " + (n - 1) what n holds in dig(1) when it resumes; the recursive call did not change that call’s n. The Fair Question box under question 4 is the same sticky-note idea in words; have early finishers read it.

Day 2 · Direct instruction: Returning values on the way back

  1. A recursive description (slide 13). The total of 1 through 4 is 4 plus the total of 1 through 3, and so on down to the total of 1 through 1, which is just 1. That is sumTo.
  2. Going down, coming back up. Trace sumTo(4) with the slide’s two columns. Going down, each call writes n + sumTo(n - 1) and must wait: no addition happens until the base case returns 1. Coming back up, each call replaces its waiting call with the returned number: 2 + 1 = 3, 3 + 3 = 6, 4 + 6 = 10. Run SumTo to confirm.
  3. Ignoring the returned value (SumToIgnored). Show the version that calls sumTo(n - 1); on its own line and then returns n. Ask for the output before running it: 4. The call runs and computes 6, but a call used as a statement throws its value away (Topic 3.5).

Misconception: The base case's value is the answer

Students see return 1 and answer 1, or stop the trace at the base case. The base case’s value goes back to the call that was waiting for it, not to main. Only the first call’s return value reaches main. Make students fill in the “back up” column on slide 13 from the bottom to the top before they write a final answer.

Misconception: Ignoring the value a recursive call returns

A recursive call on its own line still runs, but its returned value is lost. In SumToIgnored the result is just n. When tracing, check whether each recursive call’s value is used in an expression or stored in a variable.

Day 2 · Closure: Closure

Ask: “In sumTo(4), which call starts first, and which call finishes first?” sumTo(4) starts first; sumTo(1) finishes first. The first call to start is the last to finish.

Homework: worksheet questions 1, 2, and 9 (about 12 minutes). Question 2 is the call table from slide 13 with tally; question 9 is the call stack in a two-truths-and-a-lie.

Day 3 · Warm-up: Worksheet question 1 review

Poll the class on homework question 1 (hop(11)) with hands or cards for A–D. The answer is A: four calls (hop(11), hop(8), hop(5), hop(2)), and the returns are 2, 3, 4, 5. Students who chose B forgot the + 1 each waiting call adds on the way back; students who chose C or D did not count the base-case call. Use the split to decide how long to spend on slide 14.

Day 3 · Guided practice: Trace mystery(14)

Show slide 14. Pairs fill in the call table for mystery(14) on mini whiteboards and count the calls. mystery(14) waits on mystery(4) (14 / 3 is 4); mystery(4) waits on mystery(1); mystery(1) is a base case because 1 < 3, and returns 1. Coming back: mystery(4) returns 1 + 4 % 3 = 1 + 1 = 2, and mystery(14) returns 2 + 14 % 3 = 2 + 2 = 4. Three calls in all.

Teacher note

If students ask what mystery computes: it adds the digits of n written in base 3 (14 is 112 in base 3). That is a fun aside, but the AP skill is the trace, not naming the purpose. Students who compute 14 % 3 before the recursive call still get 4; the order of the two operands in the + does not change the sum here.

Day 3 · Direct instruction: Recursion and loops

  1. The parameter does the job of the loop variable (4.16.A.2, slide 16). Put the for loop and countdown side by side and fill in the slide’s table with the class: starts at int n = 3 / countdown(3); stops when n > 0 is false / the base case n == 0; moves on by n-- / countdown(n - 1). A loop changes one variable over and over; recursion gives each call a new parameter holding the next value.
  2. Parameters can carry a running total (AddRange). addLoop and addRecursive both add 3 through 6 and print 18. Trace them in two columns: loop pass 3 has i 5 and total 7, and the third call is addRecursive(5, 6, 7). The rows match exactly. Then show AddRangeStuck: passing i instead of i + 1 is the recursive version of forgetting i++, and it crashes instead of looping forever.
  3. Either one can replace the other (4.16.A.3, slide 17). sumLoop(5) and sumRec(5) both return 15. Any recursive solution can be written with a loop, and any loop can be written recursively; programmers choose whichever is clearer. Line up the parts: the base case’s return value is the loop’s starting total (return 0 and total = 0), and the changed argument is the loop update. Run DigitSum and PowerBothWays as two more matched pairs.

Misconception: Copying the base case test into the loop condition

When translating digitSumRecursive to a loop, students reuse n < 10 and write while (n >= 10). Run DigitSumLoopBug: it prints 10 instead of 14, because the last digit is never added. The base case did not just stop; it returned n, adding that digit. A loop has no such return, so it must run until n is 0. When translating, check that the work the base case did still happens.

Misconception: Some problems need recursion, others need loops

Students who have just seen both versions still say that recursion is “for harder problems” or that some jobs cannot be done with it. Answer with the CED statement directly: any recursive solution can be replicated with an iterative approach and vice versa. Worksheet question 3’s last line asks students to say exactly this.

Day 3 · Independent practice: Independent practice

Students work worksheet question 8 (match-up), then question 3 (face-off). In question 8, r1 prints before it calls (S: 4 3 2 1), r2 prints after the call returns (P: 1 2 3 4), and r3 steps by 2 (Q: 4 2); loop R has no twin because no method prints 0. Push students who match r2 to S to trace it with the call stack from Day 2. Question 3 summarizes the whole topic in eight blanks; check that students wrote “parameters” (not “variables” or “loop variable”) for what tracks progress.

Day 3 · Closure: Closure

Spend one minute on the vocabulary on slide 18; ask students which two words name the parts every recursive method needs. Then show slide 19 and have pairs finish the sentence starter about countdown: “The recursion stops when n reaches 0, the base case, and every recursive call has to move n closer to 0.”

Homework: worksheet questions 5, 6, and 7 (about 12 minutes). Question 7 is a good check of Day 1’s “it compiles, so it’s fine” misconception: two of its four methods compile and then crash.

Day 3 · Exit ticket: Exit ticket

Give the exit ticket (about five minutes). Score each question separately: question 1 checks tracing with code after the recursive call and a base case that catches a jump (4.16.A.1, 4.16.A.2), question 2 checks finding a return value on the way back (4.16.A.1), and question 3 checks a return value and matching recursion with a loop (4.16.A.2, 4.16.A.3). Re-teach the weakest one before Topic 4.17, which traces recursive binary search and merge sort and depends on all three.

Exit ticket

Question 1 · Multiple choice

What does this program print?

ExitBounce.java
public class ExitBounce
{
    public static void bounce(int n)
    {
        if (n <= 0)
        {
            System.out.println("floor");
        }
        else
        {
            System.out.println("down " + n);
            bounce(n - 2);
            System.out.println("up " + n);
        }
    }

    public static void main(String[] args)
    {
        bounce(5);
    }
}
  1. Seven lines: down 5, down 3, down 1, floor, up 1, up 3, up 5
  2. Four lines: down 5, down 3, down 1, floor
  3. Seven lines: down 5, down 3, down 1, floor, up 5, up 3, up 1
  4. down 5, down 3, down 1, then a StackOverflowError, because n skips over 0
Check your reasoning

A.

Step Running Its n Prints
1 bounce(5) 5 down 5
2 bounce(3) 3 down 3
3 bounce(1) 1 down 1
4 bounce(-1) -1 floor
5 bounce(1) resumes 1 up 1
6 bounce(3) resumes 3 up 3
7 bounce(5) resumes 5 up 5

Each call has its own n, and the up line runs after the recursive call returns, so the up lines come out newest call first.

B stops at the base case, but each waiting call resumes after the call it made returns and still runs its up line. C resumes the calls oldest first, but the newest call, bounce(1), is the first one to finish. D expects the calls to miss the base case, but it is n <= 0, not n == 0, so −1 stops the recursion even though the calls skip over 0.

Question 2 · Multiple choice

What does this program print?

ExitScore.java
public class ExitScore
{
    public static int score(int n)
    {
        if (n <= 1)
        {
            return 1;
        }
        return n * 2 + score(n - 3);
    }

    public static void main(String[] args)
    {
        System.out.println(score(7));
    }
}
  1. 14
  2. 22
  3. 23
  4. Nothing: it crashes with a StackOverflowError.
Check your reasoning

C. The calls are score(7), score(4), and score(1), which is a base case because 1 <= 1. Working back up: score(1) returns 1, score(4) returns 4 × 2 + 1 = 9, and score(7) returns 7 × 2 + 9 = 23.

  • A is wrong: 14 is only the first call’s own work (7 × 2); it leaves out the value its recursive call returns.
  • B is wrong: 22 is 14 + 8, which adds each call’s work but drops the 1 that the base case returns.
  • D is wrong: the argument goes 7, 4, 1, and n <= 1 catches 1, so the recursion stops.

Question 3 · Multiple choice

The method halves(int n) returns 0 when n == 0, and otherwise returns 1 + halves(n / 2). Which statement is correct for every n of 0 or more?

  1. halves(12) returns 5, one for each call; this loop returns the same value: int count = 0; while (n >= 0) { n = n / 2; count++; } return count;
  2. halves(12) returns 3, because the halving stops at 1; this loop returns the same value: int count = 0; while (n > 1) { n = n / 2; count++; } return count;
  3. halves(12) returns 4; this loop returns the same value: int count = 1; while (n > 1) { n = n / 2; count++; } return count;
  4. halves(12) returns 4; this loop returns the same value: int count = 0; while (n > 0) { n = n / 2; count++; } return count;
Check your reasoning

D. The calls use 12, 6, 3, 1, and 0; halves(0) returns 0, and each of the four waiting calls adds 1 on the way back, so halves(12) returns 4. In the loop, stopping when n > 0 is false matches the base case n == 0, and count starting at 0 matches the base case’s return 0. The update n = n / 2 matches the argument n / 2, and count++ matches the 1 +. Any recursive solution can be written with a loop like this.

A counts the base case call as a 1, but halves(0) returns 0; its loop never ends, because 0 / 2 is 0 and 0 >= 0 stays true. B stops at 1, but halves(1) is not a base case: it returns 1 + halves(0), which is 1. C gets 4 for 12, but its stopping point does not match the base case: it returns 1 for n = 0, where halves(0) returns 0.