home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tyc / list18_3.c < prev    next >
C/C++ Source or Header  |  1993-10-16  |  982b  |  45 lines

  1.  /* Functions with a variable argument list. */
  2.  
  3.  #include <stdio.h>
  4.  #include <stdarg.h>
  5.  
  6.  float average(int num, ...);
  7.  
  8.  main()
  9.  {
  10.      float x;
  11.  
  12.      x = average(10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  13.      printf("\nThe first average is %f.", x);
  14.  
  15.      x = average(5, 121, 206, 76, 31, 5);
  16.      printf("\nThe second average is %f.", x);
  17.  }
  18.  
  19.  float average(int num, ...)
  20.  {
  21.      /* Declare a variable of type va_list. */
  22.  
  23.      va_list arg_ptr;
  24.      int count, total = 0;
  25.  
  26.      /* Initialize the argument pointer. */
  27.  
  28.      va_start(arg_ptr, num);
  29.  
  30.      /* Retrieve each argument in the variable list. */
  31.  
  32.      for (count = 0; count < num; count++)
  33.          total += va_arg( arg_ptr, int );
  34.  
  35.      /* Perform clean-up. */
  36.  
  37.      va_end(arg_ptr);
  38.  
  39.      /* Divide the total by the number of values to get the */
  40.      /* average. Cast the total to type float so the value */
  41.      /* returned is type float. */
  42.  
  43.      return ((float)total/num);
  44.  }
  45.