Loops

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.


C# While Loop

Loop while entering the code block as long as the specified condition is True:

Syntax
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:

Example
int i = 0;
            while (i < 5) 
            {
              Console.WriteLine(i);
              i++;
            }
            

The Do/While Loop

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.

Syntax
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:

Example
int i = 0;
do
{ Console.WriteLine(i); i++; } while (i < 5);