954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Mode of an array in C

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
#include

#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]));
}

willingj
Newbie Poster
1 post since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

What you want from us to do from this crapy code. No code tags, no comments.

Please put code tags and comments in your code.

Luckychap
Posting Pro in Training
444 posts since Aug 2006
Reputation Points: 83
Solved Threads: 61
 

use two fors for sort i=0 to n-1 j=i+1 to n

akulkarni
Junior Poster
111 posts since Jun 2009
Reputation Points: 11
Solved Threads: 4
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You