While

While Loop

A while loop repeats a block of code as long as a condition is true. Each time the block finishes, the condition is checked again. When it becomes false, the loop stops.

For a broader introduction to loops, see Loop.

  ┌─────────────────┐
  │   check condition│◄──────┐
  └────────┬────────┘        │
      true │  false          │
           ▼      ▼          │
    ┌────────────┐  exit      │
    │ loop body  │───────────┘
    └────────────┘

Basic While Loop#

int count = 0;

while (count < 3)
{
    Console.WriteLine(count);
    count++;
}

Output: 0, 1, 2. When count reaches 3, the condition count < 3 becomes false and the loop stops.