C# ยท Chapter 18 of 46

C# While & Do-While Loops

A while loop repeats a block of code as long as its condition remains true. The condition is checked before each iteration, so the loop body might never run if the condition starts false.

A do-while loop is similar, but it checks the condition after running the loop body, guaranteeing the code runs at least once.

Syntax
while (condition) {
  // code
}

do {
  // code
} while (condition);

while loop

A while loop checks its condition before each pass. If the condition is false from the start, the loop body never executes.

do-while loop

A do-while loop executes the body first, then checks the condition. This guarantees at least one execution, useful for things like input validation menus.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int i = 0;
    while (i < 3) {
      Console.WriteLine(i);
      i++;
    }
  }
}
Output
0
1
2

The loop prints i and increments it until the condition i < 3 becomes false.

Example 2 (csharp)
using System;

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

The do-while runs the body once (printing 5) before checking the false condition.

Key points

  • while checks the condition before each iteration.
  • do-while checks the condition after each iteration, so it runs at least once.
  • Loops need a way to eventually make the condition false to avoid infinite loops.
  • The increment/decrement operators (++/--) are commonly used with loops.
๐Ÿ’ก Note: An infinite loop happens when the condition never becomes false โ€” always make sure your loop variable changes inside the loop.

๐Ÿ“ Quick Quiz

1. When is a while loop's condition checked?

2. What guarantees at least one execution of the loop body?

3. What can cause an infinite loop?