Recursion

AP Computer Science A· difficulty 4/5

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

What is printed?

  • A

    14

    check_circle
  • B

    11

  • C

    23

  • D

    10

Explanation

Sums even indices: 3 + 4 + 5 + 2 = 14.

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

Related questions