Count Number Occurrences in C

One way to count the occurrence of a specific number is by traversing through the entire array or string and keeping track of the frequency. Below is an example code:

#include <stdio.h>

int countOccurrences(int arr[], int n, int num) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == num) {
            count++;
        }
    }
    return count;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 2, 3, 2, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    int num = 2;
    
    int occurrences = countOccurrences(arr, n, num);
    
    printf("%d occurs %d times\n", num, occurrences);
    
    return 0;
}

In this example, the countOccurrences function is used to tally the number of times the number num appears in the array arr. In the main function, we define an array arr and then call the countOccurrences function to count the number of times 2 appears. Finally, we print out the result of the count.

bannerAds