 # C Programming Code Examples

## C > Arrays and Matrices Code Examples

### count frequency of each element in an array

``` 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. Logic to count frequency of each element of array Finding frequency of each array element is completely based on finding duplicate elements in an array. In fact you can take this program as modified version of find duplicate program. Here you need to find total duplicate count per element instead of whole. Below is the step by step descriptive logic to count frequency of each element of array. Read input in all array elements from user. Store it in some variable say array contains all array elements. Declare another array with same size as of input array size to store frequency of each array elements. Say freq will store frequencies of all array elements. To count frequency of each element we require two loops. One outer loop to select an array element. Second inner loop to find first duplicate element of the currently selected array element by outer loop. Run an outer loop from 0 to N. The loop structure must look like for(x=0; x<N; x++). Inside outer loop, initialize a count variable to count total frequency of the currently selected array element. Say count = 1. Run an inner loop to count total duplicates of currently selected array element. Run an inner loop from x+1 to N. The loop structure should look like for(j=x+1; j<N; j++). Inside inner loop, if a duplicate element is found increment the frequency count of current array element. Which is if(array[x] == array[j]) then count++. After all duplicates has been counted. Store the total duplicate count of current element in the frequency array. Which is say freq[x] = count. Finally print the freq array to get frequencies of each array element. #include <stdio.h> int main() { int array, freq; int size, x, j, count; /* Input size of array */ printf("Enter size of array: "); scanf("%d", &size); /* Input elements in array */ printf("Enter elements in array: "); for(x=0; x<size; x++) { scanf("%d", &array[x]); /* Initially initialize frequencies to -1 */ freq[x] = -1; } for(x=0; x<size; x++) { count = 1; for(j=x+1; j<size; j++) { /* If duplicate element is found */ if(array[x]==array[j]) { count++; /* Make sure not to count frequency of same element again */ freq[j] = 0; } } /* If frequency of current element is not counted */ if(freq[x] != 0) { freq[x] = count; } } /* * Print frequency of each element */ printf("\nFrequency of all elements of array : \n"); for(x=0; x<size; x++) { if(freq[x] != 0) { printf("%d occurs %d times\n", array[x], freq[x]); } } return 0; } ``` 