Monday 20 October 2014

C++ program to evaluate polynomial

C++ program to evaluate polynomial using array or linked list.



C++ program to evaluate polynomial using array

#include<iostream>
#include<math.h>
using namespace std;
void print(int (&d)[10][2],int n)
{
    for(int i=0;i<n-1;i++)
         cout<<d[i][0]<<"x^"<<d[i][1]<<"  +  ";
    cout<<d[n-1][0]<<"x^"<<d[n-1][1]<<endl<<endl;
}
void getpoly(int (&d)[10][2],int &n)
{
    cout<<"How many terms in polynomial  ";
    cin>>n;
    cout<<"Enter coefficient and exponent in decreasing order"<<endl;
    for(int i=0;i<n;i++)
         cin>>d[i][0]>>d[i][1];
}
int eval_poly(int (&a)[10][2],int n,int x)
{
    int res=0;
    for(int i=0;i<n;i++)
        res+=a[i][0]*pow(x,a[i][1]);
    return res;
}
int main()
{
    int a[10][2],n,x;
    getpoly(a,n);
    cout<<"Enter the value of x : ";
    cin>>x;
    print(a,n);
    cout<<"Result : "<<eval_poly(a,n,x);
    return 0;
}

OUTPUT




C++ program to evaluate polynomial using linked list

#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
struct links
{
    int exp,coef;
    links *next;
};
class linkedlist
{
    links *start;
    int x;
public:
    void create();
    void eval_poly();
    void display();
};
void linkedlist::create()
{
    int exp,coef;
    links *temp;
    char ch;
    cout<<"Enter the polynomial in descending order of exponent "<<endl;
    cout<<"Enter the coefficient and Exponent of the term ";
    cin>>coef>>exp;
    temp=new links;
    temp->coef=coef;
    temp->exp=exp;
    temp->next=NULL;
    start=temp;
    cout<<"Want to add more terms (Y/N) : ";
    ch=getche();
    cout<<endl;
    while(ch!='n'&&ch!='N')
    {
        cout<<"Enter the coefficient and Exponent of the term ";
        cin>>coef>>exp;
        temp->next=new links;
        temp=temp->next;
        temp->coef=coef;
        temp->exp=exp;
        temp->next=NULL;
        cout<<"Want to add more terms (Y/N) : ";
        ch=getche();
        cout<<endl;
    }
    cout<<"enter the value of x : ";
    cin>>x;
}
void linkedlist::display()
{
    links *temp=start;
    while(temp->next!=NULL)
    {
        cout<<temp->coef<<"x^"<<temp->exp<<"  +  ";
        temp=temp->next;
    }
    cout<<temp->coef<<"x^"<<temp->exp;
}
void linkedlist::eval_poly()
{
    links *temp=start;
    int res=0;
    while(temp!=NULL)
    {
        res+=temp->coef*pow(x,temp->exp);
        temp=temp->next;
    }
    cout<<"\nResult : "<<res;
}
int main()
{
    linkedlist eval;
    eval.create();
    eval.display();
    eval.eval_poly();
    return 0;
}

OUTPUT


No comments:

Post a Comment