Recursion

AP Computer Science A· difficulty 3/5

public static int factorial(int n) {
    /* missing code */
    return n * factorial(n - 1);
}

Which line correctly replaces /* missing code */?

  • A

    if (n == 0) return n;

  • B

    while (n == 0) return 1;

  • C

    if (n < 0) return -1;

  • D

    if (n <= 1) return 1;

    check_circle

Explanation

The base case must stop recursion. Returning 1 for n <= 1 ensures factorial(1)=1 and prevents infinite recursion. Option B returns 0, giving an incorrect product.

Want 10 more like this — adaptive to your weak spots?

Related questions

AP Computer Science A · Recursion Practice Question | Acemy