Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most occurring element in an array using c++?

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;
}
like image 318
Arun Pandey Avatar asked Dec 08 '22 12:12

Arun Pandey


1 Answers

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;
}
like image 57
hasan Avatar answered Dec 11 '22 00:12

hasan