Program for Ploynomial expression in java is as follows:
import java.lang.*;
import java.io.*;
class term
{
int coeff,exp;
}
class poly
{
term pl[] = new term[10];
int n;
poly()throws Exception
{
poly p[]=new poly[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the no. of terms: ");
n=Integer.parseInt(br.readLine());
}
public void getPoly()throws Exception
{
poly p[]=new poly[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the base & exponent:");
for(int i=0;i<n;i++)
{
p[i].coeff=Integer.parseInt(br.readLine());
p[i].exp=Integer.parseInt(br.readLine());
}
}
public void putPoly()
{
poly p[]=new poly[10];
System.out.println("Polynomial is : ");
for(int i=0;i<n;i++)
{
System.out.println(" "+p[i].coeff+"x^"+p[i].exp);
}
}
public void evalPoly()throws exception
{
poly p[]=new poly[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int x,ans=0;
System.out.println("Enter the value for x:");
x=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
ans=ans+p[i].coeff*pow(x,p[i].exp);
}
System.out.println("Ans : "+ans);
}
public static void main(String args[])throws Exception
{
poly p1=new poly();
poly p2=new poly();
p1.getPoly();
p2.getPoly();
p1.putPoly();
p2.putPoly();
p1.evalPoly();
}
}
import java.lang.*;
import java.io.*;
class term
{
int coeff,exp;
}
class poly
{
term pl[] = new term[10];
int n;
poly()throws Exception
{
poly p[]=new poly[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the no. of terms: ");
n=Integer.parseInt(br.readLine());
}
public void getPoly()throws Exception
{
poly p[]=new poly[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the base & exponent:");
for(int i=0;i<n;i++)
{
p[i].coeff=Integer.parseInt(br.readLine());
p[i].exp=Integer.parseInt(br.readLine());
}
}
public void putPoly()
{
poly p[]=new poly[10];
System.out.println("Polynomial is : ");
for(int i=0;i<n;i++)
{
System.out.println(" "+p[i].coeff+"x^"+p[i].exp);
}
}
public void evalPoly()throws exception
{
poly p[]=new poly[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int x,ans=0;
System.out.println("Enter the value for x:");
x=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
ans=ans+p[i].coeff*pow(x,p[i].exp);
}
System.out.println("Ans : "+ans);
}
public static void main(String args[])throws Exception
{
poly p1=new poly();
poly p2=new poly();
p1.getPoly();
p2.getPoly();
p1.putPoly();
p2.putPoly();
p1.evalPoly();
}
}
No comments:
Post a Comment