C# While Loop
Loops let you run the same block of code over and over without copying and pasting it. The while loop is the simplest kind: it keeps repeating as long as a condition stays true. It is perfect for situations where you don't know in advance exactly how many times you need to repeat something.
The while Loop
A while loop checks a condition before each pass. If the condition is true, the code inside the curly braces runs. Then the condition is checked again, and this repeats until the condition becomes false. Each single pass through the loop body is called an iteration.
Counting from 0 to 4
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}In the example above, i starts at 0. As long as i is less than 5, the loop prints the value and then adds 1 to i with i++. Once i reaches 5, the condition i < 5 is false and the loop stops. The output is the numbers 0, 1, 2, 3, and 4.
The do/while Loop
The do/while loop is a variation that checks the condition at the end instead of the beginning. This guarantees the code block runs at least one time, even if the condition is false from the start.
do/while runs at least once
int i = 0;
do
{
Console.WriteLine("Value is: " + i);
i++;
}
while (i < 3);while vs do/while
Use a plain while loop when it is okay to skip the body completely. Use do/while when the action must happen at least once, such as showing a menu before asking the user if they want to continue.
Exercise: C# While Loop
What's the key difference between a C# while loop and a do...while loop?