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

By

After this lesson you can

  • Run code at least once, then repeat it, with a do-while loop
  • Skip the rest of a while or do-while loop's turn with continue, changing the loop's variable before it

Key takeaways

  • A do-while loop 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-while when something must happen once before you can ask "again?", such as showing a menu.
  • In a while or do-while, continue skips the rest of the turn and jumps to the condition check. Change the loop's variable before any continue, or the loop never moves on.

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.)

Skipping a turn: continue in while and do-while

The box office sells seats 1 to 6, one at a time, but the chair in seat 4 is broken. The loop has to pass over seat 4 and carry on with seat 5. You could wrap the selling in if (seat != 4), and that works while the selling is one line. As the selling grows (print the ticket, take the payment, mark the seat taken), everything ends up nested inside that if.

C# has a keyword for "skip the rest of this turn": continue. When a loop reaches continue, it stops the current pass through its block and goes on to the next one. In a while or a do-while, "the next one" starts with the condition check: if the condition is still true, the block runs again from the top.

int seat = 0;

while (seat < 6)
{
    seat++;

    if (seat == 4)
    {
        continue;
    }

    Console.WriteLine("Selling seat " + seat);
}
Selling seat 1
Selling seat 2
Selling seat 3
Selling seat 5
Selling seat 6

When seat is 4, continue skips the Console.WriteLine line and jumps to the check seat < 6. It's still true, so the next pass makes seat 5.

The trap: change the loop's variable before continue. Here is the same loop with seat++ moved to the bottom of the block:

int seat = 1;

while (seat <= 6)
{
    if (seat == 4)
    {
        continue;
    }

    Console.WriteLine("Selling seat " + seat);
    seat++;
}

It sells seats 1, 2 and 3, then never prints again and never ends. At seat 4, continue jumps back to the check before seat++ runs, so seat stays 4, the check stays true, and continue skips the seat++ again, forever. Press Ctrl+C to stop a program stuck like this. The fix is the first version's order: change the variable the condition checks before any continue that could skip the change.

A do-while works the same way, except that its check is at the bottom: continue jumps down to while (...), not back up to do.

int roll = 0;

do
{
    roll++;

    if (roll % 2 == 0)
    {
        continue;
    }

    Console.WriteLine("Odd roll: " + roll);
}
while (roll < 5);
Odd roll: 1
Odd roll: 3
Odd roll: 5

roll % 2 == 0 is true for an even roll (the remainder after dividing by 2 is 0), so even rolls are skipped. After each continue, the loop checks roll < 5 and goes again while it's true.

Do it: count the scoreboard's digit boxes

A scoreboard shows each score in boxes, one digit per box. To set it up, the program needs to know how many boxes a score takes.

The method gets one value:

  • score: a team's score, an int (105). It's never below 0.

Each time through the loop, count one digit, then drop the score's last digit by dividing it by 10. (Dividing two ints keeps only the whole part, so 105 / 10 is 10.) For example, with 105:

Time through score at the start Digits counted score / 10
1 105 1 10
2 10 2 1
3 1 3 0

The score is now 0, so the loop stops, and DigitCount(105) returns 3.

A score of 0 still needs one box, to show the 0. That's why the loop must run at least once.

Your job: write the method int DigitCount(int score) with a do-while loop.

  • Each time through, add 1 to the count and divide the score by 10.
  • Go again while the score is more than 0.
  • Return the count.
  • A score of 0 returns 1.

Practiced live on the lesson page: write the C# right there and check it.

Do it: total the tickets, skipping the canceled shows

The box office keeps one number for each show this week: how many tickets it sold. A show that was canceled is marked -1 instead, because it sold nothing and shouldn't count. Write a method that totals the tickets sold at the shows that went ahead.

The method gets one value:

  • ticketsPerShow: the tickets sold at each show, in order, an int[] ({ 40, -1, 25, 30 }). A canceled show is -1.

For example, with { 40, -1, 25, 30 }:

Index Tickets Canceled? Total after it
0 40 No: add it 40
1 -1 Yes: skip it 40
2 25 No: add it 65
3 30 No: add it 95

So TotalSold(new[] { 40, -1, 25, 30 }) returns 95.

Your job: write the method int TotalSold(int[] ticketsPerShow) with a while loop that visits every index, from 0 to the last.

  • When a show is canceled (-1), skip it with continue.
  • Add every other show's tickets to the total.
  • Return the total.
  • When every show is canceled, or there are no shows at all, return 0.

Practiced live on the lesson page: write the C# right there and check it.

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. And when one turn of a loop should be skipped, continue skips it, as long as the loop's variable has already moved on.

Key terms

Cheat sheets