Thread: Finding mode in array of numbers

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    1

    Finding mode in array of numbers

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

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    probably because array is array of floats, but lastnum and mode are ints. change them to floats.

    From statistics, mode is the most frequently occuring value. So the program should keep track of the number of times each value in array occurs, and you will need another array to do that. std::map<float,int> is good for that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. HELP:::MIX numbers in array
    By ypramesh in forum C Programming
    Replies: 9
    Last Post: 03-30-2006, 07:47 PM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Standard Deviation of an array of numbers...
    By Xenofizz in forum C++ Programming
    Replies: 4
    Last Post: 11-19-2003, 10:48 PM
  4. Finding the mode of an array
    By Shnakepup in forum C++ Programming
    Replies: 16
    Last Post: 05-16-2003, 10:01 AM
  5. mode of an array
    By Need Help in forum C Programming
    Replies: 15
    Last Post: 09-17-2001, 08:03 AM