The Following Java Program can be used to add two polynomials of any degree.
package poly;
/**
*
* @author www.c-madeeasy.blogspot.com
*/import java.io.*;
class node
{
int coef;
int pow;
node next;
node(int c,int p)
{
coef=c;
pow=p;
next=null;
}
void display()
{
System.out.println("coef="+coef+" pow="+pow);
}
}
class list
{
node first=null;
void insert(int c,int p)
{
node n1=new node(c,p);
node curr;
curr=first;
if(curr==null)
first=n1;
else
{
n1.next=first;
first=n1;
}
}
void display()
{
node curr;
curr=first;
while(curr!=null)
{
curr.display();
curr=curr.next;
}
}
}
public class Poly {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {DataInputStream get=new DataInputStream(System.in);
int c,i,a,n;
node curr1,curr2;
list l1=new list();
list l2=new list();
list l3=new list();
try
{
System.out.println("Enter the polynomial degree:");
n=Integer.parseInt(get.readLine());
System.out.println("first polynomial:");
for(i=0;i<=n;i++)
{
System.out.println("Enter coeff. of term of power "+i);
c=Integer.parseInt(get.readLine());
l1.insert(c,i);
}
System.out.println("second polynomial:");
for(i=0;i<=n;i++)
{
System.out.println("Enter coeff. of term of power "+i);
c=Integer.parseInt(get.readLine());
l2.insert(c,i);
}
curr1=l1.first;
curr2=l2.first;
while((curr1!=null)&&(curr2!=null))
{
a=curr1.coef+curr2.coef;
int p=curr1.pow;
l3.insert(a,p);
curr1=curr1.next;
curr2=curr2.next;
}
System.out.println("Polynomial after addition");
l3.display();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
// TODO code application logic here
}
}
No comments:
Post a Comment