/* * Simple example of array -- compute variance. * * Recall that we can get input from a file with "I/O redirection", e.g., * * a.out < in.txt */ #include /* * define size of array using preprocessor directive: * compiler will replace "MAXSIZE" with "10" in code below * (artificially low for testing) */ #define MAXSIZE 10 /* convenience function to square a number */ double square(double d) { return d*d; } /* main program */ int main(void) { double sum = 0; double input; double a[MAXSIZE]; /* read in values and compute average */ printf("enter floating-point values (at most %d), anything else to end\n", MAXSIZE); int count = 0; /* keep calling scanf to read another value until it fails */ while ((count < MAXSIZE) && (scanf("%lf", &input) == 1)) { /* * make sure we don't overflow the array */ a[count] = input; sum += input; count++; } double average = sum/count; printf("sum is %g\n", sum); printf("average is %g\n", average); /* compute variance */ double variance_sum = 0.0; for (int i = 0; i < count; i++) { variance_sum += square(a[i]-average); } printf("variance sum is %g\n", variance_sum); printf("variance is %g\n", variance_sum/count); return 0; }