Learn C# · lesson 18 of 61 · about 8 minutes
while and do-while
Fight a wave of Slimes while there are Slimes left and the hero is still standing: repeat code while a condition stays true, and use do-while when the body must run at least once.
What you'll learn
- Write a while loop
- Avoid infinite loops
- Use do-while for at-least-once loops
A wave of Slimes
The first Slime is beaten, but three more slide out of the walls. Each one the hero beats bites on the way down, taking 6 HP. The fight goes on while there are Slimes left and the hero is still standing, and nobody knows in advance which runs out first. That's the job of a while loop.
Repeating
while (condition) { ... } checks first and repeats while true. Something inside must change, or it never stops. do { ... } while (condition); runs the body first, then checks, so it always runs at least once. Note the semicolon after its while.
Countdown and a menu
int n = 3;
while (n > 0)
{
Console.Write($"{n}... ");
n--;
}
Console.WriteLine("Lift off!");
string choice;
do
{
choice = Console.ReadLine() ?? "q";
Console.WriteLine($"You chose {choice}");
} while (choice != "q");Output
3... 2... 1... Lift off!
You chose a
You chose b
You chose qStep through it: a hero with 10 HP against three Slimes
int heroHp = 10;
int wave = 3;
while (wave > 0 && heroHp > 0)
{
wave--;
heroHp = Math.Max(0, heroHp - 6);
Console.WriteLine($"Hero HP: {heroHp}, Slimes left: {wave}");
}
Console.WriteLine(heroHp > 0 ? "The wave is over!" : "You were knocked out...");Output
Hero HP: 4, Slimes left: 2
Hero HP: 0, Slimes left: 1
You were knocked out...while or do-while?
Use while when the body might not need to run at all: a hero with 0 HP can't fight anyone. Use do-while when the body has to run before there's anything to check, like asking a question before you can test the answer.
Tip
Check every way out of a loop. The wave ends when the Slimes run out or the hero falls, and every lap takes one Slime away, so it can't go on forever.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.