...

/

Solution Review: Calculate the Average of Any Number of Integers

Solution Review: Calculate the Average of Any Number of Integers

Follow the step-by-step instructions to calculate the average of any number of integers.

We'll cover the following...

Solution

Press the RUN button and see the output!

Press + to interact
#include <stdio.h>
#include <stdarg.h>
int getAverage ( int count, ... );
int main( )
{
int avg1, avg2 ;
avg1 = getAverage ( 5, 10, 20, 30, 40, 50 ) ;
avg2 = getAverage ( 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) ;
printf ( "Average of 5 nos. = %d\n", avg1 ) ;
printf ( "Average of 10 nos. = %d\n", avg2 ) ;
return 0 ;
}
int getAverage ( int count, ... )
{
va_list ptr ;
int num, nos, sum, i, avg ;
va_start ( ptr, count ) ;
num = va_arg ( ptr, int ) ;
sum = num ;
for ( i = 1 ; i < count ; i++ )
{
num = va_arg ( ptr, int ) ;
sum = sum + num ;
}
avg = sum / count ;
return ( avg ) ;
}

Explanation

In the statement, va_start ( ptr, ...