Kontera

Wednesday, November 30, 2011

Polynomial Addition Using Array


/************************************************************
* Filename: pol_add_using_array.c
* Description: To add two polynomials using array
* Author: Sarju S
* Date: 24-Nov-2011
*************************************************************/
#include
#include
#define MAX_TERMS 100
typedef struct
{
float coef;
int expon; 
}polynomial;
polynomial terms[MAX_TERMS];P
int avail=0;

void attach(float coefficient, int exponent)
{

/* add new term to the polynomial */
if(avail>=MAX_TERMS) {
printf("Too many terms in the polynomial");
exit(EXIT_FAILURE);
}
terms[avail].coef = coefficient;
terms[avail++].expon = exponent;


}
void padd(int startA, int finishA, int startB, int finishB, int *startD, int *finishD)

/* add A(x) and B(x) to obtain D(x)*/
float coefficient;
*startD = avail;
while(startA<=finishA && startB<=finishB)
switch(compare(terms[startA].expon,terms[startB].expon)){

case -1: /* a expon < b expon */
attach(terms[startB].coef,terms[startB].expon);
startB++;
break;

case 0: /* equal exponents */
coefficient = terms[startA].coef + terms[startB].coef;
if(coefficient)
attach(coefficient,terms[startB].expon);
startA++;
startB++;
break;

case 1: /* a expon < b expon */
attach(terms[startA].coef,terms[startA].expon);
startA++;
}

/* add in remaining terms of A(x) */
for(;startA<=finishA; startA++)
attach(terms[startA].coef,terms[startA].expon);

/* add in remaining terms of A(x) */
for(;startB<=finishB; startB++)
attach(terms[startB].coef,terms[startB].expon);
*finishD = avail-1;
}

int compare(int expon1, int expon2)
{
if(expon1
else if(expon2
else return 0;
}

void pread(int no_ofterm, int *start, int *finish)
{
int i;
*start=avail;
printf("avail=%d",avail);
for(i=0;i
{
printf("\n Enter the coefficient and exponent:");
scanf("%f%d",&terms[avail].coef,&terms[avail].expon);
avail++;

}
*finish= avail-1;

}
void pprint(int start, int finish)
{ int i;
for(i=start;i<=finish;i++)
printf("%fX^%d+",terms[i].coef,terms[i].expon);
}

void main()
{
int no_ofterm,i,j;
int startA,finishA,startB,finishB,startD,finishD;
printf("\nEnter the number of terms in the first polynomial:");
scanf("%d",&no_ofterm);
pread(no_ofterm,&startA,&finishA);
finishA= avail-1;
printf("\nEnter the number of terms in the second polynomial:");
scanf("%d",&no_ofterm);
pread(no_ofterm,&startB,&finishB);
finishB= avail-1;
padd(startA,finishA,startB,finishB,&startD,&finishD);
printf("\nFirst Polynomial is\n");
pprint(startA,finishA);
printf("\nSecond Polynomial is\n");
pprint(startB,finishB);
printf("\nFinal Polynomial is\n");
pprint(startD,finishD);

}

0 comments:

Post a Comment