Hello,
I'm having a problem finding the mode of numbers in an array. Here's what I have so far - the problem is in the findMode function? findMode returns a number, but it's not the mode. No idea what it is. My brains are fried, I've spent way too much time on this program already. It's relatively simple, but I just can't figure it out.
Code:
#include <iostream>
using namespace std;
void userArray();
void showArray(float [], int);
float findMode(float [], int);
int main()
{
// Function for array of integers
float *values;
int size;
cout << "Enter size of array: ";
cin >> size;
cout << endl;
// dynamically generated
values = new float[size];
cout << "Enter " << size << " elements, one after the other." << endl;
for (int count = 0; count < size; count++)
{
cout << "Element " << (count + 1) << ": ";
cin >> values[count];
}
// Mode, show
cout << endl;
if (findMode(values, size) == -1)
{
cout << "No mode." << endl;
}
else
{
cout << findMode(values, size) << endl;
}
return 0;
}
float findMode(float *array, int elems)
{
int lastnum = array[0];
int curlen = 1;
int mode = array[0];
int modelen = 1;
for(int i = 1; i < elems; i++)
{
if (array[i] == lastnum)
curlen++;
else
{
if (curlen > modelen)
{
modelen = curlen;
mode = lastnum;
}
lastnum = array[i];
curlen = 1;
}
}
return mode;
}