C# While Loop

C# While Loop

Loops can execute a block of code as long as a specified condition is reached. They are incredibly useful for saving time, reducing code duplication, and iterating over data.


The while Loop

The while loop loops through a block of code as long as a specified condition is true.

In the example below, the code in the loop will run over and over again as long as a variable i is less than 5.

While Loop Example

using System;

class Program { static void Main() { int i = 0; while (i < 5) { Console.WriteLine(i); i++; // Increase i by 1 each time } } }

Warning: Always remember to increase (or decrease) the variable used in the condition (like `i++`), otherwise the loop will never end! This is called an infinite loop and it will crash your application.


The do...while Loop

The do...while loop is a variant of the while loop. The key difference is that this loop will execute the code block once, before checking if the condition is true, and then it will repeat the loop as long as the condition is true.

Because the condition check happens at the bottom of the loop, the code inside is guaranteed to run at least one time, even if the condition is false to begin with!

Do-While Loop Example

using System;

class Program { static void Main() { int i = 0; do { Console.WriteLine(i); i++; } while (i < 5); } }


Exercise

?

Which loop will always execute its code block at least once?