C# while loop

The C# while loop is one of the available loops in the C Sharp like in other programming languages. The while loop executes the 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 execute.

Syntax of while loop    

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

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 execute inside the while loop.
  • After that, update_the_counter part, that can be an increment or decrement operator, is executed.

An example of C# while loop

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 until the inta value is less than or equal to 10. See the code and output by clicking the link below.

See online demo and code

A while loop example with the decrement operator

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

See online demo and code

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

The C# do while loop

The 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 execute 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.

The reason that code inside the loop will execute at least once is because the condition is checked after the first iteration.

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

do while syntax

Following is the syntax of using the do while loop:

An example of do while C#

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

See online demo and code

You can see in the output, it will display the value of inta = 11. Although this is false in the do..while condition, however, 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.