Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- struct poly {
- int coef;
- int expo;
- } p1[100], p2[100], p3[100];
- int read(struct poly[]);
- int add(int t1, int t2);
- void display(struct poly[], int t);
- int main() {
- int t1, t2, t3;
- t1 = read(p1);
- t2 = read(p2);
- t3 = add(t1, t2);
- printf("first polynomial\n");
- display(p1, t1);
- printf("second poly\n");
- display(p2, t2);
- printf("result\n");
- display(p3, t3);
- }
- int read(struct poly p[]) {
- int terms, i;
- printf("enter no elements");
- scanf("%d", &terms);
- for (i = 0; i < terms; i++) {
- printf("enter coeff");
- scanf("%d", &p[i].coef);
- printf("enter expo");
- scanf("%d", &p[i].expo);
- }
- return terms;
- }
- int add(int t1, int t2) {
- int i = 0, k = 0, j = 0;
- while (i < t1 && j < t2) {
- if (p1[i].expo == p2[j].expo) {
- p3[k].expo = p1[i].expo;
- p3[k].coef = p1[i].coef + p2[j].coef;
- i++;
- j++;
- k++;
- } else if (p1[i].expo > p2[j].expo) {
- p3[k].expo = p1[i].expo;
- p3[k].coef = p1[i].coef;
- k++;
- i++;
- } else {
- p3[k].expo = p2[j].expo;
- p3[k].coef = p2[j].coef;
- j++;
- k++;
- }
- }
- while (i < t1) {
- p3[k].expo = p1[i].expo;
- p3[k].coef = p1[i].coef;
- k++;
- i++;
- }
- while (j < t2) {
- p3[k].expo = p2[j].expo;
- p3[k].coef = p2[j].coef;
- j++;
- k++;
- }
- return k;
- }
- /*void display(struct poly p[],int t)
- {
- int i;
- for(i=0;i<t-1;i++)
- {
- printf("%dx^%d+",p[i].coef,p[i].expo);
- }
- printf("%dx^%d",p[t-1].coef,p[t-1].expo);
- }*/
- void display(struct poly p[], int t) {
- int i;
- for (i = 0; i < t - 1; i++) {
- printf("%dx", p[i].coef);
- printf("^%d", p[i].expo);
- printf("+");
- }
- printf("%dx", p[t - 1].coef);
- printf("^%d", p[t - 1].expo);
- printf("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement