LearnFrenzy
Sign in Take a free test

Variable Number of Arguments · Variable Argument Programs · Question 7

Evaluate a polynomial with variadic coefficients in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Write poly(x, degree, ...) that takes degree + 1 coefficients (highest power first) as doubles and evaluates the polynomial with Horner's method.

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

double poly(double x, int degree, ...) {
    va_list ap;
    va_start(ap, degree);
    double result = 0;
    for (int i = 0; i <= degree; i++)
        result = result * x + va_arg(ap, double);   /* Horner: ((a)x + b)x + c ... */
    va_end(ap);
    return result;
}

int main(void) {
    /* 2x^3 - 6x^2 + 2x - 1 */
    for (int x = 0; x <= 3; x++)
        printf("p(%d) = %g\n", x, poly(x, 3, 2.0, -6.0, 2.0, -1.0));
    return 0;
}

Output Verified by compiling and running

p(0) = -1
p(1) = -3
p(2) = -5
p(3) = 5

Horner's method needs only one multiplication and one addition per coefficient. The coefficients are passed as double literals to match 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