Need to repeat something until a condition changes? That's a while loop. It's the simplest loop around — check a condition, run the body, check again, repeat.
The while Loop
The condition is tested before each iteration. If it's true, the body runs. Then the condition is checked again. If it's false from the start, the body never runs.
using System;
class Program {
static void Main() {
int i = 1;
while (i <= 5) {
Console.WriteLine("Count: " + i);
i++;
}
}
}
Try it Yourself →
Condition Is Checked First
Because while checks before it runs, it's called a pre-test loop. If the condition starts false, you get zero iterations.
using System;
class Program {
static void Main() {
int i = 10;
while (i <= 5) {
Console.WriteLine("This won't print");
i++;
}
Console.WriteLine("Loop skipped because 10 > 5");
}
}
Try it Yourself →
Infinite Loops
If the condition never becomes false, the loop runs forever. Sometimes intentional (game engines, servers), but usually a bug you'll want to avoid.
using System;
class Program {
static void Main() {
int i = 1;
while (true) {
Console.WriteLine("This goes on forever...");
i++;
if (i > 5) break;
}
}
}
Try it Yourself →