Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to calculate the average of N number using variadic function (va_arg) in C

2 Answers

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

enum { VA_END = -1 };

int average_of_N_numbers(int first, ...) {
    va_list args;
    va_start(args, first);

    unsigned int count = 0;
    int sum = 0;

    int next_number = first;
    while (next_number != VA_END) {
        sum += next_number;
        count++;
        next_number = va_arg(args, int);
    }

    va_end(args);
    return count ? (sum / count) : 0;
}

int main() {
    int avg = average_of_N_numbers(1, 5, 7, 9, 3, 2, 8, VA_END);

    printf("%d", avg);

    return 0;
}




/*
run:

5

*/

 



answered Apr 23, 2022 by avibootz
edited Apr 23, 2022 by avibootz
0 votes
#include <stdio.h>
#include <stdarg.h>

double average_of_N_numbers(int first, ...) {
    va_list args;
    va_start(args, first);

    unsigned int count = 0;
    double sum = 0.0f;

    for (int i = 0; i < first; i++) {
        double next_number = va_arg(args, double);
        sum += next_number;
        count++;
    }

    va_end(args);
    return count ? (sum / count) : 0;
}

int main() {
    double avg = average_of_N_numbers(7, 1.4f, 5.2f, 7.1f, 9.3f, 4.8f, 2.1f, 8.6f);

    printf("%lf", avg);

    return 0;
}




/*
run:

5.500000

*/

 



answered Apr 23, 2022 by avibootz
...