DEV Community

Kiruthiga S
Kiruthiga S

Posted on

do while Loop

Loop
Loops allow a block of code to run multiple times as long as a given condition is satisfied. They help reduce repetition and make programs more efficient and organized.

  • Loops continue running until the condition becomes false.
  • They are useful for iterating over arrays, strings, and ranges of values.

There are mainly two types of loops.

Entry Controlled loops:
The test condition is tested before entering the loop body. For Loop and While Loops are entry-controlled loops.

Exit Controlled Loops:
The test condition is tested or evaluated at the end of the loop body.
So the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.

do...while loop
A do...while loop is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the condition is met initially or not.

Syntax

    do {
        // Statements
    }
    while(conditions)
Enter fullscreen mode Exit fullscreen mode
let i=1;
do {
    console.log(i);
    i++;
} while(i<=5)

Enter fullscreen mode Exit fullscreen mode

Output:1 2 3 4 5

let i=1;
do {
    console.log("Hi");
    i++;
} while(i<5)
Enter fullscreen mode Exit fullscreen mode

Output:Hi

Top comments (0)