Write a C Program to Count number of occurrences (or frequency) in a given sorted array Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 2 Output: 4 // x (or 2) occurs 4 times in arr[]
#include <stdio.h>
// Function to count the occurrences of a given element in a sorted array
int countOccurrences(int arr[], int size, int x) {
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == x) {
count++;
} else if (arr[i] > x) {
// Since the array is sorted, if the current element is greater than x,
// we can break the loop since x won't appear again in the array.
break;
}
}
return count;
}
int main() {
int arr[100];
int size, x;
printf("Enter the size of the sorted array: ");
scanf("%d", &size);
printf("Enter %d elements in ascending order:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to count its occurrences: ");
scanf("%d", &x);
int occurrences = countOccurrences(arr, size, x);
printf("%d occurs %d times in the array.\n", x, occurrences);
return 0;
}
0 Comments