/************************************* ** proj2.c ** ** Dennis L. Frey ** November 11, 1998 ** ** This program reads positive integers from ** a file using Unix redirection. It counts ** the number of positive integers, finds the ** largest value, the smallest value and the ** average of all the integers. ** This program stops reading the file when ** -1 is found in the file. ** ** Assumptions -- there are only positive integers ** except for the terminating -1. there is at least ** one positive integer in the file ** ** Algorithm ** declare and initialize variables ** read the first positive integer ** while the value read is not -1 ** increment the count of positive integers ** add the value to the total ** if this value is larger than the largest so far ** make this value the largest ** else if this value is smaller than the smallest so far ** make this the smallest ** calculate the average ** print out the statistics ****************************************************/ #include #define SENTINEL -1 main ( ) { int count = 0; /* number of integers */ int largest; int smallest; int value; long sum = 0; /* sum of all the integers entered */ float average; printf ("Enter positive integers, one per line, -1 to quit\n"); scanf ("%d", &value); /* assume first value is not -1, so it can ** can be considered the largest and smallest */ largest = smallest = value; /* add each value to total ** increment count of positive ints ** check if its the largest ** check if its the smallest */ while (value != SENTINEL) { sum += value; count++; if (value > largest) { largest = value; } else if (value < smallest) { smallest = value; } /* now get the next value */ scanf ("%d", &value); } /* assume count >= 1; calc average */ average = (float)sum / count; /* print the statistics */ printf ("\n"); printf ("There were %d positive integers\n\n", count); printf ("The average is %0.2f\n", average); printf ("The maximum value is %d\n", largest); printf ("The minimum value is %d\n", smallest); printf ("The sum of the integers is %d\n", sum); printf ("\n"); }