What a while loop does
A while loop runs a block of statements again and again, as long as a condition is true. You use it when you know the rule for stopping but not necessarily how many repetitions that takes, and also for simple counting, as in this lesson.
while (condition) {
// statements that repeat
}
The condition must be a bool expression, such as count <= 5. C# doesn't treat numbers as true or false, so while (1) doesn't compile. The braces hold the loop body.
A first example
int count = 1;
while (count <= 5) {
Console.WriteLine("I made a mistake");
count++;
}
Console.WriteLine("Finished!");
This prints I made a mistake five times, and then Finished! once. The loop has three ingredients, and a counting loop needs all of them:
- Initialization.
int count = 1;creates the variable before the loop starts. - Condition.
count <= 5is checked before every pass, including the first. - Update.
count++changes the variable inside the body, moving the loop toward the point where the condition is false.
What the computer does
| Check | count | Condition | Action |
|---|---|---|---|
| 1 | 1 | 1 <= 5 true | print, count becomes 2 |
| 2 | 2 | 2 <= 5 true | print, count becomes 3 |
| 3 | 3 | 3 <= 5 true | print, count becomes 4 |
| 4 | 4 | 4 <= 5 true | print, count becomes 5 |
| 5 | 5 | 5 <= 5 true | print, count becomes 6 |
| 6 | 6 | 6 <= 5 false | leave the loop |
After the sixth check, the program continues with the first statement after the closing brace, which prints Finished!. That statement runs once because it isn't part of the body.
You can think of a while loop as an if statement that jumps back and asks the question again after each run of its body.
Two behaviours worth knowing
- The condition is checked first. If it is false at the very start, the body never runs. With
int n = 10;andwhile (n < 5), nothing is printed. - The check happens only between passes. If the condition becomes false in the middle of the body, the rest of that pass still runs. The loop ends at the next check.
Loops that don't count to a fixed number
The condition doesn't have to compare against a constant count. A while loop can run until some state is reached. This one halves a number until it reaches 1, counting the halvings:
int n = 100;
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
Console.WriteLine(steps + " " + n); // 6 1
Here the number of passes isn't written anywhere in the code. It comes from the data. Integer division discards the remainder, so 100 becomes 50, 25, 12, 6, 3, 1. That's six passes. This is the kind of job a while loop suits best: you know when to stop, but not how many passes that takes in advance.
The exercise, step by step
The task is to print I promise to learn coding. five times using a loop.
- Declare the counter.
int counter = 1;starts at 1, so the first pass counts as pass number 1. - Write the loop header.
while (counter <= 5)keeps going for the values 1, 2, 3, 4 and 5. That's five passes. - Print inside the body.
Console.WriteLine("I promise to learn coding.");runs on every pass. - Update the counter.
counter++;adds 1 after the print. Without it,counterstays 1, the condition is always true, and the loop never ends.
int counter = 1;
while (counter <= 5) {
Console.WriteLine("I promise to learn coding.");
counter++;
}
Common mistakes
- Forgetting the update. This creates an infinite loop. The program keeps printing until you stop it.
- Off-by-one errors. Starting at 0 with
counter <= 5prints six times. Starting at 1 withcounter < 5prints four times. Count the values the condition allows. - Using
=instead of==or a comparison. In C#,while (counter = 5)is a compile error, because the assignment isn't abool. - Putting a semicolon after the condition.
while (counter <= 5);makes an empty loop body. The braces below it then run once, after the loop. The compiler warns about this.
Key takeaways
while (condition) { ... }repeats its body as long as the condition is true.- A counting loop needs initialization, a condition and an update.
- The condition is checked before every pass, so the body may run zero times.
- If the update is missing, the loop never ends.