Find The Most Frequent Element in an Array
#include<bits/stdc++.h>
using namespace std;
void frequent_element(int arr[], int n) {
int i, j, max_count = 0;
cout << "\nMost occurred number: ";
for (i = 0; i < n; i++) {
int count = 1;
for (j = i + 1; j < n; j++) if (arr[i] == arr[j]) count++; if (count > max_count)
max_count = count;
}
// this loop checks if there are more than one elements that are repeated
for (i = 0; i < n; i++) {
int count = 1;
for (j = i + 1; j < n; j++)
if (arr[i] == arr[j])
count++;
if (count == max_count)
cout << arr[i] << endl;
}
}
int main() {
int arr[100], n, i;
cout << "Enter size of the array: "; cin >> n;
cout << "\nEnter elements in the array: \n";
for (i = 0; i < n; i++) {
cout << "Enter Element " << i + 1 << ":"; cin >> arr[i];
}
cout << "Original array: ";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
frequent_element(arr, n);
return 0;
}
Output:
Enter size of the array: 8
Enter elements in the array:
Enter Element 1: 3
Enter Element 2: 43
Enter Element 3: 2
Enter Element 4: 3
Enter Element 5: 21
Enter Element 6: 3
Enter Element 7: 43
Enter Element 8: 5
Entered Array: 3 43 2 3 21 3 43 5
Most occurred number: 3
