Chapter 9 Mode Function

/*8. Mode Function
In statistics, the mode of a set of values is the value that occurs most often or with the greatest frequency. Write a function that accepts as arguments the following:
A) An array of integers
B) An integer that indicates the number of elements in the array
The  function  should  determine  the  mode  of  the  array.  That  is,  it  should  determine which value in the array occurs most often. The mode is the value the function should return.  If  the  array  has  no  mode  (none  of  the  values  occur  more  than  once),  the function should return -1. (Assume the array will always contain nonnegative values.) Demonstrate your pointer prowess by using pointer notation instead of array notation in this function.*/

#include “stdafx.h”
#include<iostream>

using namespace std;
int mode(int* ,int );

int main()
{
int * number,size;
cout<<“\nEmter the number of integers: “;
cin>>size;
number=new int[size];

for(int i=0;i<size;i++)
{
cout<<“\nEnter the “<<i+1<<” number: “;
cin>>number[i];
}

int theMode=mode(number,size);

if(theMode==-1) cout<<“\nThere is no mode of these numbers.”<<endl;
else cout<<“\nThe mode of these numbers is “<<theMode<<endl;
system(“pause”);
return 0;
}

int mode(int* number,int size)
{
int* frequency=new int[size];

for(int i=0;i<size;i++)
{
frequency[i]=0;
for(int x=0;x<size;x++)
if(number[i]==number[x])frequency[i]++;
}

int maxF=frequency[0];
int mode;

for(int y=1;y<size;y++)
{
if(frequency[y]>=maxF)
{
maxF=frequency[y];
mode=number[y];

}
}

if(mode==0) mode=-1;
return mode;
}

 

2 thoughts on “Chapter 9 Mode Function

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s