Recursion

AP Computer Science A· difficulty 3/5

public static int sum(int n) { return helper(n, 0); }
private static int helper(int n, int acc) {
    if (n == 0) return acc;
    return helper(n - 1, acc + n);
}
System.out.println(sum(4));

What is printed?

  • A

    10

    check_circle
  • B

    4

  • C

    0

  • D

    24

Explanation

Tail-recursive accumulator sums 4+3+2+1 = 10.

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

Related questions