Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Control Flow and Procedures

Loops in VB.NET

Repeat work in Visual Basic .NET with For...Next, For Each, While, Do...Loop (While and Until), Exit and Continue statements, nested loops, Step values and the most common loop mistakes.

A loop repeats a block of statements. Without loops you would copy code to process 100 items; with them, one block handles any number. VB.NET offers four loop forms: For...Next for counting, For Each for walking through a collection, and While / Do...Loop for repeating while a condition holds. Listings are VB.NET (read-only); runnable C# stand-ins reproduce each loop.

For...Next: counting loops

VB
For i As Integer = 1 To 5
    Console.Write(i & " ")
Next
' 1 2 3 4 5

The counter runs from the start value to the end value inclusive. Declaring it inline (i As Integer) limits it to the loop. Step changes the increment, including counting down:

VB
For i As Integer = 0 To 100 Step 25
    Console.Write(i & " ")        ' 0 25 50 75 100
Next

For i As Integer = 5 To 1 Step -1
    Console.Write(i & " ")        ' 5 4 3 2 1
Next

The start, end and step are evaluated once, before the loop begins. Changing the end variable inside the loop does not change how often it runs. Avoid modifying the counter inside the body.

You can also loop with Double and Decimal counters, but floating-point rounding can make you miss the end value (For x = 0 To 1 Step 0.1 may stop at 0.9999999). Count with integers and compute the real value inside.

C# Stand-in (C#): For...Next with Step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For Each: walking a collection

For Each visits every element of an array or any collection without an index:

VB
Dim names() As String = {"Ada", "Linus", "Grace"}

For Each name As String In names
    Console.WriteLine(name.ToUpper())
Next

Dim total As Integer = 0
For Each n As Integer In {4, 8, 15, 16}
    total += n
Next
Console.WriteLine(total)      ' 43

The loop variable is read-only in effect: you cannot assign to it to change the collection, and you must not add or remove items of the collection while iterating (that throws InvalidOperationException). Use a counting For over indexes, or build a new list, when you need to modify.

Strings are sequences of Char, so For Each ch As Char In "hello" works.

While and Do...Loop

While tests the condition before each iteration:

VB
Dim n As Integer = 1
While n < 100
    n *= 2
End While
Console.WriteLine(n)        ' 128

Do ... Loop has four forms. While runs as long as the condition is true; Until runs until it becomes true. Putting the test at the end (after Loop) guarantees at least one pass:

VB
Do While n > 1             ' test first
    n \= 2
Loop

Do Until n >= 10           ' test first, opposite sense
    n += 3
Loop

Dim answer As String
Do                         ' body runs at least once
    Console.Write("Type yes to continue: ")
    answer = Console.ReadLine()
Loop Until answer = "yes"

Use Do ... Loop Until for "ask until the input is valid" situations. Use While or For when the loop may run zero times.

C# Stand-in (C#): while, do-until and at-least-once loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Exit and Continue

Each loop kind has an Exit and a Continue statement named after it:

  • Exit For, Exit While, Exit Do leave the loop immediately.
  • Continue For, Continue While, Continue Do skip to the next iteration.
VB
For Each value As Integer In {3, 8, -1, 5, 12}
    If value < 0 Then Continue For       ' skip negatives
    If value > 10 Then Exit For          ' stop completely
    Console.WriteLine(value)             ' prints 3, 8, 5
Next

Exit Sub and Exit Function leave the whole procedure; Return does the same in modern code.

A classic search pattern uses Exit For as soon as the item is found:

VB
Dim found As Boolean = False
For i As Integer = 0 To names.Length - 1
    If names(i) = "Linus" Then
        found = True
        Exit For
    End If
Next
C# Stand-in (C#): continue and break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Nested loops

A loop inside a loop runs its body (outer count x inner count) times. Use different counter names, and remember Exit For leaves only the innermost loop.

VB
For row As Integer = 1 To 3
    For col As Integer = 1 To 4
        Console.Write((row * col).ToString().PadLeft(3))
    Next
    Console.WriteLine()
Next

This prints a small multiplication table:

TEXT
  1  2  3  4
  2  4  6  8
  3  6  9 12

To leave both loops, set a flag, use a Function with Return, or restructure the logic.

Infinite loops and other mistakes

  • A condition that never becomes false: Do While True with no Exit Do, or forgetting to change the variable the condition tests. In a console program stop with Ctrl+C.
  • Off-by-one with array indexes: the last valid index is names.Length - 1, so For i = 0 To names.Length fails.
  • Modifying a collection inside For Each.
  • Using a floating-point counter.
  • Doing expensive work inside the condition: store it in a variable once.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many times does For i = 1 To 5 run its body?

    The end value is inclusive: i takes the values 1, 2, 3, 4 and 5.
  2. 2. Which loop always runs its body at least once?

    When the test is placed after Loop the body runs once before the first check.
  3. 3. What does Continue For do?

    Continue For jumps to the next iteration; Exit For ends the loop.
  4. 4. Which For loop visits all indexes of an array named a?

    Indexes start at 0 and the last one is Length - 1.
  5. 5. What happens if you add an item to a List inside For Each over that same list?

    Changing a collection while it is being enumerated invalidates the enumerator.

Summary

  • For...Next counts (inclusive end, optional Step); For Each walks collections; While and Do...Loop repeat on conditions.
  • A test after Loop guarantees one pass; Until is the opposite of While.
  • Exit For/While/Do stop a loop; Continue For/While/Do skip to the next pass.
  • Watch for off-by-one errors, floating-point counters, infinite loops and collection changes during enumeration.

Next: Subs and Functions