Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Count Occurrences of Each Element in an Array

$
0
0

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.

The post C Program to Count Occurrences of Each Element in an Array appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>