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