C# Tutorials
C# Methods
C# Classes
C# Examples
Loops can create a code block as long as the specified condition is reached.
Loops work because they save time, reduce errors, and make the code more readable.
Loop while entering the code block as long as the specified condition is True:
while (condition)
{
// code block to be executed
}
In the example below, the code in the loop will apply, repeatedly, as long as the variable (i) is less than 5:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
The do/while loop is a type of loop while. This loop will use a code block and, before checking that status is true, will re-loop as long as the status is true.
do
{
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be used at least once, even if the situation is false, because the code block is used before the status check:
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);