alt

Count the frequency of element in array | Simple Tuto

Hi Guys. Welcome you all for the next article of  “C Programming – How to do it” series. Today we are going to Count the frequency of element in array. Before the start our tutorial I have to do a kind request. If you haven’t liked our Facebook Page yet, please like it to support us. (FB Page: BMaxx Edu). Lets move to our work guys.

Problem Solution

  1. Declare an array with user-defined size or fixed size. Name it as nu and store the size of the array as size
  2. Declare another array with the same size as of input array size to store the frequency of elements.
  3. To count the frequency we use a nested loop. Outer loop to select an array element. Inner loop to find the duplicate element of the currently selected array element by the outer loop. Run an outer loop from 0 to size.
  4. Inside the outer loop, initialize count variable with 1 to count the total frequency of the current array element.
  5. Run an inner loop to count total duplicates of the current array element. Run the inner loop from i + 1 to size.
  6. Inside the inner loop, use an if condition between num[i] and num[j] to compare the equality of them.
  7. When the inner loop completes its repetition for a selected “i value” store the frequent as freq[i] = count. Then start the next round.
  8. Finally, print the freq the array to get frequencies of each array element.

Program Code

int main()
{
    int size, i, j, count;
    int num[size], freq[100];

    printf("Max Array Size is 100 \n");
    printf("Enter size of array: ");
    scanf("%d", &size);
    printf("\n \n");

    for(i=0; i<size; i++)
    {
        printf("Enter elements to array: ");
        scanf("%d", &num[i]);
    }
    for(i=0; i<size; i++)
    {
        count = 1;
        for(j=i+1; j<size; j++)
        {
            if(num[i]==num[j])
            {
                count++;
                freq[j]=0;
            }
        }
        if(freq[i] != 0)
        {
         freq[i]=count;
        }
    }

    printf("\nFrequency of all elements of array : \n");
    for(i=0; i<size; i++)
    {
        if(freq[i] != 0)
        {
            printf("%d occurs %d times\n", num[i], freq[i]);
        }
    }

    return 0;
}
Bonomi Tharinda
Bonomi Tharinda is the Developer of the BMaxx Blog. He is a skilled web developer and graphic designer. In addition, he is an undergraduate student of a representative University in Sri Lanka. He is working as a tutor of an institute and as a part-time blogger, he will help you all to make your problems solved.Here are his social accounts and you can follow him through them.