You are on page 1of 13

Looping in Programming

Lecture 11
Introduction
Another procedure that involves decision
making is looping. Visual Basic allows a
procedure to be repeated many times until a
condition or a set of conditions is fulfilled. This
is generally called looping . Looping is a very
useful feature of Visual Basic because it makes
repetitive works easier. There are two kinds
of loops in Visual Basic, the Do...Loop and
the For.......Next loop.
Do Loop
a) Do While condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While condition
c) Do Until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until condition
Ex 1
• Do While .... Loop
Dim num As Integer
num = 0
Do While num < 10
Print num
num = num + 1
Loop

• Do...loop while
Dim num As Integer
num = 0
Do
Print num
num = num + 1
Loop While num <= 10
Ex 2
• Do...loop until
Dim x As Integer
x=0
Do
x=x+1
Loop Until x > 10
MsgBox x
For....Next Loop
For counter=startNumber to endNumber (Step
increment)
One or more VB statements
Next
Ex:
Example : To print 0 to 10.
Dim i As Integer
For i = 0 To 10
Print i
Next I
If does not define the number of step, the value of i is
incremented by 1.
Example : To print 0 to 6 in steps of 2.
Dim i As Integer
For i = 0 To 6 Step 2
Print i
Next i

Every time, the value of i is incremented by 2.


1. For counter=1 to 1000 step 10
counter=counter+1
Next
2. For counter=1000 to 5 step -5
counter=counter-10
Next

* Notice that increment can be negative


Exit For and Exit Do statement
A For Next Loop can be terminated by an Exit For
statement and a Do loop can be terminated by an
Exit Do statement.
Example : Exit For statement :
Dim i As Integer
For i = 0 To 10
If i = 3 Then
Exit For
End If
Print i
Next i
Example : Exit Do statement

Dim num As Integer


num = 0
Do While num < 10
Print num
num = num + 1

If num = 4 Then
Exit Do
End If
The While….Wend Loop
The structure of a While….Wend Loop is very
similar to the Do Loop. it takes the following
format:
While condition
Statements
Wend
The above loop means that while the
condition is not met, the loop will go on. The
loop will end when the condition is met.
Ex:
Dim sum, n As Integer
Private Sub Form_Load()
List1.AddItem "n" & vbTab & "sum"
While n <> 100
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
Wend
End Sub
Thank You!
End…

You might also like