- Get link
- X
- Other Apps
In programming, do-while loops are a fundamental control flow statement used to execute a block of code repeatedly as long as a specified condition remains true.
The defining characteristic of a do-while loop is that it guarantees the code block will execute at least once, because the condition is checked after the code block has run.
How the do-while Loop Works
- Execute: The code inside the { } block runs first.
- Evaluate: The condition is checked.
- Repeat/Exit: If the condition is
true, the loop returns to the top and repeats. If it isfalse, the loop terminates and the program proceeds to the next line of code.
[attachment_0](attachment)
Syntax
do {
// Code to be executed
} while (condition);
Example (JavaScript)
In this example, the loop will print the value of i and then check if i < 5.
let i = 0;
do {
console.log("Count is: " + i);
i++;
} while (i < 5);
Comparison: while vs. do-while
| Feature | while Loop | do-while Loop |
|---|---|---|
| Condition Check | Before execution | After execution |
| Minimum Iterations | 0 | 1 |
Note: The most common real-world application for a do-while loop is input validation, where you need to prompt the user at least once before checking if the data is correct.
Comments