The while loop
Learn loops that run while a condition holds with while.
The while loop
For loops that run as long as a condition holds you use while. It is written while (n > 0) { ... }; the condition is checked before each step, and the loop ends when it becomes false.
Unlike for, there is no counter; you must update something in the body that moves the condition forward. Otherwise you get an infinite loop. While is preferred when the number of iterations is not known in advance.
Moving the condition forward
In a while loop the body must move the condition toward false. A decrement like n--, an increment like i++ or reading a new value like line = Console.ReadLine() does this.
Without progress the condition stays true and the program falls into an infinite loop. So when writing while, answer the question 'when will the condition become false?'.
Exercise Count down from 5 to 1
Declare an n variable with the value 5. Use a while loop: while n > 0, print n and decrement with n--. The output should be 5, 4, 3, 2, 1.
Show example solution
Write int n = 5; while (n > 0) { Console.WriteLine(n); n--; }
Example solution:
using System;
class Program
{
static void Main()
{
int n = 5;
while (n > 0)
{
Console.WriteLine(n);
n--;
}
}
}
Test yourself
-
Write the while condition
int n = 5; while (____) { Console.WriteLine(n); n--; }Show answer
int n = 5; while (n > 0) { Console.WriteLine(n); n--; } -
What kind of loop is while (i < 3) { ... }?
int i = 0; while (i < 3) { ... }- Infinite loop
- Condition first, zero runs possible
- Body runs at least once
- Counter based
Show answer
Condition first, zero runs possible — Correct. while checks the condition first; if it is false from the start, the body never runs.
-
Match each loop feature
- while
- Condition first
- do-while
- Body first
- for
- Counter based
- foreach
- Collection based