Visual Basic 2005 Guide
Iteration - For Loops

Introduction

Iteration is a way of executing lines of code multiple times. It usually saves the programmer from writing lots of lines of code.

There are many ways to do this in Visual Basic, the simplest is the For & Next structure.

Step 1 - Create A Form

Create a new project and add a button and text box to the form as shown below.

form design

The button has been named btnLoop, the text box is called txtOutput and has its multiline property set to true and scrollbars set to vertical.

Step 2 - Program The Button's Click Event

Double click on the button and write the following code in the event handler.

Dim intCounter As Integer
txtOutput.Text = ""
For intCounter = 1 To 100
   txtOutput.Text = txtOutput.Text & intCounter & vbNewLine
Next

Save your work and run the program. You should get the numbers 1 to 100 in the text box. Now look carefully at your code. The structure of a For & Next loop in Visual Basic is as follows,

For variable = startValue To endValue
   Statement(s)
Next variable

The items in bold change depending on how many times you want the code to run. You can repeat as many lines of code as you need between the For and Next statements. The start and end values can also be variables.

Step 3 - Adapting The Program

Adapt the code from the example above to get your program to do the following things,

  1. Write the numbers from 1 to 20 on the form.
  2. Write the numbers from 50 to 60 on the form.

Step 4 - Making Multiplication Tables

Replace the code in your program so that it reads as follows,

Dim intCounter As Integer, intTables As Integer, intResult As Integer
Dim strOutputLine As String
intTables = 7
For intCounter = 1 To 12
   intResult = intTables * intCounter
   strOutputLine = intTables & " x " & intCounter & " = " & intResult
   txtOutput.Text = txtOutput.Text & strOutputLine & vbNewLine
Next

Test out this code by running your program. You should now see the 7 times table when you press the button.

Step 5 - Adapt The Code Again

Adapt the code from the example above to get your program to do the following things,

  1. Change the code that you have written to show a different set of tables.
  2. Change the program so that the user can decide which set of tables to display.

The Step Parameter

In the loops that you have used so far, the counter always goes up by 1 each time the loop repeats itself. You can make the loop behave differently by setting the Step parameter to a number other than 1. For example,

Dim intCounter As Integer
txtOutput.Text = ""
For intCounter = 2 To 50 Step 2
   txtOutput.Text = txtOutput.Text & intCounter & vbNewLine
Next

Test Out This code.

Simple Tasks

  1. Change the above code so that the loop displays all of the odd numbers between 1 and 30.
  2. Change the code so that the loop counts backwards from 15 to 1.