Skip to content

Step 1 of 5 · Reading · ~2 min

Learn

Control Flow

For ... Next — counted iteration:

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

For i As Integer = 10 To 1 Step -1
    Console.WriteLine(i)
Next

To is inclusive at both ends: 1 To 10 runs ten times and i really does reach 10. That single fact is behind most off-by-one bugs in VB.NET, because a zero-based collection of n items ends at index n - 1, so its loop is 0 To count - 1.

For Each ... In over collections:

Dim nums() As Integer = {1, 2, 3, 4, 5}
For Each n As Integer In nums
    Console.WriteLine(n)
Next

Write the As Integer on the loop variable. With type inference off — the setting this course's compiler uses — a bare For Each n In nums fails with 'n' is not declared.

While ... End While tests before the body:

Dim n As Integer = 1
While n < 100
    n *= 2
End While

Do ... Loop — the flexible one. The condition may sit at the top or the bottom, and may be While (keep going while true) or Until (keep going until true):

Dim line As String = ""
Do
    line = Console.ReadLine()
Loop Until line = "quit"

The condition at the bottom is the reason to reach for Do: the body always runs at least once. Reading a line before you can know whether it was the sentinel is the classic case.

Choosing

  • Counting a known number of times → For ... Next
  • Visiting every element, index irrelevant → For Each
  • Stopping on a condition, may run zero times → While
  • Stopping on a condition, must run at least once → Do ... Loop Until

Exit For / Exit While / Exit Do leave the loop early — the keyword names the loop kind, so there is no bare Break. Continue For / Continue While / Continue Do skip to the next iteration instead.

Your exercise

Sum 1 to N with a For ... Next. Because To is inclusive, For i As Integer = 1 To n is exactly right here — no - 1. The starter declares total as Long rather than Integer; that is deliberate headroom, not a hint about the loop.

Up nextSubroutines and FunctionsSubs, Functions, Arrays

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…