Code

do-while loop

The do-while loop is a variant of the while loop except one main difference, it will always execute the loop body at least once in the beginning irrespective of the condition being true or false. The condition is evaluated at the end of the first execution of the block when the while statement is encountered. Bear in mind that somewhere in the loop, expression should be changed to false to avoid an infinite or endless loop.

do-while loop structure do-while loop execution order
do-while loop do-while loop execution order

do-while Loop example

The code below shows an example of how a do-while loop works. It writes out all the integers from 1 to 4. If you have more than one statement within the loop, you must enclose the statements in curly brackets.

do-while loop example

Run Demo

OUTPUT

1
2
3
4

With a single statement

Curly brackets for the loop are optional if there is only one statement in the code block.

int counter = 0;

do
    counter++;
while (counter < 4);

break Statement

do-while loop break statement

When counter reaches 3, the condition marked A evaluates to true. The break keyword then causes the loop to end prematurely, and resumes execution immediately after the loop.

int counter = 0;
do
{

    counter++;
    if (counter == 3) // <- A
        break;

    Console.WriteLine(counter);

} while (counter < 4);

Run Demo

OUTPUT

1
2

continue Statement

do-while loop continue statement

When a counter reaches 3, the condition marked A evaluates to true. This causes the do-while loop to skip rest of the current iteration and initiates the execution of the next cycle due to continue statement.

int counter = 0;

do
{

     counter++;
     if (counter == 3) // <- A
        continue;

     Console.WriteLine(counter);

} while (counter < 4);

Run Demo

OUTPUT: 3 skipped

1
2
4

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video