Solved

Finding the mode in a array

Posted on 2006-11-07
12
555 Views
Last Modified: 2010-05-18
Hi Experts,

I hace this program that I've been working on for several hours now and just can't figure out how to
find the mode in the array. I can display the average, total, and median, but just can't seem to code
correctly for the mode of the values.

Can someone please show me a code sample using my program of how it's done.

The program is used to gather statistical data for a survey about the number of movies college students see in a month.

Thanks for your help guys.

0
Comment
Question by:manz2
  • 6
  • 5
12 Comments
 

Author Comment

by:manz2
ID: 17890432
I forgot to to show my program:




#include <iostream>
#include <iomanip>
using namespace std;
 
void readem(int * & number, int &quant)
//          OUT             OUT
// This function reads the data and returns it in an array along with
// the quantity of elements read.
{
    // Find out how many numbers there will be and allocate space
    cout << "\nHow many students took the survey? ";
    cin >> quant;

    // Allocate appropriate amount of space
    number = new int[quant];

    // Read numbers and put them into list
    for(int i=0; i<quant; i++)
    {
            cout << "\nNumber of movies for student # " << i+1 << "? ";
        cin >> number[i];
    }

    return;
}



int sum(const int array[], int num)
//      IN                 IN
// This function calculates the sum of the array with 'num' elements.
{
    int total=0;

   for(int i=0; i < num; i++)
        total += array[i];

    return total;
}
   
float median(const int array[], int num)
//           IN                 IN
// This function calculates the average, or geometric mean of the array.
// The array contains 'num' elements.  NOTE: no error checking is done.
// If the array has an odd number of elements the median is the element in
// the middle position; otherwise it is the average of the two elements
// closest to the middle.
{
     float middle;
 
     if ( (num % 2) == 1)
       middle = float(array[num/2]);
     else
        middle = (array[num/2] + array[num/2 - 1]) / 2.0;

    return middle;
}


int main()
{
    int * number;  //Pointer to array to hold values
    int num = 0;       //Quantity of values read
    int total;

    // Read data and store in array
    readem(number, num);
 
    // Call functions to get mean and median and display results.
 
    total = sum(number, num);
 
    cout  << "\nSum = " << total << endl;
    cout << "\nAverage = " << float(total)/num << endl;
    cout << "\nMedian  = " << median(number, num) << endl;
 
     // Return space to free store
     delete[] number;  
 
    return 0;
}
0
 
LVL 14

Expert Comment

by:wayside
ID: 17891040
Your program seems to be assuming the array is sorted (otherwise your median function is incorrect).

So, if it is sorted, walk through the whole array and count how many times a number repeats (that is, the same number is in two of more consecutive array locations). Keep track of which number has repeated the most, that is the mode.

Full code cannot be provided as this is clearly homework, however if you post your attempt we can help you fix any problems.

0
 
LVL 14

Expert Comment

by:wayside
ID: 17891057
Note, if the array is not sorted, you should sort it before calculating the mode and median. Look up a bubble sort for an easy way to sort.
0
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 20 total points
ID: 17891899
>>>> Your program seems to be assuming the array is sorted

The array isn't sorted cause the values must be entered by the user in main().

You can sort the array after it is entered by using std::vector and std::sort:

#include <vector>
#include <algorithm>


          // put your array to a std::vector
          std::vector<int> v(&number[0], &number[quant]);  

          std::sort(v.begin(), v.end());

If the array is sorted you easily can determine the mode iterating the array and counting the longest sequence of equal numbers.

Regards, Alex

0
 

Author Comment

by:manz2
ID: 17892487
Hi again experts!

I made changes to my program using samples from the book, but when I added the findMode (function) i got errors when compiling. Such as  float to int, possible loss of data, a a couple other can you please tell me what I need to change to get this working.

Thank you all for your help on this.
0
 

Author Comment

by:manz2
ID: 17892500
Here is the program again with the changes:

#include <iostream>
#include <iomanip>
using namespace std;
 
void readem(int * & number, int &quant)
//          OUT             OUT
// This function reads the data and returns it in an array along with
// the quantity of elements read.
{
    // Find out how many numbers there will be and allocate space
    cout << "\nHow many students took the survey? ";
    cin >> quant;

    // Allocate appropriate amount of space
    number = new int[quant];

    // Read numbers and put them into list
    for(int i=0; i<quant; i++)
    {
            cout << "\nNumber of movies for student # " << i+1 << "? ";
        cin >> number[i];
    }

    return;
}



int sum(const int array[], int num)
//      IN                 IN
// This function calculates the sum of the array with 'num' elements.
{
    int total=0;

   for(int i=0; i < num; i++)
        total += array[i];

    return total;
}
   
float median(const int array[], int num)
//           IN                 IN
// This function calculates the average, or geometric mean of the array.
// The array contains 'num' elements.  NOTE: no error checking is done.
// If the array has an odd number of elements the median is the element in
// the middle position; otherwise it is the average of the two elements
// closest to the middle.
{
     float middle;
 
     if ( (num % 2) == 1)
       middle = float(array[num/2]);
     else
        middle = (array[num/2] + array[num/2 - 1]) / 2.0;

    return middle;
}

void sortArray(int array[], int elems)
{
      int temp;
      bool swap;

      do
      {
            swap = false;
            for (int count = 0; count < (elems - 1); count++)
            {
                  if (array[count] > array[count +1])
                  {
                        temp = array [count];
                        array[count] = array[count+1];
                        array[count +1] = temp;
                        swap = true;
                  }
            }
      } while (swap);
}



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 ;
}


int main()
{
    int * number;  //Pointer to array to hold values
    int num = 0;       //Quantity of values read
    int total;

    // Read data and store in array
    readem(number, num);
 
    // Call functions to get mean and median and display results.
 
    total = sum(number, num);

      sortArray(number, num);

    cout  << "\nSum = " << total << endl;
    cout << "\nAverage = " << float(total)/num << endl;
      cout << "\nMode = " << findMode (number, num) << endl;
    cout << "\nMedian  = " << median(number, num) << endl;
 
     // Return space to free store
     delete[] number;  
 
    return 0;
}
0
 
LVL 14

Expert Comment

by:wayside
ID: 17892744
float findMode(float *array, int elems)
{
        int lastnum = array[0];   <---------------- your array holds floats, so you should declare lastnum as a float
        int curlen = 1;
        int mode = array[0];      <---------------- same here
        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 ; <----------------------------- your function is declared as returning a float, so you must return something here.
}
0
 
LVL 14

Expert Comment

by:wayside
ID: 17892797
Actually I have it backward.

Your input is stored in an array of ints,so that is what you must pass into the findMode function:

float findMode(float *array, int elems)  <------------ pass in an integer array like in the sum function
{
        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 ; <------------------------- return the mode as the output
}
0
 

Author Comment

by:manz2
ID: 17893107
I did as you said:

float findMode(const int 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 0;
}


But as I compile, I get this error:

: warning C4244: '=' : conversion from 'double' to 'float', possible loss of data
0
 
LVL 14

Accepted Solution

by:
wayside earned 480 total points
ID: 17893403
What is happening is that you declared the function to return a float, but you are returning 0, which is a constant. So the constant is considered a double, and when casting a double to a float (since you are returning a float) you get that warning, since a double uses  64 bits and and float only 32 bits.

Since your array contains only ints, you should return an int:

int findMode(const int array[], int elems)  

and then return the mode that you have found, instead of 0:

  return mode;


If you still want a float returned, you can still do

  return mode;

or cast it to make it explicit that this is what you want:

  return (float) mode;



0
 

Author Comment

by:manz2
ID: 17894030
Thanks Wayside so much.

It worked perfectly. I gave you 480 points and I gave the other person 20 points for trying to help me also, I hope that's okay?
I try to be fair.

I appreciate your help and maybe I'll continue getting help from you since I have a couple of small projects I want to work on this week to continue learning.

Thanks again.
0
 
LVL 14

Expert Comment

by:wayside
ID: 17895127
Glad I could help!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question