0

I am continuing work on a program for analysis of an entered array, I have got min,max,median and sorting the array working with some input parameters. I cannot seem to get the mode to work, i have attempted some code to do this. Your help would be greatly appriciated, i am eager to learn how to accomplish these things.

Code:

```
#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: To 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--;
}
for(k = 0; k < sizeof a / sizeof a[0]; k++) /* for each datum */
{
++freq[a[k]]; /* track the frequency */
if(freq[a[k]] > mode) /* is this now the most common item? */
{
mode = a[k]; /* 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<< */
printf("Sorted List: ");
// 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;
}
//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]));
}
```

*Edited 3 Years Ago by Nick Evan*: Fixed formatting