title: How to multiply polynomials in C?
body: <p>I hope this code makes sense.....I create two polynomials and try to multiply them. The problem is that I don't know what I should do to multiply them properly. This programs multiplies the polynomials, stores the result to another polynomial but it doesn't add the coefficients with the same power. </p>
  
  <blockquote>
    <p>What should I do in order to do that?? Also how should I use <code>free()</code> in this program?</p>
  </blockquote>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct poly {
    int coef;
    int exp;
    struct poly *next;
  } poly;
  
  int main(void) {
    poly * po1, *head, *po2, *head2, *po3, *head3 = NULL;
    int sel, c = 1;
  
    head = NULL;
    printf(
        "\nInsert elements for the first polynomial from the biggest to the smallest power of x. (Enter a power of zero (0) to stop)\n");
    while (1) {
      po1 = (poly *) malloc(sizeof(poly));
      printf("Give number: ");
      scanf("%d", &amp;po1-&gt;coef);
      printf("Give power of x: ");
      scanf("%d", &amp;po1-&gt;exp);
      po1-&gt;next = head;
      head = po1;
      if (po1-&gt;exp == 0) break;
    }
  
    head2 = NULL;
    printf(
        "\nInsert elements for the second polynomial from the biggest to the smallest power of x. (Enter a power of zero (0) to stop)\n");
    while (1) {
      po2 = (poly *) malloc(sizeof(poly));
      printf("Give number: ");
      scanf("%d", &amp;po2-&gt;coef);
      printf("Give power of x: ");
      scanf("%d", &amp;po2-&gt;exp);
      po2-&gt;next = head2;
      head2 = po2;
      if (po2-&gt;exp == 0) break;
    }
  
    po1 = head;
    po2 = head2;
  
    printf("Multiplying********\n");
    po1 = head;
    po2 = head2;
    while (po1 || po2) {
      po2 = head2;
      while (po1 &amp;&amp; po2) {
        po3 = (poly *) malloc(sizeof(poly));
        po3-&gt;coef = (po1-&gt;coef) * (po2-&gt;coef);
        po3-&gt;exp = (po1-&gt;exp) + (po2-&gt;exp);
        po3-&gt;next = head3;
        head3 = po3;
        po2 = po2-&gt;next;
      }
      po1 = po1-&gt;next;
    }
    while (po3) {
      printf("%+d(x^%d)", po3-&gt;coef, po3-&gt;exp);
      po3 = po3-&gt;next;
    }
    printf("\n");
  
  }
  
   }
  </code></pre>