c code to add and multiply two polynomials

  • cpolynomials
  • write a c code to add and multiply two polynomials

    Write a program to add and multiply two polynomials using an array.

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> void setvalue(int *arr, int n) { int k; for (int i = 0; i < n; i++) { printf("enter the cofficient of x^%d\n", i); scanf("%d", &k); *(arr + i) = k; } } void display(int *arr, int n) { int e = 0; for (int i = 0; i < n; i++) { printf("%dx^%d ", *(arr + i), i); if (e < n - 1) { printf("+ "); e++; } } printf("\n"); } int *addpoly(int *m, int *n, int k) { int *l = (int *)malloc(k * sizeof(int)); for (int i = 0; i < k; i++) { l[i] = m[i] + n[i]; } return l; } void productpoly(int *m, int *n, int b) { int *l = (int *)calloc(b + b - 1, sizeof(int)); for (int i = 0; i < b; i++) { for (int j = 0; j < b; j++) { l[i + j] = l[i + j] + m[i] * n[j]; } } printf("\n"); printf("THE PRODUCT IS\n"); printf("\n"); int e = 0; for (int i = 0; i < b + b - 1; i++) { printf("%dx^%d ", *(l + i), i); if (e < b + b - 2) { printf("+ "); e++; } } } int main() { int d1, d2, d; printf("enter the higest degree of variable in polynomial 1 --> "); scanf("%d", &d1); printf("enter the higest degree of variable in polynomial 2 --> "); scanf("%d", &d2); if (d1 > d2) { d = d1; } else { d = d2; } d = d + 1; int *poly1 = (int *)malloc(d * sizeof(int)); int *poly2 = (int *)malloc(d * sizeof(int)); int *poly3 = (int *)malloc(d * sizeof(int)); setvalue(poly1, d); setvalue(poly2, d); display(poly1, d); display(poly2, d); poly3 = addpoly(poly1, poly2, d); printf("\n"); printf("THE SUM IS\n"); printf("\n"); display(poly3, d); productpoly(poly1, poly2, d); return 0; }