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 inﬁnite or endless loop.
The structure of a do-while loop is as follows:
|do-while loop execution order||do-while loop flow diagram|
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 ﬁrst 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.
The above code consists of:
- Declared and initialized a Counter variable with the int type and assigned an initial value of 0 to it,
- First time in the beginning, the loop body executes at least once irrespective of the condition being true or false.
- The Boolean expression is evaluated at the bottom of the code block when encountered.
- The Boolean condition
(counter < 4)will repeatedly execute until the counter is less than 4.
- 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.
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 …