Re: Could someone explain how the below c++ code works....??
Originally Posted by mrexp21
Code to determine mode .
1) Your question is not specific to Visual C++. It should have been posted in the non-Visual C++ forum.
2) Use code tags when posting code. The code you posted is unformatted and almost unreadable. Look here:
Code:
double mode (double numbers [], int i)
{
int* Repetition = new int[n];
for (int i = 0; i < n; ++i)
{
Repetition[i] = 0;
int j = 0;
bool bFound = false;
while ((j < i) && (numbers[i] != numbers[j]))
{
if (numbers[i] != numbers[j])
{
++j;
}
}
++(Repetition[j]);
}
int mode = 0;
for (int i = 1; i < n; ++i)
{
if (Repetition[i] > Repetition[mode])
{
mode= i;
}
}
cout << "Mode\t\t\t\t"<< numbers[mode]<<endl<<endl;
return 0;
}
See how that looks?
3) The person that wrote this code needs to learn proper C++ handling of dynamically allocated memory. The function leaks memory as there is no call to delete[].
4) Where did the "n" come from here?
Code:
int* Repetition = new int[n];
It isn't declared anywhere. So no one can tell you how the function works, since it can't be compiled due to syntax errors.
Did you mean this?
Code:
double mode (double numbers [], int i) // should the "i" be really "n"?
If so, then you must have attempted to type in your code when you posted your message. Don't type in your code -- copy and paste the code from your editor into the message.
Regards,
Paul McKenzie
Last edited by Paul McKenzie; May 28th, 2012 at 11:50 PM.
Bookmarks