Download this source file


/* Average.c - A program to read in up to 100 positive integers, and print a
 * list of all integers greater than the average.  Input ends when the user
 * enters a negative value.  Note the descriptive parameter names in the
 * prototype, and the different names used in the function definition.
 * Also note the use of the symbolic constant "MAX_NUM_VALUES".  Finally the
 * use of the assert macro is ilustrated; to turn off checking un-comment out
 * the line defining NDEBUG.
 *
 * Written by Wayne Pollock, Tampa Florida USA 2001.
 */

#include <stdio.h>

//#define NDEBUG     // Turn off assertion testing if defined.
#include <assert.h>

#define MAX_NUM_VALUES 100

float average ( int number_of_values, int array_of_values[] );

int main( void )
{
   float ave;
   int i, num_of_vals = 0, value[MAX_NUM_VALUES];

   for ( ;; )
   {
      fprintf( stderr, "Enter a positive integer (-1 to quit): " );
      if ( (scanf("%i", &value[num_of_vals]) != 1) || (value[num_of_vals] < 0) )
         break;
      ++num_of_vals;
      if ( num_of_vals >= MAX_NUM_VALUES )
         break;
   }
   if ( num_of_vals == 0 )
   {  fprintf(stderr, "\a\n\tNo values entered!\n");
      return 0;  // Comment out this line to test the assert code.
   }
   ave = average( num_of_vals, value );
   fprintf( stderr, "\nAverage of %i values is: %.1f\n", num_of_vals, ave );
   fprintf( stderr, "\nValues greater than average:\n\n" );
   for  (i=0; i < num_of_vals; ++i )
      if ( value[i] > ave )
         printf("\t%5i\n", value[i]);
   return 0;
}

/* Returns the arithmetic average of val[0]..val[num_of_vals - 1].  Note that num_of_vals
 * must not be zero (it is tested in main), and assert is used to verify this.
 */
float average (int num_of_vals, int val[])
{
   int i;
   float sum = 0.0;  /* use float to correctly compute the average */

   assert( num_of_vals > 0 );  /* abort the program if this isn't true. */
   for ( i=0; i<num_of_vals; ++i )
      sum += val[i];
   return sum / num_of_vals;
}

#ifdef COMMENTED_OUT   /* Output of above Program follows */
Enter a positive integer (-1 to quit): 1
Enter a positive integer (-1 to quit): 2
Enter a positive integer (-1 to quit): 3
Enter a positive integer (-1 to quit): 4
Enter a positive integer (-1 to quit): -1

Average of 4 values is: 2.5

Values greater than average:

            3
            4
#endif




Send comments and mail to pollock@acm.org.