I have to write a recursive method to count the number of user entered even integers in an array (the array size is up to 100). Here's what I have....

public static int countEven (int numbers[], int startIndex, int endIndex)

            if (numbers[startIndex]%2 == 0)
                return 1;

                return 0;

            if (numbers[startIndex]%2 == 0)
                return 1 + countEven (numbers, startIndex+1,  endIndex);

                return countEven (numbers, startIndex+1, endIndex);

This compiles and runs, but all it ever returns is 100 (I understand this is the size of the array). I've been tooling around with it for a while now, but I can't seem to get the result I want. Obviously, it's counting every index in the array whether it has 100 values or not, but I can't figure out how to fix it. Thank you in advance or any help.

5 Years
Discussion Span
Last Post by pyTony

One potential problem with the way this is coded is that you have not used {}s for the statements in the if and else parts. This can often cause problems that are hard to see.


Add some printlns to show the logic flow and the values of the variables as they change. Test with a smaller array.


I must say your method does confuse me abit, so i created a bit of a neater one, which des what you ask, maybe you could disect it and then use it as you like:

 * @params accepts integer array
 * @returns integer which holds even number count
private static int countEvenNumbers(int[] numbersArray) {

    int evenCount = 0;

    for (int i = 0; i < numbersArray.length; i++) {//iterate through array

        if (numbersArray[i] % 2 == 0) {//number is divisible by 2, thus even
            evenCount += 1;
    return evenCount;

Edited by DavidKroukamp: code


You are overcomplicating things, pseudocode:

empty sequence has 0 even numbers, 
other sequences have (1 if first number even else 0 + number of even in rest of sequence) even values

Edited by pyTony: missing words

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.