I want to write a program in JavaScript to print all the numbers from 1 to 20 except 5 and 10. When I use a for loop like this:
for (x = 1; x <= 20; x++) {
if (x == 5 || x == 10) {
continue;
}
document.write(x + ' ');
}
It works properly and prints 1 2 3 4 6 7 8 9 11 12 13 14 15 16 17 18 19 20
.
However, when I try to use a while loop like this:
var x = 1;
while (x <= 20) {
if (x == 5 || x == 10) {
continue;
}
document.write(x + ' ');
x++;
}
It makes the webpage unresponsive and I get a prompt asking me to close it. What is the problem here?
The problem is the following, inside the for-loop the continue will jump back to the update expression x++ but in the while loop it will jump back to the running condition while(x <= 20)
Referencing the mdn docs.
In a while loop, it jumps back to the condition. In a for loop, it jumps to the update expression.
Because you are not updating the counter inside your condition
while (x <= 20) {
if (x == 5 || x == 10) {
continue;
}
x will remain 5 and gets never updated because with the continue inside the while-loop it jumps back to the running condition. This will end up in an endless loop.
To solve it you can increment the counter before the continue statement inside the while-loop
while (x <= 20) {
if (x == 5 || x == 10) {
x++
continue;
// for (x = 1; x <= 20; x++) {
// if (x == 5 || x == 10) {
// continue;
// }
// document.write(x + ' ');
//}
var x = 1;
while (x <= 20) {
if (x == 5 || x == 10) {
x++
continue;
}
document.write(x + ' ');
x++;
}
In the first case the loop declaration for (x = 1; x <= 20; x++)
handles incrementing x
between iterations, so every time the loop body executes, you get a different value of x
.
In the second case, x++
is only executed if x
is neither 5
nor 10
. So, when x
reaches 5
it's the loop will keep executing with x = 5
forever, since nothing is changing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With