Find unique elements in an array question in C

Advertisements

I need to print all the unique elements in an array of ints but when I compile my program I get below error.

muratakar$ gcc Code.c 
    Code.c:20:39: error: expected expression
    int isUnique = uniqueElements(arr[], n);

Here is my code given below. Please help me to find the problem and fix it. Thanks in advance.

//Unique Elements Finder : Implement a C function to find all unique elements in an array.

#include <stdio.h>
#include <stdlib.h>

int uniqueElements(int arr[], int n);
int main()
{
    system("clear");
    int arr[10];
    
    for(int i=0;i<10;++i)
    {
        printf("Please enter a number: ");
        scanf("%d", &arr[i]);
    }

    int n;
   
    int isUnique = uniqueElements(arr[], n);
    printf("\n\n");
    return 0;
}

int uniqueElements(int arr[], int n)
{
    for (int i = 0; i < n;++i)
    {
        int isUnique = 1;
        for (int j = 0; j < n;++j)
        {
            if(i!=j && arr[i]==arr[j])
            {
                isUnique = 0;
                return 0;
            }
        }
        if (isUnique)
        {
            printf("%d", arr[i]);
        }
    }
}```

I tried to put `10` between [] but it did not help.                                                                                                                      

>Solution :

Split task into smaller problems.

Here you have an example of the "brut force" implementation:

int isUnique(const int *array, const int val, const size_t size)
{
    size_t count = 0;
    for(size_t index = 0; index < size; index++)
    {
        //if found more than once the it is not unique
        if((count += (array[index] == val)) > 1) break;
    }
    return count == 1;
}

void printAllUnique(const int *array, size_t size)
{
    for(size_t index = 0; index < size; index++)
        if(isUnique(array, array[index], size))
            printf("Unique value %d at pos %zu\n", array[index], index);
}

Leave a ReplyCancel reply