Lesson 20 +10 XP

While & Do-While Loops

While & Do-While Loops

Loops run the same block of code over and over while a condition is true.

The while loop

The while loop checks the condition first, then runs the code:

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

This prints 0 1 2 3 4. Once i reaches 5, the condition is false and the loop stops.

Important: update the counter

If i++ were missing, i would stay 0 forever and the loop would run endlessly (infinite loop). Always make sure the condition can eventually become false.

The do...while loop

do...while runs the code first, then checks the condition. The code always runs at least once:

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

while vs do...while

  • while: condition checked before the block - may run zero times.
  • do...while: block runs, then condition is checked - always runs at least once.

TL;DR

  • while loops while a condition is true.
  • Always update the counter to avoid infinite loops.
  • do...while always runs the block at least once.