-1

When the coef is 0, I used continue to not print, but only printTerm(a) comes out and the printTerm(b) part does not come out.

When I delete the (if & continue) statement, both printTerm(a) and printTerm(b) appear, so it seems that there is a problem here (if & continue) statement.

How can I solve this?

int main() {
    a[0].coef = 2;
    a[0].expon = 1000; // 2x^1000
    
    a[1].coef = 1;
    a[1].expon = 2; // x^2
    
    a[2].coef = 1;
    a[2].expon = 0; // 1
    
    b[0].coef = 1;
    b[0].expon = 4; // x^4
    
    b[1].coef = 10;
    b[1].expon = 3; // 10x^3
    
    b[2].coef = 3;
    b[2].expon = 2; // 3x^2
    
    b[2].coef = 1;
    b[2].expon = 0; // 1
    
    printTerm(a);
    printTerm(b);
    
    return 0;
}

void printTerm(polynomial *p) {
    int i=0;
    printf("polynomial : ");
    while(p[i].expon != -1) {
        if(p[i].coef == 0) continue;
        printf("%dx^%d", p[i].coef, p[i].expon);
        i++;
        if(p[i].expon != -1 && p[i].coef > 0) printf(" + ");
    }
    printf("\n");
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
sion
  • 1
  • 6
    How are `a` and `b` declared and initialized? Is `a[3].expon` `-1`? (my guess is no) Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – MikeCAT Jan 29 '21 at 11:15

1 Answers1

0

Because you only increment i if p[i].coef is not equal to 0. If p[i].coef == 0 it skips the increment part and function is stuck in infinite loop, always checking the same array item.


EDIT: Way to fix this: Instead of if(p[i].coef == 0) continue; use:

if (p[i].coef == 0) 
{
  i++;
  continue;
}

This way while loop evaluetes next array item instead of being stuck on the same.

Samogitian95
  • 121
  • 4