#include<iostream>
using namespace std;
/*Function Prototype*/
int getMode(int arr[], int size); //for getting the mode of a value
int main()
{
int Array[50]; //defining array of large size(50)
int size,index;
cout << "Enter the array size(should be between 1to50): ";
cin >> size;
while(size<1||size>50) //testing if the size is not in the range of 1 to 50
{
cout << "Wrong Input(should be between 1to50)!"
<< "\nEnter again: ";
cin >> size;
}
cout << "Enter the Array elements:\n";
for( int i=0 ; i<size ; i++ ) //for getting individual array elements
{
cout << "Enter element "
<< (i+1)
<< ": ";
cin >> Array[i];
}
index=getMode(Array,size); //calling function by passing array and its size
if( index==-1 ) //if array has no mode
cout << "\nAll the numbers exist the same number of times.\n";
else //if the array had a mode
{
cout << "\nThe number that occurs most often in the array is: "
<< Array[index]
<< endl;
}
return 0;
}
/*Functio Definition*/
int getMode(int arr[], int size)
{
int occur[50]; //array for getting the occurance of each element
int index=-1;
if(size==1) //if size is '1' then it is the only mode of the array
return 0;
//getting the occurance of each element
for( int i=0 ; i<size-1 ; i++ )
{
for( int j=i+1 ; j<size ; j++ )
{
if( arr[i]==arr[j] )
occur[i]+=1;
}
}
//checking if the array has a mode or not
for( int i=1 ; i<size ; i++ )
{
if( occur[i]!=occur[i-1] )
{
index=1;
break;
}
}
//will execute if the array has a mode
if(index==1)
{
index=0;
int large=occur[0];
//for getting the largest occurance
for( int j=1 ; j<size ; j++ )
{
if( occur[j]>large )
{
large=occur[j];
index=j; //stores the index of the element that has largest occurance
}
}
}
return index; //returns the index of the element that has largest occurance
}
No comments:
Post a Comment