To count the number of occurrences of a specified element in an array in C, you can use loops to iterate through the array and count each occurrence.
In this example,
numbers
with values 10, 20, 30, 40, 30, 50.count
to 0 to store the count of occurrences.count
each time element 30 is found.count
will contain the total count of occurrences of element 30.#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 30, 50};
int count = 0;
for(int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
if(numbers[i] == 30) {
count++;
}
}
printf("Number of occurrences of element 30: %d", count);
return 0;
}
Number of occurrences of element 30: 2
In this example,
fruits
with values 'a', 'b', 'b', 'a', '\0'.count
to 0 to store the count of occurrences.count
each time character 'b' is found.count
will contain the total count of occurrences of character 'b'.#include <stdio.h>
int main() {
char fruits[] = {'a', 'b', 'b', 'a', '\0'};
int count = 0;
for(int i = 0; fruits[i] != '\0'; i++) {
if(fruits[i] == 'b') {
count++;
}
}
printf("Number of occurrences of element 'b': %d", count);
return 0;
}
Number of occurrences of element 'b': 2
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in C language with well detailed examples.