/* * Program to compute variance of integers from stdin (example of using * array). */ #include /* make array size a named constant so it's easy to change */ #define ASIZE 100 /* "macro" -- compile-time function (compiler expands) */ #define SQUARE(x) (x)*(x) int main(void) { printf("enter integers, anything else to stop\n"); int nums[ASIZE]; int n; int count = 0; /* how many elements have been read */ int sum = 0; /* sum of elements so far */ /* read input and compute count and sum */ while (scanf("%d", &n) == 1) { if (count >= ASIZE) { printf("too much input -- max of %d\n", ASIZE); return 1; } nums[count] = n; count += 1; sum += n; } /* compute average */ double avg = (double) sum / (double) count; printf("avg %f\n", avg); /* * compute variance: * * average of sum of (nums[i] - avg)**2 */ double vsum = 0.0; for (int i = 0; i < count; ++i) { /* printf("diff %f sq %f\n", nums[i]-avg, SQUARE(nums[i]-avg)); */ vsum += SQUARE(nums[i] - avg); } printf("variance %f\n", vsum / count); return 0; }