Please help me to find out my mistake(s) in this code.
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
while (i < numbers.length){
if (numbers[i] >70){
continue;
}
console.log(numbers[i])
i++;
}
I want to get output
12
34
23
8
48
But the code shows output:
12
34
23
and the run doesn't stop.
You have an infinite loop, because if numbers[i] > 70 it's not increasing i, so the next loop it's checking that same condition again without an incremented i value. There are multiple ways to fix this, but one option is to output the value when numbers[i] <= 70, and always increment i.
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
while (i < numbers.length){
if (numbers[i] <= 70){
console.log(numbers[i]);
}
i++;
}
Another option would be a different loop:
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
for(i = 0; i < numbers.length; i++) {
if (numbers[i] > 70){
continue;
}
console.log(numbers[i]);
}
Or a simpler way:
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
for(i = 0; i < numbers.length; i++) {
if (numbers[i] <= 70){
console.log(numbers[i]);
}
}
You need to update i value before using continue if you don't the value of i will remain the same which leads to the loop becoming an infinite loop.
var numbers = [12, 34, 23, 98, 08, 78, 73, 48];
var i = 0;
while (i < numbers.length){
if (numbers[i] >70){
i++;
continue;
}
console.log(numbers[i])
i++;
}
Instead of interrupting the while loop you can re-write your logic as:
if (numbers[i] < 71){
console.log(numbers[i]);
}
so that the default action on each iteration of the loop is simply to increment i and, separately, the console logs a value only if the condition is satisfied.
Working Example:
let numbers = [12, 34, 23, 98, 08, 78, 73, 48];
let i = 0;
while (i < numbers.length){
if (numbers[i] < 71){
console.log(numbers[i]);
}
i++;
}