C program to count frequency of each element in an array

Write a C program to read elements in an array and find frequency of each element in an array. C Program to count the occurrence of each element in an array.

Example: If elements of array are: 5, 10, 2, 5, 50, 5, 10, 1, 2, 2
Frequency of 5 = 3
Frequency of 10 = 2
Frequency of 2 = 3
Frequency of 50 = 1
Frequency of 1 = 1

Required knowledge:

Basic C programming, If else, For loop, Array

Program:

/**
 * C program to count frequency of each element of array
 */

#include <stdio.h>

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

    /*
     * Read size of array and elements in array
     */
    printf("Enter size of array: ");
    scanf("%d", &size);

    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
        freq[i] = -1;
    }

    /*
     * Counts frequency of each element
     */
    for(i=0; i<size; i++)
    {
        count = 1;
        for(j=i+1; j<size; j++)
        {
            if(arr[i]==arr[j])
            {
                count++;
                freq[j] = 0;
            }
        }

        if(freq[i]!=0)
        {
            freq[i] = count;
        }
    }

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

    return 0;
} 
Output
X
_
Enter size of array: 10
Enter elements in array: 5 10 2 5 50 5 10 1 2 2

Frequency of all elements of array :
5 occurs 3 times
10 occurs 2 times
2 occurs 3 times
50 occurs 1 times
1 occurs 1 times

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment