Recursion

AP Computer Science A· difficulty 3/5

public static int countX(int[] a, int i, int target) {
    if (i == a.length) return 0;
    int rest = countX(a, i + 1, target);
    return (a[i] == target ? 1 : 0) + rest;
}
int[] arr = {1, 2, 1, 3, 1};
System.out.println(countX(arr, 0, 1));

What is printed?

  • A

    3

    check_circle
  • B

    2

  • C

    5

  • D

    1

Explanation

Three 1's appear in the array.

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

Related questions