OneBite.Dev - Coding blog in a bite size

count the number of occurrences of a specific element in an array in C

Code snippet on how to count the number of occurrences of a specific element in an array in C

  #include <stdio.h>
  int main ()
  {
    int array[] = {3, 2, 5, 2, 8, 2};
    int i, number = 2, count = 0;
    int array_size = sizeof(array) / sizeof(array[0]);
  
    // Loop through the array
    for (i = 0; i < array_size; i++)
    {
      // Check if the current element is equal to the number
      if (array[i] == number)
        // Increment the count
        count++;
    }
  
    printf("Number of occurrences of %d is %d\n", number, count);
  
    return 0;
  }

This code uses a for loop to iterate through an array. It then checks each element to see if it’s equal to the number we specified, in this case ‘2’. If it is, it increments the count. The size of the array is determined by the size of the first element, so the loop doesn’t run too long. After the loop is finished, the total number of occurrences is printed out.

c