Home > Programming > Functions using the "C" programming language > example34.c |
/*
In this example we demonstrate a function with variable number of
parameters.
*/
#include <stdio.h>
#include <stdarg.h>
#include <conio.h>
/*
Calculate the sum of variable number of integer parameters.
Last argument must be zero.
*/
int super_sum(int x,...)
{
int total = x;
va_list ap;
int arg;
va_start(ap, x);
while ((arg = va_arg(ap,int)) != 0)
{
total += arg;
}
va_end(ap);
return total;
}
/*
Calculate the sum of variable number of integer parameters.
We pass the number of parameters as the first function parameter.
*/
int super_sum2(int popularity,int x,...)
{
int total = x;
int i;
va_list ap;
va_start(ap, x);
for ( i=1; i<popularity; i++)
{
total += va_arg(ap,int);
}
va_end(ap);
return total;
}
int super_max(int x,...)
{
int max = x;
va_list ap;
int arg;
va_start(ap, x);
while ((arg = va_arg(ap,int)) != 0)
{
if(max<arg)
{
max=arg;
}
}
va_end(ap);
return max;
}
/*
Print variable number of integer parameters.
Last parameter must be zero.
*/
void print_ints(int x,...)
{
va_list ap;
int arg;
va_start(ap, x);
printf("%d ",x);
while ((arg = va_arg(ap,int)) != 0)
{
printf("%d ",arg);
}
printf("\n");
va_end(ap);
}
void main(void)
{
int sum1=super_sum(10,5,20,40,5,0);
int sum2=super_sum2(5,10,5,20,40,5);
int max=super_max(10,5,20,40,5,0);
printf("\nHere are some numbers :\n\n");
print_ints(10,5,20,40,5,0);
printf("\nfirst sum is %d\n",sum1);
printf("\nsecond sum is %d\n",sum2);
printf("\nmax is %d\n",max);
printf("press any key to continue ...\n");
getch();
printf("\nHere are some other numbers :\n\n");
print_ints(12,6,8,7,200,-1,2,3,4,89,7,9,0);
sum1=super_sum(12,6,8,7,200,-1,2,3,4,89,7,9,0);
sum2=super_sum2(12,12,6,8,7,200,-1,2,3,4,89,7,9);
max=super_max(12,6,8,7,200,-1,2,3,4,89,7,9,0);
printf("\nfirst sum is %d\n",sum1);
printf("\nsecond sum is %d\n",sum2);
printf("\nmax is %d\n",max);
getch();
}
© 2004 Jim Valavanis