LearnFrenzy
Sign in Take a free test

Variable Number of Arguments · Variable Argument Programs · Question 2

Minimum and maximum of n doubles with va_arg in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Write range(n, ...) that finds the smallest and largest of n double values and returns them through pointer parameters placed before the ellipsis.

Solution
main.c
#include <stdarg.h>
#include <stdio.h>

void range(double *lo, double *hi, int n, ...) {
    va_list ap;
    va_start(ap, n);
    *lo = *hi = va_arg(ap, double);
    for (int i = 1; i < n; i++) {
        double v = va_arg(ap, double);
        if (v < *lo) *lo = v;
        if (v > *hi) *hi = v;
    }
    va_end(ap);
}

int main(void) {
    double lo, hi;
    range(&lo, &hi, 5, 36.6, 39.1, 35.9, 37.2, 38.0);
    printf("min %.1f, max %.1f, spread %.1f\n", lo, hi, hi - lo);
    return 0;
}

Output Verified by compiling and running

min 35.9, max 39.1, spread 3.2

All values are written as double literals (36.6, not 36), because the function reads them with va_arg(ap, double).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links