AP Computer Science A · Topic 10.1

Recursion Practice

Part of Recursion.

Practice questions

96

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 96 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    public static int sumRec(int n) {
        if (n == 0) return 0;
        return n + sumRec(n - 1);
    }
    public static int sumIter(int n) {
        int s = 0;
        for (int i = 1; i <= n; i++) s += i;
        return s;
    }

    Which is true?

    • A

      Iteration cannot solve this

    • B

      They produce different sums

    • C

      Recursive version uses less memory

    • D

      Both compute the same result; iteration uses less stack

      check_circle

    Why

    Both sum 1..n. Recursion creates O(n) stack frames; iteration uses O(1) stack.

  2. Sample 2difficulty 2/5

    public static int sum(int[] a, int i) {
      if (i >= a.length) return 0;
      return a[i] + sum(a, i + 1);
    }
    // call: sum({1,2,3,4}, 0)

    What does the call return?

    • A

      6

    • B

      0

    • C

      4

    • D

      10

      check_circle

    Why

    1+2+3+4 = 10.

  3. Sample 3difficulty 2/5

    public static int fact(int n) {
      if (n <= 1) return 1;
      return n * fact(n - 1);
    }
    // call: fact(5)

    What does fact(5) return?

    • A

      60

    • B

      24

    • C

      5

    • D

      120

      check_circle

    Why

    5! = 5<em>4</em>3<em>2</em>1 = 120.

  4. Sample 4difficulty 2/5

    A recursive method

    • A

      Uses static fields

    • B

      Loops forever

    • C

      Cannot return values

    • D

      Calls itself (directly or indirectly)

      check_circle

    Why

    Recursion: method invokes itself with smaller subproblem.

  5. Sample 5difficulty 2/5

    public static int fact(int n) {
        if (n <= 1) return 1;
        return n * fact(n - 1);
    }
    System.out.println(fact(4));

    What is printed?

    • A

      6

    • B

      24

      check_circle
    • C

      12

    • D

      10

    Why

    fact(4) = 4<em>3</em>2*1 = 24. The base case returns 1 when n <= 1.