Calculate an average using variable argument lists : Variable argument lists « Language « C Tutorial

Home
C Tutorial
1.Language
2.Data Type
3.String
4.printf scanf
5.Operator
6.Statement
7.Array
8.Function
9.Structure
10.Pointer
11.Memory
12.Preprocessor
13.File
14.Data Structure
15.Search Sort
16.Wide Character String
17.assert.h
18.ctype.h
19.math.h
20.setjmp.h
21.signal.h
22.stdio.h
23.stdlib.h
24.string.h
25.time.h
26.wctype.h
C / ANSI-C
C++
C++ Tutorial
Visual C++ .NET
C Tutorial » Language » Variable argument lists 
1.14.1.Calculate an average using variable argument lists
/*
Beginning C: From Novice to Professional, Fourth Edition

By Ivor Horton
ISBN: 1-59059-735-4
640 pp.
Published: Oct 2006
*/

#include <stdio.h>
#include <stdarg.h>

double average(double v1 , double v2,...);       /* Function prototype */

int main(void)
{
  double Val1 = 10.5, Val2 = 2.5;
  int num1 = 6, num2 = 5;
  long num3 = 12, num4 = 20;

  printf("\n Average = %lf", average(Val1, 3.5, Val2, 4.50.0));
  printf("\n Average = %lf", average(1.02.00.0));
  printf("\n Average = %lf\n", average( (double)num2, Val2,(double)num1,
                                      (double)num4,(double)num3, 0.0));
  return 0;
}

/* Function to calculate the average of a variable number of arguments */
double averagedouble v1, double v2,...)
{
  va_list parg;              /* Pointer for variable argument list */
  double sum = v1+v2;        /* Accumulate sum of the arguments    */
  double value = 0;          /* Argument value                     */
  int count = 2;             /* Count of number of arguments       */

  va_start(parg,v2);         /* Initialize argument pointer        */

  while((value = va_arg(parg, double)) != 0.0)
  {
    sum += value;
    count++;
  }
  va_end(parg);              /* End variable argument process      */
  return sum/count;
}
Average = 5.250000
      Average = 1.500000
      Average = 9.100000
1.14.Variable argument lists
1.14.1.Calculate an average using variable argument lists
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.