Calculating an average using variable argument lists in C

Calculating an average using variable argument lists in C



#include
#include
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.5, 0.0));
printf("\n Average = %lf", average(1.0, 2.0, 0.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 average( double 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;
}



Related Links :

No comments:

Post a Comment


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!