I had tried the following code to get most occurring element in an array. It is working well but the only problem is when there are two or more elements having the same number of occurrence and equal to most occurring element, it just shows the first element scanned. Please help me through this.
#include <iostream>
using namespace std;
int main()
{
int i,j,a[5];
int popular = a[0];
int temp=0, tempCount, count=1;
cout << "Enter the elements: " << endl;
for(i=0;i<5;i++)
cin >> a[i];
for (i=0;i<5;i++)
{
tempCount = 0;
temp=a[i];
tempCount++;
for(j=i+1;j<5;j++)
{
if(a[j] == temp)
{
tempCount++;
if(tempCount > count)
{
popular = temp;
count = tempCount;
}
}
}
}
cout << "Most occured element is: " << popular;
}
Repeat solution twice and change two line.
if (count>max_count)
max_count = count;
with:
if (count==max_count)
cout << a[i] << endl;
Solution:
int a[5];
for (int i=0;i<5;i++)
cin>>a[i];
int max_count = 0;
for (int i=0;i<5;i++)
{
int count=1;
for (int j=i+1;j<5;j++)
if (a[i]==a[j])
count++;
if (count>max_count)
max_count = count;
}
for (int i=0;i<5;i++)
{
int count=1;
for (int j=i+1;j<5;j++)
if (a[i]==a[j])
count++;
if (count==max_count)
cout << a[i] << endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With