Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- frequency of each element in array.c
- C program to count frequency of each element of array
- https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html
- https://www.geeksforgeeks.org/find-frequency-number-array/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- int arr[] = {1, 3, 5, 7, -12, 5, 7, 0, -3, 5, 1};
- int *freq = NULL;
- int i, j, n, count;
- n = sizeof(arr) / sizeof(int); // number of elements in array arr
- freq = malloc( n * sizeof(int) ); // allocating memory for n integers
- if( freq == NULL ) {
- fprintf(stderr, "\n\n freq malloc() error! \n\n");
- exit(EXIT_FAILURE);
- }
- printf("\n Array is: "); // Print array arr
- for(i=0; i<n; i++)
- printf("%4d", arr[i] );
- for(i=0; i<n; i++){
- count = 1;
- for(j=i+1; j<n; j++)
- if( arr[i] == arr[j] ){ // If duplicate element is found
- count++;
- *(freq+j) = 0; // Make sure not to count frequency of same element again
- }
- if( *(freq+i) != 0 ) // If frequency of current element is not counted
- *(freq+i) = count;
- }
- printf("\n\n Frequency of all elements of array : \n\n");
- for(i=0; i<n; i++)
- if( *(freq+i) != 0 )
- printf("%5d occurs %3d times\n", arr[i], *(freq+i) );
- free(freq);
- return 0;
- }
RAW Paste Data
Copied