function to count duplicates in array (C)

Viewed 26

I have to write a function to count duplicates in an array the array is

45 7 -3 5 11 64 7 45 3 -5 7 0 34 64 0 9 2 -85 14 21

as you can see there are 4 duplicates (64,45,7,0), with my code it shows 6 I think there is something wrong because 7 appears 3 times and I cant seem to fix it, so here is my code I would appreciate if I get some help.

int countDuplicates(int array[], int size)
{
    int i, j;
    int counter = 0;

    for (i = 0; i < size; i++)
    {
        for (j = i + 1; j < size; j++)
        {
            if (array[i] == array[j])
            {
                counter++;
            }
        }
    }

    return counter;
}
0 Answers
Related