Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
3 Conditional Structures
4 Strings
5 Arrays
6 Objects
8 Functions
A do-while loop is a fundamental control flow statement in programming that executes a block of code repeatedly until a specified condition evaluates to false. Unlike the while
loop, which evaluates the condition before the loop starts executing, the do-while
loop executes its block of code once before checking the condition.
Here's the basic structure of a do-while loop:
do { // Code to be executed } while (condition);
The code block inside the do
statement contains the statements that you want to execute repeatedly. This block of code will execute at least once, regardless of whether the condition is true or false initially.
The condition is evaluated after each execution of the code block. If the condition evaluates to true, the loop will continue executing, and the code block will run again. If the condition evaluates to false, the loop terminates, and the program continues with the code after the loop.
Let's look at an example of a do-while
loop:
let i = 0; do { console.log("Iteration: " + i); i++; } while (i < 5);
In this example:
i
is initialized to 0 before entering the loop.i
and then increment it by 1 (i++
).i < 5
is evaluated after each iteration. Since i
starts at 0, the loop will execute once, with i
taking on the value 0 in the first iteration.i
becomes 1, and the condition i < 5
is still true. Therefore, the loop continues executing for the remaining iterations until i
reaches 5.i
becomes 5, the condition i < 5
evaluates to false, and the loop terminates.Do-while loops are useful when you need to ensure that a certain block of code executes at least once, regardless of the initial condition. They are commonly used in scenarios where you want to perform an action and then check a condition to decide whether to continue executing the loop. This makes them particularly suitable for situations where initialization of variables or setup operations need to occur before the condition check.