Code

while loop

The while loop repeatedly executes a block of code inside the loop while the given logical expression is true else it breaks. Bear in mind that somewhere in the loop, expression should be changed to false to avoid an infinite or endless loop.

while loop structure while loop execution order
while loop while loop execution order

while Loop example

The code below shows an example of how a 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.

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;
while (counter < 4)
    counter++;

break Statement

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;
while (counter < 4)
{

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

    Console.WriteLine(counter);
}

Run Demo

OUTPUT

1
2

continue Statement

while loop continue statement

In the below code sample, all of the numbers will be printed out except one. 3 gets skipped because of the continue statement. When it hits condition marked A, it jumps back up and continues on with the next cycle through the loop.

int counter = 0;
while (counter < 4)
{

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

    Console.WriteLine(counter);
}

Run Demo

OUTPUT: 3 skipped

1
2
4

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video