Friday, January 25, 2013

C Program to Add Polynomials

C program for adding of polynomials is illustrated here

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

void display(int a[])
{
  int i;
  for(i=0; i<2*a[0]+1;i++)
  {
    printf("%d, ",a[i]);
  }
  printf("\n");
}

void addpoly(int a[], int b[],int c[])
{
   int i,j,k,temp;
   i=1;j=1;k=1;
   while ((i<=2*a[0]) && (j<=2*b[0])) /* both arrays are existing */
   {
     if (a[i]>b[j])
     {
            c[k]=a[i];
            c[k+1]=a[i+1];
            k=k+2;i=i+2;
     }
     else if (b[j]>a[i])
     {
            c[k]=b[j];
            c[k+1]=b[j+1];
            k=k+2;j=j+2;
     }
     else if (a[i]==b[j])
     {
            temp=a[i+1]+b[j+1];
            if (temp==0)
            {
             i=i+2; j=j+2;
            }
            else
            {
              c[k]=a[i];  /* either a[i] or b[j] can be assigned since both powers are equal */
              c[k+1]=temp;
              k=k+2; j=j+2; i=i+2;
            }
     }
   }
   /* A is not exhausted and B is Exhausted */
   while ( (i<=2*a[0]) && (j>=2*b[0]) )
   {
     c[k]=a[i];
     c[k+1]=a[i+1];
     i=i+2;
     k=k+2;
   }
   /* A is exhausted and B is not Exhausted */
   while ( (i>=2*a[0]) && (j<=2*b[0]) )
   {
     c[k]=b[j];
     c[k+1]=b[j+1];
     j=j+2;
     k=k+2;
   }
   c[0]=k/2;
}


void main()
{
  int a[20],b[20],c[20],i;
  clrscr();
  printf("Enter no. of terms in first polynomial\n");
  scanf("%d",&a[0]);
  printf("enter elements in first polynomials i.e. power and coff.\n");
  for(i=1;i<2*a[0]+1; i++)
  {
    scanf("%d",&a[i]);
  }
  printf("Enter no. of terms in Second polynomial\n");
  scanf("%d",&b[0]);
  printf("enter elements in second polynomials i.e. power and coff.\n");
  for(i=1;i<2*b[0]+1; i++)
  {
    scanf("%d",&b[i]);
  }
  display(a);
  display(b);
  addpoly(a,b,c);
  printf("Result of Two Polynomials= \n");
  display(c);
  getch();
}

No comments:

Post a Comment