CodeBlanks Logo Icon CodeBlanks

The do-while loop

C# course · Beginner · Lesson 44/116

Learn loops that run at least once with do-while.

The do-while loop

The do-while loop runs the body FIRST and checks the condition AFTER. So the body always runs at least once. It is written do { ... } while (n > 0);.

For example, it is ideal for showing a menu at least once and looping until the user asks to stop. Unlike while, the first pass always happens even when the condition is false; you use it when you want to take one step before checking the result.

while vs do-while

Because while checks the condition first, the body may not run at all. do-while runs the body once and then checks the condition; so it always runs at least once.

For example, int n = 10; while (n < 5) { ... } never runs the body. The same condition with do-while would run the body once and then stop. This small difference creates a big behavior gap.

Exercise At least once with do-while

Declare an n variable with the value 0. Use a do-while loop: in the body print n, then increment with n++. The condition is n < 3. The output should be 0, 1, 2 (the body runs at least once).

Show example solution
Write int n = 0; do { Console.WriteLine(n); n++; } while (n < 3);
Example solution:
using System;

class Program
{
    static void Main()
    {
        int n = 0;
        do
        {
            Console.WriteLine(n);
            n++;
        }
        while (n < 3);
    }
}

Test yourself

  1. Match each loop type to its feature

    for
    Counter, counted repeat
    while
    Condition first, zero runs possible
    do-while
    Body first, at least once
    foreach
    Collection elements
  2. How many times does int n = 10; do { Console.WriteLine(n); } while (n < 5); print?

    int n = 10;
    do { Console.WriteLine(n); } while (n < 5);
    • Never
    • 5 times
    • 10 times
    • 1 time
    Show answer

    1 time — Correct. do-while runs the body once, then the condition is false and it stops.

  3. Write the do-while terminator

    int n = 0;
    do
    {
        Console.WriteLine(n);
        n++;
    }
    ____ (n < 3);
    Show answer
    int n = 0;
    do
    {
        Console.WriteLine(n);
        n++;
    }
    while (n < 3);

All lessons in Beginner