Evaluate Polynomial Expressions in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to evaluate polynomial expressions in C programming. The lab covers the following steps: reading polynomial coefficients and the variable x from user input, and using Horner's method to efficiently evaluate the polynomial expression. By the end of this lab, you will have a better understanding of working with algebraic expressions in C and implementing an effective polynomial evaluation algorithm.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435177{{"`Evaluate Polynomial Expressions in C`"}} c/variables -.-> lab-435177{{"`Evaluate Polynomial Expressions in C`"}} c/if_else -.-> lab-435177{{"`Evaluate Polynomial Expressions in C`"}} c/for_loop -.-> lab-435177{{"`Evaluate Polynomial Expressions in C`"}} c/user_input -.-> lab-435177{{"`Evaluate Polynomial Expressions in C`"}} c/math_functions -.-> lab-435177{{"`Evaluate Polynomial Expressions in C`"}} end

Read Coefficients and Variable x

In this step, you will learn how to read polynomial coefficients and the variable x from user input in a C program. This is the first part of implementing a polynomial evaluation algorithm.

First, create a new C file for the polynomial evaluation program:

cd ~/project
nano polynomial_eval.c

Now, add the following code to read coefficients and variable x:

#include <stdio.h>

#define MAX_DEGREE 10

int main() {
    int degree;
    double coefficients[MAX_DEGREE + 1];
    double x;

    // Read the degree of the polynomial
    printf("Enter the degree of the polynomial (0-10): ");
    scanf("%d", &degree);

    // Read coefficients
    printf("Enter coefficients from highest degree to constant term:\n");
    for (int i = degree; i >= 0; i--) {
        printf("Coefficient for x^%d: ", i);
        scanf("%lf", &coefficients[i]);
    }

    // Read the value of x
    printf("Enter the value of x: ");
    scanf("%lf", &x);

    return 0;
}

Example output:

Enter the degree of the polynomial (0-10): 3
Enter coefficients from highest degree to constant term:
Coefficient for x^3: 2
Coefficient for x^2: -3
Coefficient for x^1: 0
Coefficient for x^0: 5
Enter the value of x: 2

Let's break down the code:

  • We define a maximum degree for the polynomial to prevent buffer overflow
  • degree stores the polynomial's degree
  • coefficients array stores the coefficients from highest degree to constant term
  • x stores the value at which we'll evaluate the polynomial
  • We use scanf() to read user inputs for degree, coefficients, and x value

Compile and run the program to test input:

gcc polynomial_eval.c -o polynomial_eval
./polynomial_eval

Use Horner's Method for Evaluation

In this step, you will implement Horner's method to efficiently evaluate polynomial expressions. Horner's method reduces the number of multiplications needed to compute polynomial values.

Open the previous C file and modify it to include the Horner's method evaluation:

cd ~/project
nano polynomial_eval.c

Update the code with the Horner's method implementation:

#include <stdio.h>

#define MAX_DEGREE 10

double hornerMethod(int degree, double coefficients[], double x) {
    double result = coefficients[degree];

    for (int i = degree - 1; i >= 0; i--) {
        result = result * x + coefficients[i];
    }

    return result;
}

int main() {
    int degree;
    double coefficients[MAX_DEGREE + 1];
    double x, result;

    // Previous input code remains the same
    printf("Enter the degree of the polynomial (0-10): ");
    scanf("%d", &degree);

    printf("Enter coefficients from highest degree to constant term:\n");
    for (int i = degree; i >= 0; i--) {
        printf("Coefficient for x^%d: ", i);
        scanf("%lf", &coefficients[i]);
    }

    printf("Enter the value of x: ");
    scanf("%lf", &x);

    // Evaluate polynomial using Horner's method
    result = hornerMethod(degree, coefficients, x);

    printf("Polynomial value at x = %.2f is: %.2f\n", x, result);

    return 0;
}

Compile and run the updated program:

gcc polynomial_eval.c -o polynomial_eval
./polynomial_eval

Example output:

Enter the degree of the polynomial (0-10): 3
Enter coefficients from highest degree to constant term:
Coefficient for x^3: 2
Coefficient for x^2: -3
Coefficient for x^1: 0
Coefficient for x^0: 5
Enter the value of x: 2
Polynomial value at x = 2.00 is: 11.00

Let's break down Horner's method:

  • The function hornerMethod() takes degree, coefficients, and x as parameters
  • It starts with the highest degree coefficient
  • Iteratively multiplies the current result by x and adds the next coefficient
  • Reduces computational complexity from O(n²) to O(n)

The method efficiently evaluates polynomials like 2x³ - 3x² + 0x + 5 at x = 2.

Print the Result

In this final step, you will enhance the polynomial evaluation program by adding formatted output and error handling to improve the user experience.

Open the previous C file and update it with improved result printing:

cd ~/project
nano polynomial_eval.c

Update the code with formatted result printing and input validation:

#include <stdio.h>

#define MAX_DEGREE 10

double hornerMethod(int degree, double coefficients[], double x) {
    double result = coefficients[degree];

    for (int i = degree - 1; i >= 0; i--) {
        result = result * x + coefficients[i];
    }

    return result;
}

void printPolynomial(int degree, double coefficients[]) {
    printf("Polynomial: ");
    for (int i = degree; i >= 0; i--) {
        if (coefficients[i] != 0) {
            if (i == degree) {
                printf("%.2fx^%d ", coefficients[i], i);
            } else if (i > 1) {
                printf("%+.2fx^%d ", coefficients[i], i);
            } else if (i == 1) {
                printf("%+.2fx ", coefficients[i]);
            } else {
                printf("%+.2f", coefficients[i]);
            }
        }
    }
    printf("\n");
}

int main() {
    int degree;
    double coefficients[MAX_DEGREE + 1];
    double x, result;

    // Input validation
    do {
        printf("Enter the degree of the polynomial (0-10): ");
        scanf("%d", &degree);
    } while (degree < 0 || degree > MAX_DEGREE);

    printf("Enter coefficients from highest degree to constant term:\n");
    for (int i = degree; i >= 0; i--) {
        printf("Coefficient for x^%d: ", i);
        scanf("%lf", &coefficients[i]);
    }

    printf("Enter the value of x: ");
    scanf("%lf", &x);

    // Print polynomial details
    printPolynomial(degree, coefficients);

    // Evaluate polynomial using Horner's method
    result = hornerMethod(degree, coefficients, x);

    // Formatted result output
    printf("Polynomial Evaluation:\n");
    printf("P(x) = f(%.2f) = %.2f\n", x, result);

    return 0;
}

Compile and run the updated program:

gcc polynomial_eval.c -o polynomial_eval
./polynomial_eval

Example output:

Enter the degree of the polynomial (0-10): 3
Enter coefficients from highest degree to constant term:
Coefficient for x^3: 2
Coefficient for x^2: -3
Coefficient for x^1: 0
Coefficient for x^0: 5
Enter the value of x: 2
Polynomial: 2.00x^3 -3.00x^2 +5.00
Polynomial Evaluation:
P(x) = f(2.00) = 11.00

Key improvements:

  • Added printPolynomial() function to display the polynomial
  • Implemented input validation for polynomial degree
  • Enhanced result printing with formatted output
  • Showing both the polynomial and its evaluated value

Summary

In this lab, you first learned how to read polynomial coefficients and the variable x from user input in a C program. This involved defining a maximum degree for the polynomial, creating an array to store the coefficients, and using scanf() to read the user inputs. Then, you implemented Horner's method to efficiently evaluate polynomial expressions, which reduces the number of multiplications needed to compute polynomial values. By following these steps, you can implement a robust polynomial evaluation algorithm in C.

Other C Tutorials you may like