Which general while loop definition is written correctly?

A

while (x is true) {
// code
}
B

if (i < 5) {
//code
}
C

while (let i = 0; i < count; i++) {
//code
}
D

while (condition) {
//code
}

A

B

C

D

1 answer

The correct definition of a general while loop is:

D

while (condition) {
    //code
}

Here's a brief explanation of each option:

  • A: This option uses "is true" which is not correct syntax for a while loop in most programming languages; it should just evaluate a condition (e.g., while (x), where x is a boolean).

  • B: This is an if statement, not a while loop.

  • C: This uses the let keyword in the loop condition, which is not correct. This syntax resembles a for loop, not a while loop.

  • D: This is the correct syntax for a while loop, where condition is evaluated, and the code block executes as long as the condition is true.