Counting occurrences in an array.

Hello folks. I was wondering how to count the number of occurrences within an array. In python there is a count function that returns the number of times a specific value occurs within the array (.count()). Any help would be much appreciated ;).

You have to step through the array yourself. C doesn't offer those kinds of features for simple arrays.

Depending on the type of the array the code can look slightly different.
Below the basics for an unsorted integer array.

int arr[10] = { 1,2,3,2,3,2,1,3,4,3};
int count = 0;
int myNumber = 3;

for (int i=0; i<10; i++)
{
  if (arr[i] == myNumber) count++;
}

Occurrences of characters in an array is similar.

Counting words in an array is a bit more complex.

If the array is sorted, you can break out of the for loop when e.g. arr > 3
A point of attention is counting of arrays holding float values.
Although values will print the same on display/serial often,
they can differ in the digits not shown.
Counting and comparing floats for equalness is therefor a bit more complex.
typical one uses the absolute value and a threshold
```
*float arr[10] = ....

if (abs(arr[i] - myNumber) < threshold) count++*
```
Hope this helps.

When iterating through arrays it is a good idea to allow the compiler to calculate how many entries there are like this

byte NUMBER_OF_ENTRIES = sizeof(theArray) / sizeof(theArray[0]);

This allows you to change the number of entries and/or data type of the array without the need to do any calculations yourself or search/replace any "magic" numbers in your code relating to the size of the array.