Recursion

AP Computer Science A· difficulty 3/5

public static int sum(int[] a, int i) {
    if (i == a.length) return 0;
    return a[i] + sum(a, i + 1);
}
int[] arr = {1, 2, 3, 4};
System.out.println(sum(arr, 0));

What is printed?

  • A

    0

  • B

    10

    check_circle
  • C

    1

  • D

    4

Explanation

1+2+3+4 = 10. Recursion adds each element from index i to the end.

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

Related questions