Lesson 15 · Looping

Looping

Master all five loop structures in VB 2026 — For..Next, For Each..Next, Do While..Loop, Do Until..Loop, and Do..Loop While/Until — plus Exit, Continue, nested loops, and .NET 10 LINQ-based iteration alternatives.

Key Takeaway: Choose the right loop for the job: use For..Next when you know the exact count, For Each when iterating a collection, Do While when you might iterate zero times, and Do..Loop While when you need to run at least once. Always ensure loops have a termination condition to prevent infinite loops. Use Exit For / Exit Do to break early and Continue For / Continue Do to skip the current iteration.
COUNT-CONTROLLED

For..Next

Known number of iterations. Counter increments automatically.

COLLECTION

For Each..Next

Iterates every item in a collection, array, or List. No index needed.

CONDITION: CHECK FIRST

Do While..Loop

Tests condition before body. May run zero times.

CONDITION: CHECK FIRST

Do Until..Loop

Runs until condition becomes True. Inverse of Do While.

CONDITION: CHECK LAST

Do..Loop While/Until

Tests condition after body. Runs at least once guaranteed.

15.1 For..Next Loop

The For..Next loop executes a block a fixed number of times. The counter variable starts at start, increments by Step after each iteration (default step is 1), and stops when it passes end.

ForNext.vb — Visual Basic 2026
' Basic For..Next (1 to 10)
For i As Integer = 1 To 10
    lstNumbers.Items.Add(i)
Next

' Custom Step: count by 2 (odd numbers)
For i As Integer = 1 To 19 Step 2
    lstOdd.Items.Add(i)       ' 1, 3, 5, 7 ... 19
Next

' Negative Step: count down
For i As Integer = 10 To 1 Step -1
    lblCountdown.Text &= i & " "   ' "10 9 8 7 6 5 4 3 2 1 "
Next

' Sum 1 to N using For..Next
Dim n As Integer
Integer.TryParse(txtN.Text, n)
Dim total = 0
For i As Integer = 1 To n
    total += i
Next
lblSum.Text = $"Sum 1..{n} = {total}"     ' fast closed-form: n*(n+1)/2

' Iterate an array by index
Dim scores() As Integer = {88, 72, 95, 61, 84}
Dim highest = scores(0)
For i As Integer = 1 To scores.Length - 1
    If scores(i) > highest Then highest = scores(i)
Next
lblHighest.Text = $"Highest: {highest}"

' Double Step: 0.0 to 1.0 in steps of 0.1
For t As Double = 0.0 To 1.0 Step 0.1
    lstPercent.Items.Add($"{t:P0}")
Next
Try It — Simulation 15.1: For..Next Loop Visualiser

Set start, end and step — watch cells fill as the counter advances. Try negative step to count down, or step 2 to skip evens.

For..Next Visualiser
Start:
End (To):
Step:

15.2 For Each..Next

For Each iterates over every item in any collection — arrays, List(Of T), Dictionary, ListBox.Items, controls on a form, and more. The loop variable takes the value of each element in turn. No index management needed.

ForEach.vb — Visual Basic 2026
' Iterate a string array
Dim fruits() As String = {"Apple", "Banana", "Cherry", "Durian"}
For Each fruit As String In fruits
    lstFruits.Items.Add(fruit)
Next

' Calculate average from a List(Of Integer)
Dim scores As New List(Of Integer) From {88, 72, 95, 61, 84}
Dim total = 0
For Each s As Integer In scores
    total += s
Next
lblAvg.Text = $"Average: {total / scores.Count:F1}"

' Iterate all TextBoxes on the form to clear them
For Each ctrl As Control In Me.Controls
    If TypeOf ctrl Is TextBox Then
        CType(ctrl, TextBox).Clear()
    End If
Next

' Dictionary iteration
Dim capitals As New Dictionary(Of String, String) From {
    {"Malaysia", "Kuala Lumpur"},
    {"Japan",    "Tokyo"},
    {"France",   "Paris"}
}
For Each kvp As KeyValuePair(Of String, String) In capitals
    lstCapitals.Items.Add($"{kvp.Key}: {kvp.Value}")
Next

' Validate all TextBoxes before form submit
Dim allFilled = True
For Each txt As TextBox In {txtName, txtEmail, txtPhone}
    If String.IsNullOrWhiteSpace(txt.Text) Then
        txt.BackColor = Color.LightPink
        allFilled = False
    Else
        txt.BackColor = Color.White
    End If
Next
btnSubmit.Enabled = allFilled
For Each vs For..Next — when to use each

Use For Each when you only need the value of each element (no index needed). Use For..Next when you need the index (to update elements, compare with neighbours, or build index-dependent output). Never modify a collection while iterating it with For Each — that throws an InvalidOperationException. To remove items while looping, iterate backwards with For i = list.Count - 1 To 0 Step -1.


15.3 Do While..Loop

The Do While loop checks its condition before each iteration. If the condition is False on entry, the body never runs. Ideal for input validation loops and reading data until an end marker is encountered.

DoWhile.vb — Visual Basic 2026
' Basic Do While (count up)
Dim counter = 1
Do While counter <= 10
    lstCount.Items.Add(counter)
    counter += 1             ' MUST advance counter or loop runs forever!
Loop

' Read numbers until sentinel 0
Dim running = True
Dim sumTotal = 0
Do While running
    Dim input = InputBox("Enter a number (0 to stop):")
    Dim n As Integer
    If Integer.TryParse(input, n) AndAlso n <> 0 Then
        sumTotal += n
    Else
        running = False     ' exit condition
    End If
Loop
lblTotal.Text = $"Total: {sumTotal}"

' Collatz sequence: keep halving or tripling until you reach 1
Dim n = 27
Dim steps = 0
Do While n <> 1
    If n Mod 2 = 0 Then
        n = n \ 2           ' even: halve
    Else
        n = 3 * n + 1       ' odd: triple + 1
    End If
    steps += 1
Loop
lblSteps.Text = $"Collatz(27) took {steps} steps"   ' = 111 steps

15.4 Do Until..Loop

Do Until is the logical inverse of Do While: it loops until the condition becomes True (i.e., while the condition is False). Use it when the exit condition reads more naturally as a positive statement.

DoUntil.vb — Visual Basic 2026
' Do Until: runs while counter > 0
Dim counter = 10
Do Until counter = 0
    lstCountdown.Items.Add(counter)
    counter -= 1
Loop

' Equivalent Do While version (both correct, Until reads nicer here)
Do While counter > 0
    lstCountdown.Items.Add(counter)
    counter -= 1
Loop

' Keep asking until valid number entered
Dim age As Integer
Dim valid = False
Do Until valid
    Dim input = InputBox("Enter your age (1-120):")
    If Integer.TryParse(input, age) AndAlso age >= 1 AndAlso age <= 120 Then
        valid = True
    Else
        MsgBox("Please enter a number between 1 and 120.")
    End If
Loop
lblAge.Text = $"Your age: {age}"
Try It — Simulation 15.2: Do Loop Visualiser

Switch between all four Do Loop forms and see condition checking happen before vs after the body. Compare Do While, Do Until, Do..Loop While, Do..Loop Until on the same value.

Do Loop Visualiser
Loop type:
Start:
Limit:

15.5 Do..Loop While / Do..Loop Until

Placing the condition after the loop body guarantees the body runs at least once. This is useful for menus, game loops, and retry scenarios where the first attempt must always execute.

DoLoopWhile.vb — Visual Basic 2026
' Do..Loop While: body runs first, then condition is checked
Dim counter = 1
Do
    lstItems.Items.Add($"Item {counter}")
    counter += 1
Loop While counter <= 5            ' runs 5 times: 1, 2, 3, 4, 5

' Even if condition is false from the start, body runs once
Dim x = 100
Do
    lblDemo.Text = "This always runs!"   ' executes once
    x += 1
Loop While x < 5                  ' False immediately, but body ran once

' Guess the number game -- must try at least once
Dim secret = 42
Dim attempts = 0
Dim guess As Integer
Do
    Dim input = InputBox($"Guess the number (attempt {attempts + 1}):")
    Integer.TryParse(input, guess)
    attempts += 1
    If guess < secret Then MsgBox("Too low!")
    If guess > secret Then MsgBox("Too high!")
Loop Until guess = secret OrElse attempts >= 10
lblResult.Text = $"Got it in {attempts} tries!"

15.6 Exit and Continue

Use Exit For / Exit Do to break out of a loop early, and Continue For / Continue Do to skip the rest of the current iteration and jump to the next.

ExitContinue.vb — Visual Basic 2026
' Exit For: stop as soon as we find what we need
Dim names() = {"Alice", "Bob", "Carol", "Diana"}
Dim found = -1
For i As Integer = 0 To names.Length - 1
    If names(i) = "Carol" Then
        found = i
        Exit For             ' stop searching
    End If
Next
lblResult.Text = If(found >= 0, $"Found at index {found}", "Not found")

' Continue For: skip even numbers, only process odds
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To 20
    If i Mod 2 = 0 Then Continue For   ' skip evens
    sb.Append(i & " ")
Next
lblOdds.Text = sb.ToString()         ' "1 3 5 7 9 11 13 15 17 19 "

' Exit Do: break when a prime is found
Dim start = 50
Do While start < 1000
    If IsPrime(start) Then
        lblPrime.Text = $"First prime >= 50: {start}"
        Exit Do
    End If
    start += 1
Loop
Try It — Simulation 15.3: Exit & Continue Visualiser

Loop 1–20 with a rule applied to each value. Green = processed, red = skipped (Continue For), and the loop stops early when Exit For fires. Try divisible-by-3 skip and stop-at-first-prime.

Exit & Continue Visualiser
Skip rule (Continue For):
Exit rule (Exit For):

15.7 Nested Loops

A loop inside another loop. The inner loop runs its full cycle for every single iteration of the outer loop. Total iterations = outer count × inner count. Classic uses: multiplication tables, 2D arrays, generating combinations.

NestedLoops.vb — Visual Basic 2026
' Multiplication table (3x3)
Dim sb As New System.Text.StringBuilder
For row As Integer = 1 To 10
    For col As Integer = 1 To 10
        sb.Append((row * col).ToString().PadLeft(4))
    Next
    sb.AppendLine()      ' new row
Next
txtTable.Text = sb.ToString()

' Fill 2D array
Dim grid(4, 4) As Integer
For r As Integer = 0 To 4
    For c As Integer = 0 To 4
        grid(r, c) = r * 5 + c
    Next
Next

' Bubble sort (classic nested loop algorithm)
Dim arr() As Integer = {64, 34, 25, 12, 22, 11, 90}
For i As Integer = 0 To arr.Length - 2
    For j As Integer = 0 To arr.Length - 2 - i
        If arr(j) > arr(j + 1) Then
            Dim temp = arr(j)
            arr(j)     = arr(j + 1)
            arr(j + 1) = temp
        End If
    Next
Next
lblSorted.Text = String.Join(", ", arr)   ' "11, 12, 22, 25, 34, 64, 90"
Try It — Simulation 15.4: Nested Loops — Multiplication Table

Nested For..Next generates a multiplication table. Choose the table size (2×2 to 12×12) and watch the outer and inner loop counters tick.

Multiplication Table Generator
Table size (N x N):

15.8 Practical Examples

Example 15.1 — Fibonacci Sequence

Fibonacci.vb — Visual Basic 2026
Private Sub btnFib_Click(sender As Object, e As EventArgs) Handles btnFib.Click
    Dim n As Integer
    If Not Integer.TryParse(txtN.Text, n) OrElse n < 1 OrElse n > 50 Then
        lblResult.Text = "Enter N between 1 and 50." : Return
    End If

    Dim a = 0
    Dim b = 1
    Dim sb As New System.Text.StringBuilder
    sb.Append("0, 1")

    For i As Integer = 3 To n
        Dim next = a + b
        sb.Append($", {next}")
        a = b
        b = next
    Next
    lblResult.Text = sb.ToString()
End Sub

Example 15.2 — Prime Number Sieve (For + Do While)

Primes.vb — Visual Basic 2026
' Find all primes up to N using trial division
Private Function IsPrime(n As Integer) As Boolean
    If n < 2 Then Return False
    If n = 2 Then Return True
    If n Mod 2 = 0 Then Return False
    Dim i = 3
    Do While i * i <= n
        If n Mod i = 0 Then Return False
        i += 2
    Loop
    Return True
End Function

Private Sub btnPrimes_Click(sender As Object, e As EventArgs) Handles btnPrimes.Click
    Dim limit As Integer
    If Not Integer.TryParse(txtLimit.Text, limit) Then Return

    lstPrimes.Items.Clear()
    For i As Integer = 2 To limit
        If IsPrime(i) Then lstPrimes.Items.Add(i)
    Next
    lblCount.Text = $"{lstPrimes.Items.Count} primes found"
End Sub
Try It — Simulation 15.5: Loop Lab

All loop types in one lab — Fibonacci, sum of N, factorial, prime check, and FizzBuzz — each using the most appropriate loop structure.

Loop Lab
Task:
N:

15.9 GitHub Copilot — Loop Patterns

GitHub Copilot — Bubble Sort with Steps
You typed: ' Sort an integer array from txtInput using bubble sort. Show each swap in a ListBox so the user can follow the algorithm step by step.'
' Sort an integer array from txtInput using bubble sort. Show each swap step by step.
Dim parts = txtInput.Text.Split(","c)
Dim arr(parts.Length - 1) As Integer
For i As Integer = 0 To parts.Length - 1
    If Not Integer.TryParse(parts(i).Trim(), arr(i)) Then
        lblError.Text = $"'{parts(i)}' is not a number." : Return
    End If
Next

lstSteps.Items.Clear()
lstSteps.Items.Add($"Start: [{String.Join(", ", arr)}]")

Dim swapped = True
Dim pass = 0
Do While swapped
    swapped = False
    pass += 1
    For j As Integer = 0 To arr.Length - 2 - (pass - 1)
        If arr(j) > arr(j + 1) Then
            Dim temp = arr(j) : arr(j) = arr(j + 1) : arr(j + 1) = temp
            swapped = True
            lstSteps.Items.Add($"Pass {pass}: swap [{j}]<->[{j+1}]  [{String.Join(", ", arr)}]")
        End If
    Next
Loop
lstSteps.Items.Add($"Done ({pass} passes): [{String.Join(", ", arr)}]")
GitHub Copilot — Password Generator with For Each
You typed: ' Generate N unique passwords of length L using a For loop. Each password must have uppercase, lowercase, digit, and special char. Add to lstPasswords.'
' Generate N unique passwords of length L with all character classes.
Dim count As Integer
Dim length As Integer
If Not Integer.TryParse(txtCount.Text, count) OrElse count < 1 Then count = 10
If Not Integer.TryParse(txtLength.Text, length) OrElse length < 8 Then length = 12

Dim upper   = "ABCDEFGHJKLMNPQRSTUVWXYZ"
Dim lower   = "abcdefghjkmnpqrstuvwxyz"
Dim digits  = "23456789"
Dim special = "!@#$%&*"
Dim allChars = upper & lower & digits & special
Dim rng As New Random()

lstPasswords.Items.Clear()
For i As Integer = 1 To count
    Dim chars(length - 1) As Char
    ' Ensure each character class is represented
    chars(0) = upper(rng.Next(upper.Length))
    chars(1) = lower(rng.Next(lower.Length))
    chars(2) = digits(rng.Next(digits.Length))
    chars(3) = special(rng.Next(special.Length))
    For j As Integer = 4 To length - 1
        chars(j) = allChars(rng.Next(allChars.Length))
    Next
    ' Shuffle to avoid predictable first 4 chars
    For k As Integer = length - 1 To 1 Step -1
        Dim swap = rng.Next(k + 1)
        Dim tmp = chars(k) : chars(k) = chars(swap) : chars(swap) = tmp
    Next
    lstPasswords.Items.Add(New String(chars))
Next
Copilot Chat Prompts for This Lesson

Try these in the Copilot Chat panel while writing loop code:

  • "Loop through a ListBox and remove all items where the text starts with 'Error:' using For i = lstLog.Items.Count - 1 To 0 Step -1"
  • "Use For Each to iterate all Labels on the form and reset their Text to empty string and BackColor to default"
  • "Generate a times table from 1 to N using nested For loops and display it in a DataGridView"
  • "Use a Do While loop to read CSV lines from a file until EOF and add each parsed record to a List(Of Student)"

Lesson Summary

  • For..Next: use when the iteration count is known. Supports positive, negative, and fractional Step. Counter variable is scoped to the loop.
  • For Each..Next: use for any collection (array, List, Dictionary, Controls). Never modify the collection mid-iteration — iterate backwards with Step -1 to safely remove items.
  • Do While..Loop: condition checked before body — may run zero times. Do Until..Loop: inverse logic, runs while condition is False.
  • Do..Loop While and Do..Loop Until: condition checked after body — always runs at least once. Use for input validation, menus, and retry loops.
  • Exit For / Exit Do breaks out of the innermost loop immediately. Continue For / Continue Do skips to the next iteration. Both are essential for search and filter loops.
  • Always ensure loop termination: every Do loop must have a statement inside that can eventually make the condition False, otherwise it runs forever.
  • Nested loops: inner loop executes fully for each outer iteration. Total iterations = outer × inner. Use Exit For to break from the inner loop; to exit both loops, use a flag variable or GoTo.

Exercises

Exercise 15.1 — Times Table Generator

  • Enter N in a TextBox and generate the N times table from 1×N to 12×N using a For..Next loop
  • Display each line in a ListBox: "1 × 7 = 7", "2 × 7 = 14", …
  • Add a second TextBox for a custom range (start to end) with step validation
  • Highlight multiples of 10 in a different ListBox colour using an If inside the loop
  • Copilot challenge: Ask Copilot to "generate a full 12×12 grid into a DataGridView using nested For loops"

Exercise 15.2 — Number Guessing Game

  • Generate a random number 1–100 using Random.Shared.Next(1, 101)
  • Use a Do..Loop Until to keep asking until the player guesses correctly
  • Give "Too high" / "Too low" hints after each guess using If..ElseIf
  • Count attempts and display the final score with a rating (1–3 = Amazing, 4–6 = Good, 7+ = Keep practising)
  • Copilot challenge: Ask Copilot to "add a hint mode: after 5 wrong guesses, reveal if the number is odd or even"

Exercise 15.3 — Student Score Analyser

  • Allow user to enter student names and scores in two TextBoxes and click Add to build parallel arrays
  • Use For Each to calculate average, highest, and lowest scores
  • Use a For..Next with Continue For to list only students who passed (≥50)
  • Use a nested loop to rank students: compare each student with all others to find their rank
  • Copilot challenge: Ask Copilot to "sort the students by score descending using a For..Next bubble sort and display the ranked list"

Next: Lesson 16 — Sub Procedures

Learn how to organise code into reusable Sub procedures, pass arguments ByVal and ByRef, use optional and ParamArray parameters, and call procedures from event handlers.

Continue »

Related Resources


Featured Books

Visual Basic 2022 Made Easy

Visual Basic 2022 Made Easy

by Dr. Liew Voon Kiong

Practical loop-based projects including number games, sorting algorithms, and data processing loops.

View on Amazon →
VB Programming With Code Examples

VB Programming With Code Examples

by Dr. Liew Voon Kiong

48 complete VB.NET programs many of which use loops for data processing, sorting, and generation.

View on Amazon →