Write a variadic function that takes a count followed by that many integers and reports their sum and average.
#include <stdarg.h>
#include <stdio.h>
void report(int count, ...) {
if (count <= 0) {
printf("no values\n");
return;
}
va_list ap;
va_start(ap, count);
long sum = 0;
for (int i = 0; i < count; i++)
sum += va_arg(ap, int);
va_end(ap);
printf("%d values: sum %ld, average %.2f\n", count, sum, (double) sum / count);
}
int main(void) {
report(4, 70, 85, 90, 66);
report(2, -5, 6);
report(0);
return 0;
}
4 values: sum 311, average 77.75 2 values: sum 1, average 0.50 no values
The count comes first so the function knows when to stop. va_start is called only when there is something to read.