The code has 2 somewhat serious problems, and 2 other oddities:
1) it leaks memory (there is a new[], but no matching delete[])
2) it attempts to do a direct compare of floating point values, which is unreliable. You shouldn't use == or != operators with floats/doubles because exact comparison is sketchy due to the nature of how floating points work.
3) Also a minor goof. I assume the 2nd parameters passed was supposed to be 'n', not 'i'.
4) Another oddity is that the function returns a double, but the return value is completely meaningless (always returns zero). It would have made much more sense for the mode to be returned instead of being printed.
double mode (int numbers [], int n)
{
// Create an array to count how many times each element has been repeated in the array
int* Repetition = newint[n];
// for each element in the array....
for (int i = 0; i < n; ++i)
{
// reset its repition value to zero
Repetition[i] = 0;
int j = 0;
// bool bFound = false; <- this is worthless and never used
// we now want to see if this element is a duplicate of an element already in the array.
// 'j' will hold the index to the first element that matches this element.
// loop until j==i (i is the current element)
// and EXIT the loop if we find that the number has repeated
while ((j < i) && (numbers[i] != numbers[j]))
{
if (numbers[i] != numbers[j])
{
++j;
}
}
// end result: numbers[j] == numbers[i]
// and: j is the lowest possible index which satisifes above condition.
// if this is the first occurance of a number in the series, then j==i
// the loop is a little confusing. I probably would have written it like this:
/*
for(int j = 0; j < i; ++j)
{
if( numbers[i] == numbers[j] )
break;
}
*/
// add 1 repetion to j. If this number has been repeated, then this tallies
// the original occurance of the number. Duplicates of the number will have a tally of 0
++(Repetition[j]);
}
// now we know how many times each number is repeated in the array.
// So this loop just finds which number has been repeated most
int mode = 0; // 'mode' is a little misleading. It's actually the index to the mode, not the mode itself.
// mode starts at 0. Now check each tally after 0:
for (int i = 1; i < n; ++i)
{
// 'mode' is the highest tally we've seen so far
// if this tally is higher, then make it our new highest
if (Repetition[i] > Repetition[mode])
{
mode= i;
}
}
// now 'mode' is the index to the number repeated most often.
// therefore 'numbers[mode]' is the mode
cout << "Mode\t\t\t\t"<< numbers[mode]<<endl<<endl;
// I added this. It should really be here to avoid memory leaks:
delete[] Repetition;
return 0;
}