Control Flow: Loops

7.1 For...Next

For i As Integer = 1 To 5
    Console.WriteLine(i)
Next

For i = 10 To 0 Step -2
    Console.Write($"{i} ")
Next

For i = 0 To items.Length - 1
    If items(i) = "" Then Continue For
    If items(i) = "STOP" Then Exit For
    Console.WriteLine(items(i))
Next i                              ' the counter name after Next is optional

7.2 For Each...Next

You can't add to or remove from a collection while iterating it with For Each. Iterate a copy, or loop backwards with For.

Dim fruits = {"apple", "banana", "cherry"}
For Each fruit As String In fruits
    Console.WriteLine(fruit.ToUpper())
Next

For Each kvp In dictionary
    Console.WriteLine($"{kvp.Key} = {kvp.Value}")
Next

7.3 Do...Loop (Four Forms)

Dim n = 0
Do While n < 5          ' check before (while true)
    n += 1
Loop

Do Until n = 0          ' check before (until true)
    n -= 1
Loop

Do                      ' check after: runs at least once
    input = Console.ReadLine()
Loop While input <> "quit"

Do
    attempts += 1
Loop Until attempts >= 3

Do                      ' infinite loop with Exit Do
    If Done() Then Exit Do
Loop

7.4 While...End While

While queue.Count > 0
    Process(queue.Dequeue())
End While

7.5 Exit, Continue and GoTo

Exit For, Exit Do, Exit While, Exit Sub, Exit Function, Exit Select, Exit Try, Exit Property.

Continue For, Continue Do, Continue While.

GoTo label exists but should be avoided (it's mostly used in legacy On Error code).

7.6 With...End With

With customer
    .Name = "Ana"
    .Email = "ana@example.com"
    .Address.City = "Pune"
    .Save()
End With