From a set of array elements, find the number of occurrences of each element present in the given array.
#include <stdio.h>Â Â Â
  Â
int main()Â Â Â
{Â Â Â
  //Initialize an array of ints
  int myArray[] = {4, 5, 6, 7, 2, 6, 8, 4, 7};  Â
    Â
  //Get array size
  int length = sizeof(myArray) / sizeof(myArray[0]);  Â
  int frequency[length]; //Array to store frequency of element  Â
  int visited = -1;  Â
    Â
  for(int i = 0; i < length; i++)
  {  Â
    int count = 1;  Â
    for(int j = i+1; j < length; j++)
    {  Â
      if(myArray[i] == myArray[j])
      {  Â
        count++;  Â
        frequency[j] = visited; //Ensures element is only counted onceÂ
      }  Â
    }  Â
    if(frequency[i] != visited)  Â
    {
      frequency[i] = count; Â
    }
  }  Â
    Â
  //Displays the frequency of each elementÂ
  printf("Element Frequency\n");
  for(int i = 0; i < length; i++)
  {  Â
    if(frequency[i] != visited)
    {  Â
      printf("%d \t : %d \n", myArray[i], frequency[i]); Â
    }  Â
  }
  return 0;  Â
}Â Â
Comments
Leave a comment