/*****************************************************/ /* File: loop_exercise.c */ /* Author: Prof. Marron */ /* Date: March 26, 2014 */ /* Description: */ /* Computes the mean, variance, and std. deviation */ /* of a list of numbers. The user is prompted to */ /* enter the number of data items (n) and then is */ /* prompted to enter each item. Once all items */ /* have been entered, computes the mean, variance, */ /* and standard deviation and prints them out. */ /* */ /* Compile with gcc -Wall loop_exercise.c -lm */ /*****************************************************/ #include #include int main() { int i; /* loop variable */ int n; /* number of data items */ float data; /* data item */ float sumx; /* sum of data items */ float sumx2; /* sum of squared data items */ float mean; /* mean of the data */ float var; /* variance of the data */ float sd; /* std. deviation of data */ /* Get the number of data items from the user */ printf("How many numbers do you need to enter (n)? "); scanf("%d", &n); /* EXERCISE 1 */ /* The number of data items (n) must be positive. */ /* Use a while loop to ensure that the user enters */ /* a positive value. */ /* Initialization */ sumx = sumx2 = 0.0; /* Prompt the user to enter the data; compute the sum */ /* of the numbers and the sum of the squares of the */ /* numbers. */ i = 1; while (i <= n) { printf("Enter data item %d: ", i); scanf("%f", &data); sumx = sumx + data; sumx2 = sumx2 + (data*data); i = i + 1; } /* EXERCISE 2 */ /* The while loop above is counter-controlled and can */ /* be implemented more succinctly as a for loop. */ /* Re-write the loop as a for loop. */ /* EXERCISE 3 */ /* Modify the program so that it also computes and */ /* prints the maximum and minimum values entered. */ /* Compute the mean, variance, and std. deviation */ mean = sumx / n; var = 1.0/(n-1) * (sumx2 - (1.0/n)*sumx*sumx); sd = sqrt(var); /* print the computed values */ printf("\n"); printf(" mean = %f\n", mean); printf(" variance = %f\n", var); printf("std. dev. = %f\n\n", sd); }