Hi,

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(startIndex==endIndex)
            if (numbers[startIndex]%2 == 0)
                return 1;

            else
                return 0;

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

            else
                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.

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 4 Years Ago 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 4 Years Ago by pyTony: missing words

This article has been dead for over six months. Start a new discussion instead.