Repeat

Loop

A loop repeats a block of code multiple times. Instead of writing the same code over and over, you write it once and tell the program how many times — or under what condition — to repeat it.

Without loops, a program runs each line exactly once. With loops, it can repeat work automatically.

Types of Loops#

While Loop#

Repeats as long as a condition is true. Used when you don’t know in advance how many times to repeat.

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.