1. Lesson 4 of 8 Visual Basic Programming
1 of 3
Lesson 4: Loops
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2020 May 01
Loops can be used to run one or more lines of code repetitively. There
are three types of loops in visual basic: While…End While,
Do…Loop, and For.
While…End While
This loop runs a series of statements as long as a given condition is
true. Look at the code segment given below.
Dim var As Integer = 0
While var <= 2
MessageBox.Show (var)
var = var + 1
End While
The condition of the loop is var <= 2.
The value of the variable var is initially equal to 0.
The condition is checked.
The condition is true since 0 <= 2. Therefore, a message box
displays the value of var and then the value of var is incremented
by 1.
The condition is checked again.
The condition is true since 1 <= 2. Therefore, a message box
displays the value of var and then the value of var is incremented
by 1.
2. Lesson 4 of 8 Visual Basic Programming
2 of 3
The condition is checked again.
The condition is true since 2 <= 2. Therefore, a message box
displays the value of var and then the value of var is incremented
by 1.
The condition is checked again.
The condition is false since 3 <= 2 is false. Therefore, the program
exits from the loop.
Do…Loop
This loop runs a series of statements while a condition is true or until
a condition becomes true. Now look at the code segments given
below along with their outputs.
Dim var As Integer = 0
Do While var <= 2
MessageBox.Show (var)
var = var + 1
Loop
Output: 0, 1, 2
Dim var As Integer = 0
Do
MessageBox.Show (var)
var = var + 1
Loop While var > 0
Output: 0, 1, 2, 3…
3. Lesson 4 of 8 Visual Basic Programming
3 of 3
Dim var As Integer = 0
Do Until var > 5
MessageBox.Show (var)
var = var + 1
Loop
Output: 0, 1, 2, 3, 4, 5
Dim var As Integer = 0
Do
MessageBox.Show (var)
var = var + 1
Loop Until var < 5
Output: 0
For
This loop runs a series of statements a specified number of times.
Now look at the code segment given below along with its output.
Dim i As Integer
For i = 0 To 4
MessageBox.Show (i)
Next i
Output: 0, 1, 2, 3, 4