Do-While Loop
Run a block of code at least once, then repeat it while a condition is true, with C#'s do-while loop.
Apprentice · C# · Updated
After this lesson you can
- Run code at least once, then repeat it, with a do-while loop
Key takeaways
- A
do-whileloop runs its block first and checks the condition after, so the block always runs at least once. - The condition comes at the end, followed by a semicolon:
while (roll > 4);. - Use
do-whilewhen something must happen once before you can ask "again?", such as showing a menu.
A do-while loop is a while loop turned upside down. It runs its block first, and checks the condition after. So its block always runs at least once.
The shape
int roll = 6;
do
{
Console.WriteLine("You rolled a " + roll);
roll--;
}
while (roll > 4);
You rolled a 6
You rolled a 5
The condition comes at the end, after while, and is followed by a semicolon.
At least once
Compare the two loops when the condition is false from the start:
int ticketsLeft = 0;
while (ticketsLeft > 0)
{
Console.WriteLine("while: selling a ticket");
ticketsLeft--;
}
do
{
Console.WriteLine("do-while: selling a ticket");
ticketsLeft--;
}
while (ticketsLeft > 0);
do-while: selling a ticket
The while loop checks first and never runs. The do-while runs once before it checks.
A menu that shows at least once
do-while fits whenever something must happen once before you can decide whether to repeat it. A menu is the classic case: you have to show it before the user can choose to quit.
string? choice;
do
{
Console.WriteLine("1) Show scores");
Console.WriteLine("2) Add a score");
Console.WriteLine("Q) Quit");
Console.Write("Choose: ");
choice = Console.ReadLine();
if (choice == "1")
{
Console.WriteLine("Showing scores...");
}
else if (choice == "2")
{
Console.WriteLine("Adding a score...");
}
}
while (choice != "Q" && choice != "q" && choice != null);
Console.WriteLine("Goodbye.");
The menu always shows once; it repeats until the user types Q. (The choice != null part stops the loop if there's no more input at all.)
Check yourself
2 questions to try on the lesson page.
So what
Choose do-while when the block has to run before the question "again?" makes sense: menus, games, and asking for input until it's valid.