Home Visual Basic Loops

 
 


The power of the computer lies in its ability to perform repetitive tasks. The parts of the program that are repeated are called LOOPS.  A loop gives us the capability to execute the same statements over and over again.  The process of repeating statements is called LOOPING.  

Types of Visual Basic Loops

There are six different types of loops you can use in VB:

For...Next

Do While…End While

Do Until..Loop

Do..Loop While

Do..Loop Until

While..End While

Depending upon which loop you use, the loop can be repeated a fixed number of times until a predetermined specific value has been met, or until a certain condition has changed. The While…End While loop works exactly the same as the Do While…Loop which it is being replaced by.   Therefore we will not look at the While…End While loop structure.

For...Next Loop

The For..Next Loop uses a starting point, a stopping point, and an amount you wish to increment or decrement by during each iteration (cycle) of the loop. The For…Next statement is used to run a loop a fixed number of times. The loop starts at the For statement and ends with the Next statement.

For <counter > = <starting value > To <stopping value> [Step increment >/<decrement >]

            …Statements that will be repeated

Next[counter]

Note: : :The values placed in the counter, start, stop and step must all be numeric.

For X = 1 to 6 Step 1
 :     ...Statements that will be repeated
Next X

In the example above the variable X starts with a value of 1 (starting value). The steps between the For and the next statements are executed repeatedly until the value of the variable X has a value greater than 6(stopping value). Each time through the loop the value of X is increased by 1(increment). The letters X, Y and Z are often used as names for the counter variable though any name is acceptable. The counter var iable after the Next is not required.

Example: For..Next Loop

1:        Dim X As Integer
2:        For X = 1 to 3 Step 1
3:            MsgBox( "The value of X is " & X)
4:        Next
5:        MsgBox("The value of x after the loop is finished is " & X)

 

The loop above is run in this fashion:

Line 2: X is assigned a value of 1
Line 3: The Message Box displays "the value of X is 1"
Line 4: The Next statement takes you back to the For statement(Line 2)

Line 2: X is incremented by 1 thus it now has a value of 2
Line 3: The Message Box displays "The value of X is 2"
Line 4: The Next statement takes you back to the For statement.

Line 2:
  X is incremented by 1 thus it now has a value of  3
Line 3:   The message Box displays “The value of X is 3"
Line 4:   The Next statement takes you back to the For statement

Line 2:  X is incremented by 1 thus it now has a value of 4.  Four is greater than the stopping point of 3.  The next line of code that will be run is the one following the Next statement

Line 5:  The Message Box will display “The value of X after the loop is finished is 4”.

Example:  For..Next Loop without using  a Step option


*Note:  Notice that the example below doesn't have a Step option.  If the Step option is ommitted as in the example below the Step will default to 1 thus the counter variable X will increment by 1 each time the loop is run.  The results will be the same as the previous example.

Dim X As Integer
For X = 1 to 3
       MsgBox ("The value of X is " & X)
Next
MsgBox ("The value of X after the loop is finished is " & X)

Using Step Decrement

The counter can move either in an ascending or descending order. If the step increment is positive the counter values will progress in descending order. If the step is negative the starting value must be greater than the stopping value.

Example: For/Next Statement that uses a decrement .

This For/Next Loop example has a starting value of 4, a stopping value of 1, and a step decrement of 1.  The value of X decreases by 1 for each iteration of the loop.  You can't omit the decrement step like you can for the increment.  There is no default value for the decrement step.

Dim X as Integer
For X = 4 to 1 Step -1 'Starting value is greater than stopping value
   Label1.Text & X & " "
Next
Label2.Text = ("The value of X after the loop is finished is " & X)

 

Example 2: For/Next statement that uses a decrement

This program displays the first ten numbers in reverse order when the user clicks on a button.
The counter variable X will decrement by 1 for each loop iteration.

  1. Create a new Application named ReverseNumbers.
  2. Add a button and a listbox to your form.
  3. Double-click on the button, this places your cursor in the click event for the button.
  4. Enter the code for the Button1_Click event as shown below.
  5. Run and the test the application.

Visual Basic Form with Button and List Box


Private Sub btnReverseNumbers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReverseNumbers.Click
Dim X As Integer
For X = 10 to 1 Step -1
ListBox1.Items.Add(X)
Next
End Sub


Loop Examples

Dim X, intResult as Integer
For X = 1 to 4
        intResult = intResult + X
Next


Number of Times Through Loop Value of X Value of intResult
1 1 1
2 2 3
3 3 6
4 4 10


Practice for viewing the counter variable values while program is Running


You can create the following example to get a really good view of how the For/Next Loop works. This program allows you to enter the values for the starting, stopping and incremental step values during runtime. The program will then display the value of the counter variable for each iteration of the loop.
  1. Click on File on the menu bar and then select New Project. Create a Windows Application named For_Next_Loop.
  2. Make your form look like the one below using the information from Table 4-4.

Completed practice for creating a viewable For/Next Loop

Object Property Property Values
Form Text For/Next Loop
Label1 Text Starting Value
Label2 Text Stopping Value
Label3 Text Incremental Value
TextBox Name txtStart
TextBox Name txtStop
TextBox Name txtIncremental
Label Name lblMessage
  Text (Remove the text from the Text property)
Button1 Text Run Loop
All Objects* Font Size 14

  1. *Draw a rectangle around all of the objects to select them and then change the Font property size to 14.
  2. 3.
  3. After placing all the objects on the form double-click on the button you placed on the form. Double-clicking the button will place you in the code view window ready to type the code for the Button1_Click Event. Study the code below as your enter it, then run the program.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Declare variables
Dim X, intStart, intStop, intIncremental As Integer
'Convert values from TextBoxes
intStart = CInt(txtStart.Text)
intStop = CInt(txtStop.Text)
intIncremental = CInt(txtIncremental.Text)
'Create loop to display current value of the loop variable For X = intStart To intStop Step intIncremental lblMessage.Text = lblMessage.Text & CStr(X) & vbCrLf Next
End Sub