Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

7 Loops

4 Do While Loop

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);

Code Block

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.

Condition

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.

Example

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.
  • Inside the loop, we log the value of i and then increment it by 1 (i++).
  • The condition 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.
  • After 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.
  • After the fifth iteration, when 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.