VISUAL PROGRAMMING
Unit 4 – Program Flow: Loop
Structures
Eng SN Niles
Department of Textile & Clothing Technology
University of Moratuwa
Learning Outcomes
At the end of this lecture you should have an:
understanding of the role of loop structures in
program flow.
appreciation of the different loop structures in
VB 2008
ability to select and use loop structures in an
appropriate manner.
Loop Structures
A loop structure is used to repeat a
sequence of statements a certain
number of times.
Within the loop will be one or more
variables whose values will change at
each repetition, or pass.
Loop Structures
Loops may be classified as
Determinate Loops, which repeat the
instructions over a specified number of
times
Indeterminate Loops, which repeat the
instructions until a predetermined goal is
reached, or until certain conditions change.
FOR-NEXT LOOP
For I = a to b
<statements>
Next
1. The value I is called the control variable of
the loop, and its initial and final values will
be a and b respectively.
2. The value of I will be incremented by 1
starting from a and the statements between
the For and Next lines will be repeated until
the value of I has become b.
This loop will work only if b is not less than a.
If a is greater than b the loop will be skipped
and the program will continue from the
statement after the Next.
The initial and final values may be literals or
variables. For example, if we declare two
variables LowerValue and UpperValue and
assign values to them, they may be used as
follows:
For I = LowerValue To UpperValue
A variation of the basic For-Next loop is
where the increment is some value other
than 1.
For I = a To b Step n
Here the value of n is the increment by which
a will increase to b. It is called the step value
of the loop.
It is possible in this case to have a situation
where a > b and a negative step value is used.
The control variable may be declared in the
same line as the For statement.
For I as Integer = a To b
This is the preferred way of declaring the
control variable
Nested For-Next
Write the For-Next loop to generate the
multiplication table from 2 to 12. (Display is not
important in this example)
Nested For-Next
The Continue For statement will skip an
iteration or a part of it. The moment this
statement is seen in the body of the loop the
rest of the statements in the loop are ignored
and the Next statement is executed.
The Exit For provides the facility to exit the
loop before the set number of iterations is
over.
e.g.
For I as Integer = 1 to 10
If I Mod 3 = 0 Then
X+=I
Else
Continue For
End If
Next
Indeterminate Loops
In this type of loop the number of iterations is
not known beforehand, and the given set of
statements is repeated until the particular
condition changes.
Do While <condition>
<statements>
Loop
Do
<statements>
Loop While <condition>
Do Until <condition>
<statements>
Loop
Do
<statements>
Loop Until <condition>
Dim X as Double, Y as Integer
Do
X+=0.001
Y += 1
Loop Until X=1
lblOne.text = CStr(Y)