Skip to content

Commit fa97eab

Browse files
authoredOct 5, 2022
Create Count number of occurrences (or frequency) in a sorted array.cpp
1 parent b5eb6e1 commit fa97eab

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// C++ program to count occurrences of an element
2+
#include<bits/stdc++.h>
3+
4+
using namespace std;
5+
6+
// Returns number of times x occurs in arr[0..n-1]
7+
8+
int countOccurrences(int arr[], int n, int x)
9+
{
10+
11+
int res = 0;
12+
13+
for (int i=0; i<n; i++)
14+
15+
if (x == arr[i])
16+
17+
res++;
18+
19+
return res;
20+
}
21+
22+
// Driver code
23+
24+
int main()
25+
{
26+
27+
int arr[] = {1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8 };
28+
29+
int n = sizeof(arr)/sizeof(arr[0]);
30+
31+
int x = 2;
32+
33+
cout << countOccurrences(arr, n, x);
34+
35+
return 0;
36+
}

0 commit comments

Comments
 (0)
Please sign in to comment.