Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I was wondering if you can help me with C++ programming? I have a mode function

ID: 3871231 • Letter: I

Question

I was wondering if you can help me with C++ programming?
I have a mode function but it only picks up one instance of a mode.
If i prove multiple modes with the same frequency, it still only picks up one mode.
I'm assuming I'll have to create an additional variable or an array to track any additional modes

int mode(int *mArray, int size)
{
int num = mArray[0];
int mode = num;
int count = 1;
int numMode = 1;
int i;
for(i=1; i < size; i++)
{
if(mArray[i] == num) //If the same as current value...
{
count++;
}
else
{
if(count > numMode)
{
numMode = count;
mode = num;
}
count = 1; //reset counter for new number
num = mArray[i];
}
}
cout << "mode: " << mode << endl;
}

Explanation / Answer

Solution==============

To get mode, we roughly do:

This indicates that, there has to be a for loop for choosing each array element, and another nested for loop for iterating over array to count it's occurence. You are missing the nested for loop, that's why you are getting wrong answers.

int mode(int *mArray, int size)
    {
  
int maxValue = 0, maxCount = 0, i, j;

   for (i = 0; i < size; ++i) {
      int count = 0;  
    
  
      //The missing nested loop
      for (j = 0; j < size; ++j) {
         if (mArray[j] == mArray[i])
         ++count;
      }
    
      if (count > maxCount) {
         maxCount = count;
         maxValue = a[i];
      }
   }
  
    cout << "mode: " << maxCount << endl;

   //The number having highest frequency
   return maxValue;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote