Evaluation Of Polynomial Expression Using C Program

Polynomial Expression

Here you will see how to evaluate a polynomial using C program. The evaluation means what would be the final result of the polynomial expression.

A Polynomial is a mathematical expression involving a sum of powers in one or more variables multiplied by coefficients.

In mathematics, a polynomial expression consists of indeterminates and coefficients, that involves only the operations of addition, subtraction, multiplication, and positive-integer powers of variables.

For example, a polynomial can be represented as 2+3x^2+5x^4. So it is required to evaluate the value of the above polynomial expression when a particular value of x is specified. For instance, for a given value 1 of x, the expression can be evaluated as:

2 + 3.1^2 + 5.1^4 = 2 + 3 + 5 = 10

Evaluation using C Program

Now I will implement the C program to evaluate the polynomial expression.

#include <stdio.h>
#include <stdlib.h>

typedef struct termType {
    int coefficient, exponent;
} termType;

typedef struct poly {
    termType terms[100];
    int noOfTerms;
} poly;

double evaluate(poly *p, double x) {
    int i, j;
    double term, result = 0;

    term = 1;

    for(i=0; i<p->noOfTerms; i++) {
        for(j=0; j<p->terms[i].exponent; j++) {
            term *= x;
        }

        result += term*p->terms[i].coefficient;
        term = 1;
    }

    return result;
}

int main() {
    termType t1, t2, t3;
    poly *p;
    double result;

    p = malloc(sizeof (poly));

    t1.coefficient = 5;
    t1.exponent = 4;

    t2.coefficient = 3;
    t2.exponent = 2;

    t3.coefficient = 2;
    t3.exponent = 0;

    p->terms[0] = t1;
    p->terms[1] = t2;
    p->terms[2] = t3;
    p->noOfTerms = 3;

    result = evaluate(p, 1);
    printf("Result: %lf", result);

    result = evaluate(p, 2);
    printf("\nResult: %lf", result);

    return 0;
}

Executing the above program would give you below result:

Result: 10.000000
Result: 94.000000

That’s all about the evaluation of polynomial using C program.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *