1

I am supposed to write a recursive(!) method to count the amount of occurrences of a given integer in an integer array and return true if even and false if odd. This is my code so far:

public static boolean evenNumberOf(int x, int[] arr) {

    if (arr == null || arr.length == 0)
        return false;
    int count = counting(x, arr, 0, 0);
    if (count % 2 == 0) {
        System.out.print("true");
        return true;
    } else {
        System.out.print("false");
        return false;
    }
}

public static int counting(int x, int[] arr, int index, int count) {

    if (arr[index] == x && index < arr.length) {
        return counting(x, arr, index++, count++);
    } else {
        return counting(x, arr, index++, count);
    }
}

It works for

evenNumberOf(2, new int[] { 1, 2, 3, 2 });

but it gives java.lang.StackOverflowError for

evenNumberOf(1, new int[] { 1, 2, 3, 2 });

I am not sure how to prevent this endless recursive loop, as I'm new to programming and it's my first time using recursion. Thanks in advance.

Kaan
  • 5,434
  • 3
  • 19
  • 41
egg
  • 13
  • 2
  • 4
    Recursion only works if, at *some* point, the function doesn't need to call itself. As written, `counting` *always* calls itself. – Scott Hunter Nov 30 '21 at 14:06
  • I agree with Scott; there must be a point when the recursive function simply returns a value instead of relying on a next call of itself forever. Another thing is that `index++` is not the same as `++index`! Your line `return counting(x, arr, index++, count++);` seem to invoke itself with the very same parameters it receives, because the `n++` (postfix) operator increments the value only after evaluation. I suspect you'd like to call it like: `return counting(x, arr, ++index, ++count);`, but `return counting(x, arr, index + 1, count + 1);` would be more straight-forward. – Magyar Dávid Nov 30 '21 at 14:15
  • See [this](https://stackoverflow.com/a/70168058/3992939) answer – c0der Nov 30 '21 at 15:35

1 Answers1

4

Any recursion should have a stop condition and 1 or more recursive calls.

in this example, the stop condition is index >= arr.length so you start writing the function as folows:

public static int counting(int x, int[] arr, int index) {
    if (index >= arr.length) {
        return 0;//there are 0 x's between index and arr.length
    }

after you handled the stop condition, you need to write the rest:

public static int counting(int x, int[] arr, int index) {
    if (index >= arr.length) {
        return 0;//there are 0 x's between index and arr.length
    }
    int countAfterIndex = counting(x, arr, index+1);//the amount of x's starting from index+1
    if (x == arr[index]) {
        return countAfterIndex + 1;//there is 1 more to add
    } else {
        return countAfterIndex; //the amount of x's after index is the same as the amount from index.
    }
}
Ofek
  • 1,065
  • 6
  • 19