impera Open Impera

AP Computer Science A · Data collections

Recursion

1What recursion is

A recursive method calls itself. Every recursive method needs:

  • a base case: a simple case answered directly, with no recursive call;
  • a recursive case: a call on a smaller version of the problem that moves toward the base case.
public static int factorial(int n) {
    if (n <= 1) return 1;          // base case
    return n * factorial(n - 1);   // recursive case
}

Without a base case (or if calls never reach it), the method recurses forever until the program runs out of call-stack memory: a StackOverflowError.

Check yourself

What happens if a recursive method has no reachable base case?

  • A compile-time error

  • It returns 0

  • It runs once

  • StackOverflowError

Show the answer

StackOverflowError

Infinite calls.

2Tracing recursive calls

Each call gets its own copy of parameters and local variables on the call stack. Calls pause until the call they made returns.

Worked example

factorial(4).

  1. factorial(4) = 4 × factorial(3)
  2. factorial(3) = 3 × factorial(2)
  3. factorial(2) = 2 × factorial(1)
  4. factorial(1) = 1 (base case)
  5. Returning: 2 × 1 = 2; 3 × 2 = 6; 4 × 6 = 24.

Tracing factorial(4): each call waits for the smaller call to return

Check yourself

What does factorial(5) return?

  • 15

  • 24

  • 5

  • 120

Show the answer

120

5 × 4 × 3 × 2 × 1.

3Recursion with strings and arrays

Recursive string methods usually process the first (or last) character and recurse on the rest using substring:

public static String reverse(String s) {
    if (s.length() <= 1) return s;
    return reverse(s.substring(1)) + s.substring(0, 1);
}
Worked example

reverse("abc") = reverse("bc") + "a" = (reverse("c") + "b") + "a" = "cba".

Recursive array methods usually pass an index that moves toward the end:

public static int sum(int[] arr, int i) {
    if (i == arr.length) return 0;
    return arr[i] + sum(arr, i + 1);
}
Check yourself

What does reverse("dog") return?

  • "ogd"

  • "dog"

  • "god"

  • "gdo"

Show the answer

"god"

Recurse on "og", then add "d".

4Output order and recursive searching

Where a print statement sits relative to the recursive call controls output order:

public static void countdown(int n) {
    if (n == 0) return;
    System.out.print(n + " ");
    countdown(n - 1);
}

countdown(3) prints "3 2 1". If the print came after the call, it would print "1 2 3", because each print waits until the deeper calls finish.

Recursive binary search and merge sort are standard recursive algorithms: binary search recurses on half the range; merge sort recurses on each half and merges.

Check yourself

If the print in countdown is moved after the recursive call, countdown(3) prints:

  • 1 2 3

  • 3 2 1

  • Nothing

  • 3

Show the answer

1 2 3

Prints as calls return.

5Going deeper: tracing the call stack, and what happens before and after the recursive call

A recursive method calls itself. It needs two parts:

  • a base case: an input simple enough to answer without another call;
  • a recursive case: a call on a smaller version of the problem, moving toward the base case.

Without a reachable base case the calls never stop, and the program fails with a StackOverflowError.

The call stack: each call gets its own copy of the parameters and local variables. A call waits while the call it made is running, then resumes where it left off.

public static int factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

Worked example (trace factorial(4)):

  1. factorial(4) = 4 × factorial(3): waits.
  2. factorial(3) = 3 × factorial(2): waits.
  3. factorial(2) = 2 × factorial(1): waits.
  4. factorial(1) returns 1 (base case).
  5. Unwinding: 2 × 1 = 2; 3 × 2 = 6; 4 × 6 = 24.

Tracing method: write each call on a new, indented line going down; when the base case is reached, fill in return values going back up.

Before or after? Order of output: statements before the recursive call run on the way down; statements after it run on the way back up, in reverse order.

public static void countDown(int n) {
    if (n > 0) {
        System.out.print(n + " ");
        countDown(n - 1);
    }
}

countDown(3) prints 3 2 1.

public static void countUp(int n) {
    if (n > 0) {
        countUp(n - 1);
        System.out.print(n + " ");
    }
}

countUp(3) prints 1 2 3: the print waits until the deeper calls have finished.

Worked example (both at once): what does mystery(3) print?

public static void mystery(int n) {
    if (n == 0) {
        System.out.print("* ");
    } else {
        System.out.print(n + " ");
        mystery(n - 1);
        System.out.print(n + " ");
    }
}
  1. Going down: prints 3, 2, 1.
  2. Base case: prints *.
  3. Coming back: prints 1, 2, 3.
  4. Output: 3 2 1 * 1 2 3.

Recursion with numbers

public static int sumDigits(int n) {
    if (n < 10) {
        return n;
    }
    return n % 10 + sumDigits(n / 10);
}

sumDigits(472) = 2 + sumDigits(47) = 2 + 7 + sumDigits(4) = 2 + 7 + 4 = 13.

Recursion with strings: handle one character and recurse on the rest.

public static String reverse(String s) {
    if (s.length() <= 1) {
        return s;
    }
    return reverse(s.substring(1)) + s.substring(0, 1);
}

reverse("cat") = reverse("at") + "c" = (reverse("t") + "a") + "c" = "tac".

Recursion with arrays: pass an index (or bounds) that moves toward the end. Recursive binary search passes low and high, and its base case is low > high (not found).

More than one recursive call: Fibonacci.

public static int fib(int n) {
    if (n <= 1) {
        return n;
    }
    return fib(n - 1) + fib(n - 2);
}
Worked example

how many calls does fib(4) make in total?

  1. fib(4) calls fib(3) and fib(2).
  2. fib(3) calls fib(2) and fib(1); each fib(2) calls fib(1) and fib(0).
  3. Counting: fib(4) once, fib(3) once, fib(2) twice, fib(1) three times, fib(0) twice: 9 calls, returning 3.
  4. The same values are recomputed again and again, so the number of calls grows explosively with n. A loop would be far faster.

Recursion against iteration: anything written recursively can be written with a loop, and the reverse. Recursion is often shorter and clearer for problems that are naturally self-similar (merge sort, binary search, tree-like structures), but each call uses memory on the stack.

Checking a recursive method

  1. Is there a base case, and does it return the right thing?
  2. Does every recursive call move toward the base case?
  3. Assuming the smaller call works, does this call combine its result correctly?

Common mistakes

  • No base case, or one that is never reached (n == 0 when n decreases by 2 from an odd start).
  • Calling the method but ignoring its return value (factorial(n - 1); on a line by itself).
  • Forgetting that code after the recursive call still runs.
  • Changing the problem size in the wrong direction.
  • Tracing as though all calls share one copy of the variables.
Check yourself

What does this method return for f(5)? public static int f(int n) { if (n <= 0) return 0; return n + f(n - 2); }

  • 9

  • 15

  • 5

  • 6

Show the answer

9

5 + f(3) = 5 + 3 + f(1) = 5 + 3 + 1 + f(−1) = 9.

6For top marks

  • For "what is returned" questions, write each call on its own line, then substitute values back up.
  • Check that each recursive call moves toward the base case (e.g. n - 1, substring(1), i + 1).
  • Any recursive solution can be written with a loop; recursion is natural for problems that split into smaller copies of themselves.
  • Count calls: mystery(n) calling mystery(n - 1) until 0 makes $n + 1$ calls.
Example

power(b, e) returns 1 if e == 0, otherwise b * power(b, e - 1).

Check yourself

How many calls are made in total by factorial(4) (including the first)?

  • 4

  • 3

  • 24

  • 5

Show the answer

4

n = 4, 3, 2, 1.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera