 # frequency of each element in array.c

May 25th, 2021 (edited)
264
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*
2.
3.     frequency of each element in array.c
4.
5.     C program to count frequency of each element of array
6.
7. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html
8. https://www.geeksforgeeks.org/find-frequency-number-array/
9.
10.
11.     You can find all my C programs at Dragan Milicev's pastebin:
12.
13.     https://pastebin.com/u/dmilicev
14.
15. */
16.
17. #include <stdio.h>
18. #include <stdlib.h>
19.
20. int main()
21. {
22.     int arr[] = {1, 3, 5, 7, -12, 5, 7, 0, -3, 5, 1};
23.     int *freq = NULL;
24.     int i, j, n, count;
25.
26.     n = sizeof(arr) / sizeof(int);      // number of elements in array arr
27.
28.     freq = malloc( n * sizeof(int) );   // allocating memory for n integers
29.     if( freq == NULL ) {
30.         fprintf(stderr, "\n\n freq malloc() error! \n\n");
31.         exit(EXIT_FAILURE);
32.     }
33.
34.     printf("\n Array is: ");            // Print array arr
35.     for(i=0; i<n; i++)
36.         printf("%4d", arr[i] );
37.
38.     for(i=0; i<n; i++){
39.         count = 1;
40.         for(j=i+1; j<n; j++)
41.             if( arr[i] == arr[j] ){     // If duplicate element is found
42.                 count++;
43.                 *(freq+j) = 0;  // Make sure not to count frequency of same element again
44.             }
45.
46.         if( *(freq+i) != 0 )            // If frequency of current element is not counted
47.             *(freq+i) = count;
48.     }
49.
50.     printf("\n\n Frequency of all elements of array : \n\n");
51.     for(i=0; i<n; i++)
52.         if( *(freq+i) != 0 )
53.             printf("%5d occurs %3d times\n", arr[i], *(freq+i) );
54.
55.     free(freq);
56.     return 0;
57. }
58.
RAW Paste Data Copied