Loop, For ... Next

We have seen sequential and conditional execution of programs, and we will now look at looping, the repetitive execution of instructions. (In a subsequent note, we will cover a fourth flow mechanism called recursion in which a function calls itself).

There are three loop statements in Visual Basic, For, Do while and Do until. This note discusses For loops.

A For loop consists of a For statement followed by the instructions you wish to execute repeatedly (the body of the loop) followed by a Next statement:

For <index> = <initial value> to <limit> [step <increment>]

   body: statements to execute until the
   index is equal or beyond the limit

Next
This is illustrated in this inflexible loop demonstration.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   txtOut.Clear()
   Dim i As Integer
   For i = 2 To 10 Step 2
      txtOut.AppendText("loop" & " " & CStr(i) & vbCrLf)
   Next
   txtOut.AppendText("the end")
End Sub
This loop has an index variable called i which is initialized at 2 and incremented by 2 each time the loop is executed. The loop repeats until the index reaches the limit of 10. As you see, this results in five iterations of the loop.

This example is simple and limited, but the For statement is more general. The index can be any numeric variable, and its initial value, limit, and increment amount may be any numeric expression:

For <numeric variable> = <numeric expression> to <numeric expression> [step <numeric expression>]
(Note that the step value is optional. If it is omitted, it is assumed to be 1).

Here is a generalized loop demonstration in which the user specifies the initial value, limit and increment amount for the index variable, and a general flow chart for a For ... Next loop:

Private Sub Button1_Click ...
   Dim intStart As Integer  'initial index value
   Dim intInc As Integer    'index increment
   Dim intEnd As Integer    'index limit
   Dim i As Integer         'index variable
   txtOut.Clear()
   intStart = CInt(txtInitial.Text)
   intInc = CInt(txtIncrement.Text)
   intEnd = CInt(txtLimit.Text)
   For i = intStart To intEnd Step intInc
      txtOut.AppendText("loop" & "  " & CStr(i) & vbCrLf)
   Next
   txtOut.AppendText("the end")
End Sub

Note that there is a risk of getting into an infinite loop when experimenting with this program. For example, if you tell it to increment the index by 0 until it reaches some limit, it will never reach that limit.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.