shinryu333
shinryu333

Reputation: 37

My recursion method won't properly return the total amount of occurrences of a char

{
    char[] charArray = {'a', 'b', 'a', 'c', 'a', 'd', 'e', 'b'};
    int occurrences;

    occurrences = countOccurrence(charArray, 'a', 0);

    System.out.println("\"a\" occurred " + occurrences + " times.");
} 
public static int countOccurrence(char[] array, char character, int index)
{
    int counter = 0;
    if (index > array.length-1)
    {
        //This probably seems a little awkward...But I have this here just so it stops 
        //recursion when it hits the end of the array.
    }
    else
    {
        if (array[index] == character)
        {
            counter++;
            countOccurrence(array, character, index + 1);
        }
        else
        {
            countOccurrence(array, character, index + 1);
        }            
    }
    return counter;
}

Hi, for some reason when I run this program the number of occurrences of 'a' is always 1...I've tried tweaking it various ways but I've run out of ideas. I'm still a novice at recursion.

Upvotes: 2

Views: 64

Answers (2)

shauryachats
shauryachats

Reputation: 10385

You should stick to a plain for loop instead of a messy recursion.

public static int countOccurrence(char[] array, char character)
{
    int counter = 0;
    for(int index = 0; index < array.length; ++index)
    {
        if (array[index] == character)
        {
            counter++;
        }
    }
    return counter;
}

Or, if you are hell bent on using recursion:

When your index reaches the value array.length, just terminate the recursion.

That is,

public static int countOccurrence(char[] array, char character, int index)
{
    int counter = 0;
    if (index >= array.length)
        return 0;
    if (array[index] == character)
            counter++;
    counter += countOccurrence(array, character, index + 1);
    return counter;
}

Upvotes: 2

Anderson Vieira
Anderson Vieira

Reputation: 9049

You need to add the result of the recursive call to your counter:

counter += countOccurrence(array, character, index + 1)

Also, note that if you have the same code in the if and else blocks, you should probably factor it out:

if (array[index] == character) {
    counter++;
}
counter += countOccurrence(array, character, index + 1);

A cleaner way to do this using recursion would be:

static int countOccurrence(char[] array, char character, int index) {
    if (index >= array.length) {
        // base case
        return 0;
    } else {
        int foundChar = (array[index] == character) ? 1 : 0;
        return foundChar + countOcurrence(array, character, index + 1);
    }
}

Upvotes: 0

Related Questions