0

I am trying to convert the following for-loop

for( x = 1; x <= 10; x++ ){

    if( x == 5 ){
        continue;
    }

    printf("%d ", x);

}

into a while-loop. However, the following code, which seems reasonable to me, is not executing properly:

int x = 1;
while( x <= 10 ){
    if( x == 5){
       continue;
    }
    printf("%d ", x);
    x++;
}

Why is this the case?

Thanks in advance.

5
  • 1
    Are you sure your for loop is correct? That x++; at the end seems to me very suspicious Commented Aug 31, 2017 at 0:48
  • @carcigenicate, that was just a typo on my part. I have fixed it now. In the original, I had the if statement. Thanks. Commented Aug 31, 2017 at 1:16
  • Your for loop increments x twice each iteration, your while loop does not. Commented Aug 31, 2017 at 1:17
  • @Amadeus thanks for pointing that out. That was also a typo. Commented Aug 31, 2017 at 1:24
  • Your while loop will never end. When x == 5 you continue forever since you never increment it. ideone.com/B2eLwo Commented Aug 31, 2017 at 1:29

6 Answers 6

2

Here's a version of your for loop in JavaScript so we can run it here and see the output. C and JavaScript have the same loop semantics, so this makes a handy way to test the code:

for( x = 1; x <= 10; x++ ) {

    if( x == 5 ) {
        continue;
    }

    console.log( x );
}

Now, why doesn't your while loop produce this output? It's because of the continue statement. Here's a JavaScript version of your while loop:

var x = 1;
while( x <= 10 ) {

    if( x == 5) {
       continue;
    }

    console.log( x );

    x++;
}

On second thought, don't run that! In fact I took off the snippet tag so you don't run it. Because here is the problem...

When you use continue in a any kind of loop, it skips the rest of the loop body. In the for loop, the x++ is not part of the loop body. It is part of the for statement itself, so it gets run even when you use continue inside the loop. In the while loop, the x++ is part of the loop body, so it gets skipped along with the rest of the body.

Your while version will hit an infinite loop when x is 5, because it will not increment x during that loop iteration, and in fact will never increment x again.

Now for some advice: it is certainly possible to write a while loop that works like the corrected for loop, but it's going to be a bit more complicated. Why do you want to use while instead of for? Stick with the for loop for simplicity, or explain the reason you want to use while instead.

In general, you can say that the following for loop and while loop are equivalent:

for( a; b; c ) {
    // loop body
}

a;
while( b ) {
    // loop body
    c;
}

But they are not the same when you use continue in the loop body, for the reason mentioned above.

If you really want to use while, you can use a goto as in Amadeus's answer. Or you can rearrange the loop body, like this:

var x = 1;
while( x <= 10 ) {

    if( x != 5) {
        console.log( x );
    }

    x++;
}

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your response! Yes, the extra increment in the for-loop was an accident. As for why I am trying to use a while-loop to perform this task, I am just fiddling around as I learn C.
1

A for loop can be seen as compound of:

for (initialization; test; increment) 
{
    body
}

and can be implemented using while loop keeping this format:

initialization;
while (test)
{
    body
    increment;
}

So, in your case, the solution is (you are using the continue statement, which means that you have to skip the rest of the body and goes directly to the increment part):

x = 1;
while (x <= 10) {
    if( x == 5 ){
        goto cont;
    }

    printf("%d ", x);

    cont: x++; // this increment is due the increment in for statement
}

Using goto to jump to skip the body and going to the increment part

3 Comments

Isn't there an endless loop when x==5 ?
The trick is when body contain a continue or break. So not quite like initialization; while (test) { body increment; }
Instead of a goto, you can use an else.
1

Welcome to C! If you can keep something simpler without compromising efficiency and readability, do that _(^.^)_/ ! i.e.

int x = 1;
while( x <= 10 ){
    if( x != 5)
        printf("%d ", x);
    x++;
}

Notice: You don't even need brackets if you're doing a single command [within that "if" statement).

When you use "continue" in a while, you are skipping the loop's instructions, and you need 'em in order to iterate! ;)

4 Comments

Although you don't need braces with a single statement as you illustrated, many of us do not allow them to be omitted in our code. The reason is that it makes it too easy to have a bug like the infamous goto fail; that caused security breaches a few years ago. If you always use the braces you're less likely to have a nasty problem like that one.
Can you provide some articles explaining/defining that type of security breach, Michael? Sounds interesting!
Click the "goto fail;" text in my previous comment for an excellent article on the topic. (I wish SO made it more clear when formatted code like this is also a clickable link; it's hard to tell it from the way they display it.) Also do a web search for "goto fail" for several other articles. And a handy tip: if you use the Chrome address bar to do a search that begins with a keyword like "goto" or "google", type a space at the beginning to prevent Chrome from interpreting it as a keyword.
Thanks a lot, Michael! Appreciate it!
0

Each iteration (except when X==5) has two iterations, one in the for() and one in the body. Try something like this:

int x = 1;
while( x <= 10 ){
    if( x == 5){
      ;
    }else{
        printf("%d ", x);
        x++;
    }
    x++ // "for()" increment
}

1 Comment

Aka if(x!=5).
0

In the second block of code you have

int x = 1;
while( x <= 10 ){
    for( x == 5){
       continue;
    }
    printf("%d ", x);
    x++;
}

and in the second line of the while statement, you have for(x == 5) instead of if (x == 5) like you have in the for-loop in the first block.

Otherwise, this is the correct way to write a for-loop as a while loop, essentially move the initialization variable to outside of the loop, and place the modification statement at the end. Depending on the situation, one will probably be a better choice than the other, but they are interchangeable.

Edit:

It would probably be best to minimize the code by excluding the one time the value is 5 instead of using continue when it isn't. Additionally, the other poster is correct, your continue statement would exclude the increment of x causing an infinite loop.

int x = 1;
while( x <= 10 ){
    if ( x != 5){
       printf("%d ", x);
    }
    x++;
}

1 Comment

thanks for your response. Indeed, the "for" was a typo and I meant it to be an if, as it is in the original code, but it is not working. I am not getting the output that I should be with the while-loop, 1 2 3 4 6 7 8 9 10.
-1

You just need to add "else" - what you want to be done if the "if statement" is not working, or you can tell the program what to do in every other case:

int x = 1;
while( x <= 10 ){
    if( x != 5)
       printf("%d ", x);
    x++;
}

1 Comment

You still do not reach the x++ after you reach continue. The code is flawed in the same way as from the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.