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.
count = 0
while count < 3:
print(count)
count += 1let count = 0;
while (count < 3) {
console.log(count);
count++;
}Compound Conditions#
The condition can combine multiple checks using logical operators. The loop continues only when all required conditions are met:
while (playerWins < 2 && computerWins < 2)
{
// play a round
}The loop stops as soon as either player reaches 2 wins.
while player_wins < 2 and computer_wins < 2:
# play a roundwhile (playerWins < 2 && computerWins < 2) {
// play a round
}Breaking Out of a Loop#
Sometimes you need to stop a loop based on something that happens inside it, not just the condition at the top. The break statement exits the loop immediately, regardless of the condition.
Common Mistakes#
Infinite loop — condition never becomes false
If nothing inside the loop changes the variables used in the condition, the condition stays true forever and the program hangs. Always make sure something inside the loop moves it toward the exit condition.
Off-by-one in the condition
while (count < 3) runs for 0, 1, 2 — three iterations. while (count <= 3) runs four. Choose < or <= carefully based on whether the boundary value should be included.
Modifying the wrong variable
If the loop condition checks playerWins but only computerWins is incremented inside, the loop may never exit. Make sure every variable in the condition can actually change.
Checking the condition after it’s already false
The condition is checked at the start of each iteration, before the loop body runs. If the condition is already false before the loop is reached, the loop body never runs at all.