Skip to content
AgileLogics
4 min read

Do and While Loops

Prerequisites: For and For Each loops

Use a Do loop when you don't know in advance how many times to repeat.

Do While ... Loop

Module Program
    Sub Main()
        Dim balance = 1000D
        Dim years = 0
        Do While balance < 2000D
            balance *= 1.07D
            years += 1
        Loop
        Console.WriteLine($"Doubled after {years} years: {balance:F2}")
    End Sub
End Module
Doubled after 11 years: 2104.85

The condition is checked before each pass, so the body may run zero times.

Do ... Loop Until

Put the condition at the end to run the body at least once:

Module Program
    Sub Main()
        Dim n = 27
        Dim steps = 0
        Do
            If n Mod 2 = 0 Then
                n \= 2
            Else
                n = 3 * n + 1
            End If
            steps += 1
        Loop Until n = 1
        Console.WriteLine($"Reached 1 after {steps} steps")
    End Sub
End Module
Reached 1 after 111 steps

All four forms exist: Do While cond ... Loop, Do Until cond ... Loop, Do ... Loop While cond, and Do ... Loop Until cond. Until is simply "while not".

Exit Do and endless loops

Module Program
    Sub Main()
        Dim attempts = 0
        Do
            attempts += 1
            Console.WriteLine($"attempt {attempts}")
            If attempts = 3 Then Exit Do
        Loop
        Console.WriteLine("done")
    End Sub
End Module
attempt 1
attempt 2
attempt 3
done

A Do ... Loop with no condition runs until Exit Do — common for menus and "read until the user types quit" programs.

While ... End While

While cond ... End While is an older form equivalent to Do While cond ... Loop. You'll see it in existing code; Do While is more flexible (it supports Exit Do and the Until variants).

  • Make sure something in the loop changes the condition, or it never ends. Press Ctrl + C to stop a runaway console program.