Recursion

AP Computer Science A· difficulty 3/5

public static int f(int n) {
    if (n == 0) return 1;
    return n * f(n + 1);
}

What is wrong?

  • A

    Base case should return 0

  • B

    Nothing is wrong

  • C

    Multiplication should be addition

  • D

    The recursive call increases n; it never reaches the base case for n > 0

    check_circle

Explanation

f(n+1) makes n grow without bound, so the base case n == 0 is never reached for positive starting values, leading to a stack overflow.

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

Related questions