Question

In a school exercise (on paper) i've this question:

5) rewrite the code without using continue and break:

for (i = 0; i < N; i++) {
    scanf("give me an int %d", & a);
    if (a < 0) {
        continue;
    }
    if (a == 0) {
        break;
    }
    /* elaborate positive int */
}

I'm thinking about this:

for(i=0;i<N;i++){

 scanf("give me an int %d",&a");

 if(a==0){return -1; //??i dont know how to exit}
 if(a<0){
  do{
        scanf("give me an int %d",&a");
        if(a==0){return -1; //??i dont know how to exit}
    }while(!(a<0))
 }
 /* elaborate positive int */
}

but, I'm actually not able to do this.. can you help me? thanks :)

Was it helpful?

Solution 2

for(i = 0; i < N && a != 0; i++)
{
    scanf("give me an int %d",&a");
    if(a>0)
    { /*do stuff*/ }
}
if(a==0) i--; //As noted by Daniel Fischer

OTHER TIPS

Might not be what your teacher wants but that's actually the easiest way:

a = INT_MAX;
for(i = 0; i < N && a != 0; i++) {
    scanf("give me an int %d", &a);
    if(a > 0) {
        /* elaborate positive int */
    }
}

The reason for not using return is that you just want to exit/restart the loop. The function could contain more stuff that should not be skipped.

And that scanf call looks wrong.. do you really want to enter "give me an int .." everytime?

Not going to give you full code, but:

  • remember you can add conditions inside the clause of the for statement. (hint: move the breaking condition there to terminate the loop)
  • does the continue actually do anything in your example?

In this specific case, not much needs to be done. Since a < 0 and a == 0 are mutually exclusive conditions, an if-else-if statement could be used as follows:

for (i = 0; i < N; i++)
{
    scanf("give me and int %d", &a);

    if (a < 0)
        // Do something or nothing here, but this skips the rest of the loop
        // body just like continue would.
    else if (a == 0)
        i = N; // This satisfies the loop condition, so it won't loop again
               // just like break would.
}

This is not a general solution, but it should give you the proper behavior in this case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top