Controlling Program Flow Part 3

Iteration – For Loops

Loops are used to perform repetitive tasks in a program and each time a task is repeated it is said to have completed one iteration. Increasing values in mathematical calculations can be performed very easily using loops. There are a number of loop types including; For Next Loops, Do While Loop, Do Loop Until.

We will work through a number of exercises to demonstrate the controls so you will need to add another form (FrmLoops) to your MDI program and a menu item on the main form to open it

For Loops

The basic syntax for a ‘For loop’ is:

For <index> = <start value> To <end value>

Execute code

Next <value>

Suppose we want to add a list of numbers to a list box starting from a number and an end value input by the user i.e. display the numbers 1 to 20 or 4 to 9.

Exercise:

Create an interface that contains the following controls:

· Listbox – lstTest

· Textbox – txtFrom

· Textbox – txtTo

· Button - btnTest

The user enters start and end values into the textboxes and clicks the Test button.

In the click event of the button place the following code:

Dim valFrom As Integer = txtFrom.Text

Dim valTo As Integer = txtTo.Text

Dim i As Integer

For i = valFrom To valTo

lstTest.Items.Add(i)

Next

There are 3 integer variables - 2 to hold the start and end values (valFrom, valTo) that are initialised through the textboxes and a third to use as an increment value (i) . The first time through the loop the variable i is assigned the value of valFrom (in this case 1 – see below on interface). The value of i is then added to the list box through the Items.Add method. The Next keyword then increments the value of i by one. This continues until i reaches the end value - valTo

The program above is very simple and of very little use. A more useful program would be to find the square root of a set of numbers using the same interface and adding more functionality to the click event code – see below

Dim valFrom As Integer = txtFrom.Text

Dim valTo As Integer = txtTo.Text

Dim i As Integer

For i = valFrom To valTo

lstTest.Items.Add(i & " Squared = " & (i * i))

Next

The result would be:

The major difference to the code is the line which is adding the calculation to the list box

lstTest.Items.Add(i & " Squared = " & (i * i))

Instead of just adding the value of (i) I have added a literal string value which has been concatenated by ampersands (&) and speech marks. The calculation of the square of the number is to times it by itself i.e. (i * i) which is contained in brackets – omitting the brackets will cause an error

Exercise

Re-write the above code and change the operator.

The Step Keyword

The ‘For loop’ will increment (or decrement) by one every time through the loop but you can reassign this value by using the Step operator. For example if you wanted to display the square of numbers 2 to 10 incremented by 2 (or decrement from10 to 2 by -2) we could do the following:

For i = valFrom To valTo Step 2

lstTest.Items.Add(i & " Squared = " & (i * i))

Next

For i = valFrom To valTo Step -2

lstTest.Items.Add(i & " Squared = " & (i * i))

Next

Nested For Loops

It is possible to nest Loops the same as IF statements. The following example uses two loops to display the times table in the list box. The outer loop is evaluated first and the it immediately goes to the inner loop and executes the code however may times it has been set up to iterate. It then drops out of the inner loop, increments the outer loop and then iterates through the inner loop. This continues until the limit is reached by the outer loop.

The code is shown below

Dim valFrom As Integer = txtFrom.Text

Dim valTo As Integer = txtTo.Text

Dim i, count As Integer

For i = valFrom To valTo

lstTest.Items.Add(valFrom & " Times Table ")

For count = 1 To 12

lstTest.Items.Add(count & " X " & valFrom & " = " & (count * valFrom))

Next

valFrom += 1

Next

I have added a count variable to use for incrementing the times table 1 to 12 in the inner loop. The first time through the loop the values of valFrom and valTo are determined by user (below shows 2 to 3). I have added a string for the times table heading to the list box just before going into the 2nd loop. The value of count is set to 1 and used with the value of valFrom to make up each line of the times table and repeats 12 times. When it exits the 2nd loop it adds 1 to the value of valFrom using the shortcut valFrom += 1 (this is the same as writing valFrom = ValFrom + 1. *=, /= and -= work in the same way by multiplying, dividing and subtracting by one or numerous i.e. a *= 2 will times a by 2). The second loop is incremented and the procedure continues until the 1st loop reaches its set limit – valTo. The result can be seen below

Another version of the ’For Loop’ is the For Each Next loop. This can be used for looping through arrays and groups of objects. The example below will clear any textbox on the current form

Dim ctrl As Control

For Each ctrl In Me.Controls

If TypeOf ctrl Is TextBox Then

ctrl.Text = ""

End If

Next

I have created an object variable of the type Control for comparison and incrementing.

The first line of the loop checks the first control it encounters on the current for (Me), check to see if it is a textbox and if it is it clears the text property by setting it to an empty string (“”)


Summary

In this session we covered:

· iteration using ‘For Loops’

· Using the Step parameter to alter the default increment/decrement

· Formatting string to be displayed on one line of a list box

· Nested loops

· Using the shortcut to increment/decrement/divide/subtract

· For Each loops

We will continue with looping next session when we will cover Do While and Do Loop Until

? Peter Bilbie – 2007-8 Page 4 of 7