C Program to Count Occurrences of Each Element in an Array

Here we’ll see how to write C program to count occurrences of each element in an array. The C program will check how many times a particular integer occurs in the array.

#include <stdio.h>

#define MAX_ARRAY_LEN 1024

int main(){
  int arr[MAX_ARRAY_LEN];
  int counter[MAX_ARRAY_LEN];
  int len = 0;
  int i, j;
  
  printf("Enter the array size: ");
  scanf("%d", &len);

  printf("Enter array elements: ");
  for (i = 0; i < len; i++) {
    scanf("%d", &arr[i]);
    counter[i] = -1; /* Marking as not visisted. */
  }

  for (i = 0; i < len; i++) {
    
    /* i-th element is already visited/counted. */
    if (counter[i] == 0) continue;
    
    counter[i] = 1;
    for (j = i + 1; j < len; j++) {
      if(arr[i] == arr[j]) {
        counter[i]++;
        counter[j] = 0;
      }
    }
  }
  
  for (i = 0; i < len; i++) {
    if (counter[i] == 0) continue;
    printf("%d occured %d times.\n", arr[i], counter[i]);
  }

  return 1;
}

This program first takes the array size and the array elements as input. It maintains another array of same size to keep the elements counters / occurrences.

For each array element, the corresponding counter array element is initialized as -1 to mark as non-visited.

The outer loop iterates for every element of the array. If the corresponding counter [counter[i]] is 0 (means already visited), it skips that element. The inner loop scans the next array elements.

If a match is found, the corresponding counter array element is set to 0 to mark as visited. And the counter is incremented by 1.

At the element, for all elements with non-zero counter value is printed with their corresponding occurrence counter.

Here is sample output.

$ cc test.c -o test
$ ./test
Enter the array size: 10
Enter array elements: 2 32 5 45 6 2 2 45 32 32
2 occured 3 times.
32 occured 3 times.
5 occured 1 times.
45 occured 2 times.
6 occured 1 times.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
2
7
0