Recursion

AP Computer Science A· difficulty 3/5

public static int sumTo(int n) {
    if (n <= 0) return 0;
    return /* missing */;
}

Which expression replaces /* missing */ to compute 1+2+...+n?

  • A

    n + sumTo(n)

  • B

    n * sumTo(n - 1)

  • C

    n + sumTo(n - 1)

    check_circle
  • D

    sumTo(n - 1)

Explanation

Standard tail-recursive summation: add n to the sum of the previous integers; sumTo(n) = n + sumTo(n-1).

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

Related questions