C program to count occurrences of an element in an array; Through this tutorial, we will learn how to count occurrences of an element in an array in c programs.
C Program to Count Occurrences of an Element in an Array
/* C program to find occurrence of an element in one dimensional array. */ #include <stdio.h> #define MAX 100 int main() { int arr[MAX], n, i; int num, count; printf("Enter total number of elements: "); scanf("%d", &n); //read array elements printf("Enter array elements:\n"); for (i = 0; i < n; i++) { printf("Enter element %d: ", i + 1); scanf("%d", &arr[i]); } printf("Enter number to find Occurrence: "); scanf("%d", &num); //count occurance of num count = 0; for (i = 0; i < n; i++) { if (arr[i] == num) count++; } printf("Occurrence of %d is: %d\n", num, count); return 0; }
The output of the above c program; as follows:
Enter total number of elements: 5 Enter array elements: Enter element 1: 5 Enter element 2: 2 Enter element 3: 5 Enter element 4: 9 Enter element 5: 4 Enter number to find Occurrence: 5 Occurrence of 5 is: 2