Skip to content
Advertisement

Count occurrences of a given integer in an array using recursion

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);
    }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement