Tuesday, 1 August 2017

Addition of polynomial using array and structure in c

#include <stdio.h>
#include <stdlib.h>
struct poly{
    int exp;
    float coeff;
};
int main()
{
    struct poly a[50],b[50],c[50];
    int i,d1,d2;
    int k=0,l=0,m=0;
    printf("Enter the highest degree of 1st polynomial\n");
    scanf("%d",&d1);
    printf("Enter the highest degree of 2nd polynomial\n");
    scanf("%d",&d2);

    printf("Enter the 1st polynomial \n");

    for(i=0;i<=d1;i++){
            printf("enter the coefficient of x^%d\n",i);
            scanf("%f",&a[i].coeff);
            a[k++].exp = i;
    }

     printf("Enter the 2nd polynomial \n");

    for(i=0;i<=d2;i++){
            printf("enter the coefficient of x^%d\n",i);
            scanf("%f",&b[i].coeff);
            b[l++].exp = i;
    }

    printf("\nExpression of 1st polynomial is %.1f",a[0].coeff);
    for(i=1;i<=d1;i++){

        printf("+%.1fx^%d",a[i].coeff,a[i].exp);

    }

     printf("\nExpression of 2nd polynomial is %.1f",b[0].coeff);
    for(i=1;i<=d2;i++){

        printf("+%.1fx^%d",b[i].coeff,b[i].exp);

    }
    //Addition of polynomials

    if(d1>=d2){

            for(i=0;i<=d2;i++){
                c[m].coeff = a[i].coeff+b[i].coeff;
                c[m].exp = a[i].exp;
                m++;
            }
            for(i=d2+1;i<=d1;i++){
                c[m].coeff = a[i].coeff;
                c[m].exp = a[i].exp;
                m++;

            }
    }
    else{
            for(i=0;i<=d1;i++){
                c[m].coeff = a[i].coeff+b[i].coeff;
                c[m].exp = a[i].exp;
                m++;
            }
            for(i=d1+1;i<=d2;i++){
                c[m].coeff = b[i].coeff;
                c[m].exp = b[i].exp;
                m++;
            }
    }

    //Now print the sum of polynomials
    printf("\nExpression of sum of polynomial is %.1f",c[0].coeff);
    for(i=1;i<m;i++){

        printf("+%.1fx^%d",c[i].coeff,c[i].exp);

    }

    return 0;

}

All In One Blog

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.

0 comments:

Post a Comment

 

Copyright @ 2015