Asked by: Umar Khan | Category: C++ ( c plus plus ) | CPP program to count frequency of elements in an array
#include <bits/stdc++.h>
using namespace std;
void countFreqOfElement(int arr[], int n){
vector<bool> visited(n, false);
for (int i = 0; i < n; i++) {
if (visited[i] == true)
continue;
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
cout<< "\n" <<arr[i] <<" occured ->" << count <<" times" << endl;
}
}
int main(){
int n;
cout<< "Enter the number of elements: ";
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cout<< "Enter "<<i+1 <<"th element: ";
cin>>arr[i];
}
cout << "\nThe array is:";
for(int i=0; i<n; i++){
cout << " "<<arr[i];
}
countFreqOfElement(arr, n);
return 0;
}
Comments