I am creating a program which performs statistical analysis of an array. So far i have got an enter array, that gives the min, max and median values and sorts the array. I have not been able to work out the mode. I have been able to find the mode on hardcoded array without the other analysis. Could anyone help me get the mode to work please.
This is the program as is now.

#include <stdio.h>
#include <stdlib.h>

#define N 100
#define MINVAL 0 /* the lowest allowable data value */ 
#define MAXVAL 100 /* the highest allowable data value */ 

int main()
{    
	int a[N] = {0};   
	int i, j, value, n;   
	
	int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency counts to 0. */ 
	size_t k = 0; /* loop counter */ 
	int mode = 0; /* for recording the modal value */ 
   
   	printf("Please enter array : \nTo end and sort array enter 0  \n");  
   
	// Upto 100 items can be created in a[i]   
	scanf("%d", &a[0]);    
	for(i = 1; i < N && a[i-1] < 100 && a[i-1] != 0; i++)      
 	{
 	// Input of the numbers into array a[i]   
	scanf("%d", &a[i]);  
 	}
	n = i;    
 
 	if(a[n-1] > 100) 
 	{    
  		printf("Number must be between 0 and 100");   
    	exit(1);   
	}   
 	
	 if (a[n-1] == 0) 
 	{       
		a[n-1] = 0;     
  		n--;    
  	}    
   
  	printf("Sorted List: \n");    
	 
 	// Simple insertion sort    
	for(i = 1; i < n; i++) 
	{        
 		value = a[i];       
	  	for (j = i - 1; j >= 0 && a[j] > value; j--)        
			a[j + 1] = a[j];       
		a[j + 1] = value;    
	}      
	
	for(i = 0; i < sizeof a / sizeof a[0]; i++) /* for each datum */ 
	{ 
		++freq[a[i]]; /* track the frequency */ 
		if(freq[a[i]] > mode) /* is this now the most common item? */ 
		{ 
		mode = a[i]; /* yes, so log it */ 
		} 
	} 
	printf("The modal value is %d which occurs %d time%s\n", 
		mode, 
		freq[mode], 
		freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */


	//Prints the sorted array    
	for(i = 0; i < n; i++)       
		printf("%d ", a[i]);     
	printf("\n");    
	printf("Min: %d\n", a[0]);    
	printf("Max: %d\n", a[n-1]);   
	printf("Median: %f\n", n % 2 ? a[n/2] : 0.5*(a[n/2] + a[n/2-1]));
	}

This is the code that can get the mode of an entered array.

#include <stdio.h> /* prototype for printf, and def of size_t */ 

#define MINVAL 0 /* the lowest allowable data value */ 
#define MAXVAL 42 /* the highest allowable data value */ 

int main(void) 
{ 
int data[] = { 0, 1, 2, 3, 4, 5, 3, 7 }; /* initialise the data array */ 
int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency 
* counts to 0. 
*/ 
size_t i = 0; /* loop counter */ 
int mode = 0; /* for recording the modal value */ 

for(i = 0; i < sizeof data / sizeof data[0]; i++) /* for each datum */ 
{ 
++freq[data[i]]; /* track the frequency */ 
if(freq[data[i]] > mode) /* is this now the most common item? */ 
{ 
mode = data[i]; /* yes, so log it */ 
} 
} 
printf("The modal value is %d which occurs %d time%s\n", 
mode, 
freq[mode], 
freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */ 

return 0; 
}

Your help would be greatly appriciated, i am eager to learn how to accomplish this.

Dani AI

Generated

A few practical points that add to what , and already discussed:

  • Use the actual number of entered items (your n) for any processing loops, not the full buffer size. That prevents counting unused (zero-initialized) slots as data.
  • Never index a frequency array without validating the value is inside the allowed range. If the input range is unknown or large, prefer a map/hash instead of a fixed-size frequency table.
  • Keep two clearly named variables: one for the highest frequency seen (maxfreq) and one (or a small list) for the value(s) that reach that frequency. Using a single variable for both count and value is fragile.

A robust approach that avoids a fixed-range frequency table is: sort the data, then scan once to find the longest run(s). Sorting makes the mode calculation simple and works for any integer values. Example function (expects the array already sorted):

/* find modes in sorted array a[0..n-1]
   returns number of distinct modes stored in 'modes' (up to max_modes)
   *mode_freq is set to the count for those modes (>=1) */
size_t find_modes_sorted(const int *a, size_t n, int *modes, size_t max_modes, size_t *mode_freq)
{
    if (n == 0) { *mode_freq = 0; return 0; }
    size_t best = 1, cur = 1, found = 0;
    int last = a[0];
    for (size_t i = 1; i < n; ++i) {
        if (a[i] == last) ++cur;
        else {
            if (cur > best) { found = 0; if (found < max_modes) modes[found] = last; ++found; best = cur; }
            else if (cur == best) { if (found < max_modes) modes[found] = last; ++found; }
            cur = 1; last = a[i];
        }
    }
    if (cur > best) { found = 0; if (found < max_modes) modes[found] = last; ++found; best = cur; }
    else if (cur == best) { if (found < max_modes) modes[found] = last; ++found; }
    *mode_freq = best;
    return found;
}

Practical tips: if all values are unique (mode_freq == 1) report "no mode" or treat every value as a mode depending on your definition; when inputs may include zero use a different sentinel or read a count/EOF; and for large or unknown ranges, use unordered_map<int,int> (C++) or a hash table to count frequencies in O(n) average time.

Recommended Answers

All 5 Replies

Yes, but i thought there was no harm in trying to get more help.

There's no harm in doing so if it eventually looks like you're doing something on your own rather than merely bombing forums waiting for some boob to finish your homework.

If you functionize your second chunk of code, it ought to work with a user-entered array. Such a conversion would seem trivial for the work you've already shown.

int mode(int *data, size_t size)
{
   /* Mostly copy and paste and changing hard-coded array size. */
}

[edit]Heh. Or just change the loop control:

for(i = 0; i < n; i++) /* for each datum */

Please use code tags!
When it is only one line of code I usually post them in bold.
Form your second code listing(just changed one value):
int data[] = { 0, 100, 2, 3, 4, 5, 3, 7 }; /* initialise the data array */
What would happen if the following code gets executed and data=100 ?
++freq[data]; /* track the frequency */

Thank you Dave, that seems to have sorted it, can't believe i missed changing the loop control.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.