Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct term{
- int exp;
- float coef;
- };
- void display(struct term* poly,int,int);
- void input(struct term*,int,int);
- void sort(struct term*,int,int);
- void add(struct term*,int,int);
- int main(){
- int n1,n2;
- printf("Enter the number of term in 1st polynomial:");
- scanf("%d",&n1);
- printf("Enter the number of term in 2nd polynomial:");
- scanf("%d",&n2);
- struct term*poly=(struct term *)malloc((n1+n2)*sizeof(struct term));
- printf("Enter 1st polynomial:\n");
- input(poly,0,n1-1);
- sort(poly,0,n1-1);
- printf("Enter 2nd polynomial:\n");
- input(poly,n1,n1+n2-1);
- sort(poly,n1,n1+n2-1);
- printf("Polynomial 1 is:\n");
- display(poly,0,n1-1);
- printf("Polynomial 2 is:\n");
- display(poly,n1,n1+n2-1);
- add(poly,n1,n2);
- sort(poly,0,n1+n2-1);
- printf("Resultant polynomial is:\n");
- display(poly,0,n1+n2-1);
- return 0;
- }
- void input(struct term* p,int l,int r){
- int i;
- for(i=l;i<=r;i++){
- printf("TERM %d:\n",i-l+1);
- printf("Enter exponent:");
- scanf("%d",&p[i].exp);
- printf("Enter coefficient:");
- scanf("%f",&p[i].coef);
- }
- }
- void display(struct term* poly,int l,int r){
- int i;
- for(i=l;i<=r;i++){
- if(poly[i].coef){
- printf("%.2fx^%d",poly[i].coef,poly[i].exp);
- if(i!=r)
- printf("+");
- }
- }
- printf("\n");
- }
- void sort(struct term* poly,int l,int r){
- int i,j;
- struct term temp;
- // int n=r-l+1;
- for(i=l;i<r-1;i++){
- for(j=l;j<r-i+1;j++){
- if(poly[j].exp<poly[j+1].exp){
- temp=poly[j];
- poly[j]=poly[j+i];
- poly[j+i]=temp;
- }
- else if(poly[j].exp==poly[j+1].exp){
- poly[j].coef+=poly[j+1].coef;
- poly[j+1].coef=0;
- }
- }
- }
- }
- void add(struct term* poly,int m,int n){
- int i,j;
- for(i=0;i<m;i++){
- for(j=m;j<m+n;j++){
- if(poly[i].exp==poly[j].exp){
- poly[i].coef+=poly[j].coef;
- poly[j].coef=0;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement