Most occurring element in an array using c++? -


i had tried following code occurring element in array. working problem when there 2 or more elements having same number of occurrence , equal occurring element, shows first element scanned. please 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 elements: " << endl;     for(i=0;i<5;i++)     cin >> a[i];         (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 , change 2 line.

if (count>max_count)     max_count = count; 

with:

if (count==max_count)     cout << a[i] << endl; 

solution:

int a[5]; (int i=0;i<5;i++)    cin>>a[i];  int max_count = 0;  (int i=0;i<5;i++) {    int count=1;    (int j=i+1;j<5;j++)        if (a[i]==a[j])            count++;    if (count>max_count)       max_count = count; }  (int i=0;i<5;i++) {    int count=1;    (int j=i+1;j<5;j++)        if (a[i]==a[j])            count++;    if (count==max_count)        cout << a[i] << endl; } 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -