Count All Occurrences of an Element in an Array
“Count All Occurrences 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 write a program to count all occurrences of an element in an array.
Example (Count All Occurrences of an Element in an Array):
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 all occurrences of an element in an array are as follows:
- Scan the size of array and elements of the array from user.
- Scan the key element whose occurrences needed to be count from the array.
- Set Count = 0.
- 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.
- Print the result as Count.
C++ Program to count all occurrences of an element in an array is as follows:
/* Program to count all occurrences of an 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:
- Program to search an element in an Array (Linear Search).
- Program to Rotate Array Elements by ‘D’ positions.
- Program to find most frequent element in an array.
- Program to find pair in an array with given sum.
- Program to find first repeating element of an array.
- Program to merge two sorted arrays.
- Program to find missing number in an array.
- Program to sort if array is sorted.
- Program to Add two Matrix.
- Program to Transpose a Matrix.
- Program to Multiply Two Matrix.
- Program to check Identity Matrix.
- Program to print Alternate Elements of an Array.
- Program to swap kth element from beginning to kth element from end in an Array.
- Program to print all possible subarrays of the given array.
- Program to print kth smallest and kth largest element of an Array.
- Program to find equilibrium index of an Array.
- Program to find majority element of an Array.
- Program to find mean of the Array.
- Program to sort an Array of 0s and 1s.