# Thread: How can I count the total no of unique elements in an array?

1. ## How can I count the total no of unique elements in an array?

Hi
How can i count the total no of unique elements in an array?
like I have an array.

Code:
```int array[]= { 2,1,4,0,3,3,0,0,1,2,1,1}
// As it has 0,1,2,3,4 as unique values so total no of unique values are=5
int unique =5;```
Thanks

2. What have you tried?

Jim

3. My problem is that array is not sorted, it work fine if i do first sorting.. some thing like that

1. Code:
` const int size = 7;`
2. int array[size] = {0,0,0,1,2,3,3};
3. int unique = 1; //In case we have only one element; it is unique!
4. for(int i = 0; i < size -1 ; i++)
5. {
6. if(array[i]==array[i+1])
7. continue;
8. else
9. unique++;
10. }
11. printf("The number of unique elements are %d ",unique);
12. }

Originally Posted by jimblumberg
What have you tried?

Jim

• Originally Posted by gevni
My problem is that array is not sorted, it work fine if i do first sorting.
That is a good idea, so do it.

By the way, post your code in [code][/code] bbcode tags instead of list tags.

• So if the array is not sorted then either sort the array, or maybe create an array of numbers found to store the "unique" numbers. Also why are you using "i < size -1" in you for loop, that will probably miss the last element.

Jim