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++;
}
x++;at the end seems to me very suspicious