I'm quite new with C++ and trying to write a program at which I should:
- take 20 numbers from the user,
- putting them in an array,
- writing a function to find the most repeated element,
- returning the most repeated element,
- printing it in the main function.
For that purpose I wrote the below code, but the output is the last number which is entered regardless to whether it's the most repeated one or not.
#include<iostream.h>
#include<conio.h>
using namespace std ;
int maxi ( long a[] , int size )
{
int i , j , k=1 , max=0 , m ;
for (i=1 ; i<=size ; i++)
{
for (j=1 ; j<20 ; j++)
{
if (a[i] == a[j+1])k=k+1 ;
}
if (max<k){ max = k ; m=a[i] ;}
}
return m ;
}
int main ()
{
const int size=20 ;
long a[size] ;
cout << " Please Enter the elements of your aray " << endl ;
for (int i=1 ; i<=size ; i++ )
{
cout << "a["<<i<<"] : " ;
cin >> a[i] ;
}
cout << "The number which does have the most repitition is : "<<maxi (a,size) ;
getch() ;
return 0 ;
}
I don't really understand what's wrong here. I would really appreciate it if anyone can help me to figure out what should change here.