C# Basics

C# do-while loop

The C# do-while loop is a variant of the while loop except for 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, the expression should be changed to false to avoid an infinite or endless loop.

The structure of a do-while loop is as follows:
do-while loop

do-while loop execution order do-while loop flow diagram
do-while loop execution order do-while loop flow chart

The do-while loop starts with the do keyword and the loop body. At the bottom of the block is while keyword followed by single expression within parentheses ().

  • This type of loop is also called a post-test loop.
  • Always executes the loop body at least once, even if the condition fails the first time.
  • The condition (Boolean expression) is evaluated after each new iteration of the loop. This must be true in order for the next iteration to be performed. The iterations end when the condition is false.
  • If the loop’s condition is constantly true, then the loop never ends.
  • Loop ends with a semicolon “;”.
  • Statements are the block of code that you want to execute multiple times in a loop.

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

The above code consists of:

  1. Declared and initialized a Counter variable with the int type and assigned an initial value of 0 to it, counter=0.
  2. First time in the beginning, the loop body executes at least once irrespective of the condition being true or false.
  3. The Boolean expression is evaluated at the bottom of the code block when encountered.
  4. The Boolean condition (counter < 4) will repeatedly execute until the counter is less than 4.
  5. An expression for updating the counter (counter++ is a syntactically-shorter version of counter=counter+1) adds 1 at the end of each repetition, thus increasing the counter variable by 1.
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);

Loop Control Statements

You may need to use jump statements to control the order in which the statements are executed. Read more on …

C# Reference | Microsoft Docs


Tagged in :

Add Comment

Click here to post a comment