Without using a loop, I’m trying to count the number of times a given integer is in an array using recursion. I keep getting a StackOverflow error and I can’t figure out why.
public static int countOccurrences(int[] arr, int n) { if (arr.length == 0) { return 0; } if (arr[0] == n) { return 1 + countOccurrences(arr, n - 1); } return countOccurrences(arr, n - 1); }
}
Advertisement
Answer
If you can use only two parameters, then try:
public static int countOccurrences(int[] arr, int n) { if (arr.length == 0) { return 0; } if (arr[0] == n) { return 1 + countOccurrences(Arrays.copyOfRange(arr, 1, arr.length), n); } return countOccurrences(Arrays.copyOfRange(arr, 1, arr.length), n); }