How to use C# while and do while loops with examples

The while loop

The C# while loop is one of the available loops in the C Sharp, like in other programming languages. The C# while loop executes given statement or block of code repeatedly until the given condition is true. After the condition is evaluated as false, the execution will get out of the while loop to the next line of code in the program. In the while loop, if the condition is false at first check the code inside the while loop will not be executed.

Syntax of while loop    

Following is the general syntax to use while loop in C#:

While (condition){

 

                //Code to be executed;

                //Update the counter;

}

Where:

  • The while keyword is followed by the parenthesis.
  • The condition will be evaluated in each iteration. If the condition is true the given block of code will be executed inside the while loop.
  • After that, update_the_counter part, that can be an increment or decrement operator is executed.

A while loop example

Following is an example of using C# while loop. A variable inta is declared with the value of 1. The condition is set to run the while loop of C# until the inta value is less than or equal to 10. See the code and output by clicking the link below.

A while loop example with the decrement operator

Following example uses decrement operator in the update counter of the while loop. See the example by clicking the link below:

You can see, values of variable inta are displayed from 10 to 1 by using the decrement in the counter update of the while loop.

The do while loop

C# do while is another type of the loop available in the C Sharp programming. The do while is just like the while loop, except in that case the statement or block of code inside the do while will be executed at least once. The reason that code inside the loop will be executed at least once is because the condition is checked after the first iteration.

See example below to learn more but first let us look at its syntax.

do while syntax

Following is the syntax to use do while in C#:

do {

                //Code to be executed;

                //Update the counter;

}

while (condition);

C# do while example

Following is a do while loop example in C#. We have declared a variable inta with an initial value of 11. This is followed by a do..while loop where it will check if inta value is less than or equal to 10.  See example code and output by clicking the link:

You can see in the output, it will display the value of inta = 11. Although this is false in the do..while condition but as do..while at least executes the block inside the loop once and then meets the condition, so the value of the variable is displayed.

Also see C# if | C# for

Was this article helpful?

Related Articles

Leave A Comment?