C# While Loop Tutorial For Beginners With Examples

C# while loops execute a block of code repeatedly until a specific condition is true.

Type of while Loops in C#

There are two type of while loops in C#:
  • while loop
  • do...while loop

C# while Loop

A C# while loop iterates through a block of code until a specific condition is true.
The syntax of a while loop is shown below:
while(condition)
{
    Code to be executed;
}              
The example below sets a variable iCount to 1 and then checks whether the value of iCount is less than or equal to 10. The iteration stops once the value of the variable iCount becomes greater than 10.
    int iCount = 1;

    while (iCount <= 10)
    {
        Console.WriteLine(iCount);
        iCount++;
    }
    

C# do...while Loop

In a C# do...while loop first the block of code inside do...while statement gets executed and then the condition is checked. If the condition is true then the loop is repeated.
The syntax of a do...while loop is shown below:
do
{
    Code to be executed;

}while(condition);    
The below example displays the numbers from 1 to 10.
    int iCount = 1;

    do
    {                
        Console.WriteLine(iCount);
        iCount++;

    } while (iCount <= 10);
    
In the above example first the value of variable iCount is displayed in the console window and then the value of iCount is incremented. The condition to check if the value of iCount is less than or equal to 10 is evaluated at the end of the iteration.
The code block inside a do...while loop always get executed once.