'While Loop: Challenge for beginners

Challenge:

Use a while loop to increment count by 2 on each repetition of the block of code. Run the code block of your while loop until count is 8

let count = 2;


I just started learning code two days ago, I am not really sure the logic behind what it is I should do, when to use a while loop or logically the difference between that and an infinite loop. I would really appreciate any help



Solution 1:[1]

You call while with a condition, in your case while count < 8.

Inside your while loop you increment count by two every iteration until it is 8 or bigger. So it would look like this:

let count = 2;

while (count < 8) {
    count = count + 2;
}

When the condition is not true, so when your count is equal or bigger than 8, the inner part of the while loop is not being executed (your while loop terminates).

An example for an infinite while loop would be with the condition "true":

while (true) {
    ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sun lu