# Count Occurrence of an Element in an Array

Count Occurrence of an Element in an Array” is a basic problem of array data structure. Here, we are given an array of size ‘n’ and an element ‘x’. Our task is to count the occurrences of an element ‘x’ in an array.

Example:

```INPUT:
Enter the size of an array: 10
Enter Array Elements:
12 13 11 12 45 67 13 11 12 43
Enter an element to count: 12
OUTPUT:
The number of occurrences of 12 are: 3```

The steps required to count occurrences of an element are as follows:

1. Scan the size of array and elements of the array from user.
2. Scan the key element whose occurrences needed to be count from the array.
3. Set Count = 0.
4. Iterate over each element and check whether it is equal to key element or not. If element is key element, increment count as: Count = Count + 1.
5. Print the result as Count.

C++ Program to count occurrences of an element is as follows:

```/* Program to count occurence of key element in an array */
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Scan size of array */
int n;
cout<<"Enter the size of an array: ";
cin>>n;

/* Scan Array Elements */
int arr[n];
cout<<"\nEnter array elements:\n";
for(int i = 0; i < n; i++)
{
cin>>arr[i];
}

/* Scan key element */
int key;
cout<<"\nEnter key element: ";
cin>>key;

int count = 0;

/* Count occurence of key element in an array */
for(int i = 0; i < n; i++)
{
if(arr[i] == key)
count = count + 1;
}

/*Printing the result */
cout<<"\nThe number of occurences of "<<key<<" are: "<<count;
}

```
```OUTPUT:
Enter the size of an array:
Enter array elements:
1 3 2 3 5
Enter key element:
The number of occurences of 3 are: 2
Time Complexity:
O(n), where ‘n’ is the size of an element```

Related Posts: