Home »
C++ programming language
Polynomial Evaluation Using Structure [with C++ program]
Learn: How to evaluate polynomials using structures in C++? This article explain algorithm and C++ program for polynomial Evaluation.
Submitted by Abhishek Jain, on June 24, 2017
To learn about implementation of polynomial using structure, please take reference from Polynomial Addition Using Structure.
Polynomial Evaluation refers to finding the resultant of the polynomial expression for a particular value of polynomial variable.
Example:
P(x)= 4x3+6x2+7x+9 where x=2 then,
Result = 4(2)3+6(2)2+7(2)1+9 = 4(8)+6(4)+7(2)+9= 32+24+14+9= 79
Polynomials are stored using structure for each term of polynomial and thus program uses array of structures.
Struct polynomial
{
int coefficient;
int exponent;
};
Algorithm
Eval (struct poly p[10],int n,int x)
1.) [Initialize segment variables]
[Initialize Counter] Set i=0,sum=0
2.) Repeat step 3 while i<n
3.) sum=sum+p[i].coeff*pow(x,p[i].expo)
4.) Return sum;
5.) Exit
C++ program for polynomial evaluation using structure
#include<iostream>
#include<math.h>
using namespace std;
/* declare structure for polynomial */
struct poly
{
int coeff;
int expo;
};
/* function prototypes */
int readPoly(struct poly []);
void displayPoly( struct poly [],int terms);
int eval(int n1,struct poly []);
int main()
{
int n1;
int value;
struct poly p1[20];
cout<<"\n Enter the polynomial details:";
n1=readPoly(p1);
cout<<"\n The polynomial is: ";
displayPoly(p1,n1);
value=eval(n1,p1);
cout<<"\n The Resultant value of the polynomial is:"<<value<<endl;
return 0;
}
int readPoly(struct poly p[])
{
int t1,i;
cout<<"\n Enter the total number of terms in the polynomial: ";
cin>>t1;
cout<<"\n Enter the COEFFICIENT and EXPONENT "<<endl;
for(i=0;i<t1;i++)
{
cout<<" Enter the Coefficient("<<i+1<<"):";
cin>>p[i].coeff;
cout<<" Enter the Exponent("<<i+1<<"):";
cin>>p[i].expo;
}
return(t1);
}
void displayPoly(struct poly p[10],int term)
{
int k;
for(k=0;k<term-1;k++)
cout<<p[k].coeff<<"(x^"<<p[k].expo<<")+";
cout<<p[k].coeff<<"(x^"<<p[k].expo<<")";
}
int eval(int n1,struct poly p1[])
{
int i,sum,x;
cout<<"\n\n Enter the value of x for evaluation: ";
cin>>x;
sum=0;
for(i=0;i<n1;i++)
sum=sum + p1[i].coeff*pow(x,p1[i].expo);
return(sum);
}
Output
Enter the polynomial details:
Enter the total number of terms in the polynomial: 4
Enter the COEFFICIENT and EXPONENT
Enter the Coefficient(1):4
Enter the Exponent(1):3
Enter the Coefficient(2):6
Enter the Exponent(2):2
Enter the Coefficient(3):7
Enter the Exponent(3):1
Enter the Coefficient(4):9
Enter the Exponent(4):0
The polynomial is: 4(x^3)+6(x^2)+7(x^1)+9(x^0)
Enter the value of x for evaluation: 2
The Resultant value of the polynomial is:79