/**** * * This program computes simple statistics for up to 1000 numbers read from * standard input. The program first asks for the number of values that the * statistics will be computed for. The program then reads in that many * values or 1000 values, whichever is smaller. * * The statistics computed are the sum of the numbers, arithmetic mean and the * standard deviation. The results are printed to standard output, in the * following form: * * Sum = * Mean = * Standard Deviation = * * The precise formulae for mean and standard deviation are as defined here: * * http://www.gcseguide.co.uk/statistics_and_probability.htm * * * Author: Gene Fisher (gfisher@calpoly.edu) * Created: 14apr11 * Last Modified: 14apr11 * */ #include #include #define MAX_DATA_POINTS 1000 int main () { int n; /* Number of values to compute stats for */ double x; /* Input value read from the terminal */ double sum; /* Computed sum */ double mean; /* Computed mean */ double sum_sq; /* Computed sum of squares, for std dev */ double std_dev; /* Computed standard deviation */ int i; /* Loop counter variable */ double data[MAX_DATA_POINTS]; /* Array to hold numbers */ /* * Input the number of values, and prompt for the rest of the data values. */ printf("Input the number of values you want to compute stats for: "); scanf("%d", &n); printf("Input the values, separated by whitespace: "); /* * Bounds check the input, and truncate to MAX_DATA_POINTS if necessary. * This is to ensure that we don't store values past the end of the array. */ if (n > MAX_DATA_POINTS) { printf("The program will use the first 1000 numbers only.\n"); n = MAX_DATA_POINTS; } /* * Initialize the sum to 0. */ sum = 0; /* * Initialize the loop counter to 0. */ i = 0; /* * Loop until all the values are read in, accumulating the sum as we go. * Note that the loop will not go at all if the user enters a non-positive * value for the number of data points. */ while (i < n) { /* * Input the next value. */ scanf("%lf", &x); /* * Put the value into the array. */ data[i] = x; /* * Increment the sum. */ sum = sum + x; /* * Increment the loop counter, so we'll stop after n inputs. */ i = i + 1; } /* * Compute the mean. */ mean = sum / n; /* * Compute the standard deviation. This computation is the whole reason * for using the array. That is, the formula we're using for standard * deviation requires both the mean and each of the data points. So the * computational strategy here is as follows: * (1) Read the values from stdin, computing the sum as we go. * (2) Also store each value in an array as we go. * (3) Compute the mean once all the values are read in. * (4) Compute the standard deviation */ for (i = 0, sum_sq = 0; i < n; i++) { sum_sq += pow(data[i] - mean, 2); } std_dev = sqrt(sum_sq / (n - 1)); /* * Output the results. */ printf("Sum = %f\n", sum); printf("Mean = %f\n", mean); printf("Standard Deviation = %f\n", std_dev); return 0; }