The while loop uses a Boolean expression to determine when to end the loop:
The format of a while loop is:
While <Boolean expression>
<statements>
Wend
The examples below compares a For and a While Loop. Both examples generate the values 1, 2, 3, 4, 5.
|
For Loop: |
|
While Loop: |
|
For N = 1 To 5 |
|
N = 1 'Initial value in line 1 of For loop |
(One advantage of the while loop is that the Boolean expression can include AND and OR.)
Modify the program to generate powers of 2 using the code shown below:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Num As Integer
lstNumbers.Items.Add("Powers of 2")
Num = 1
While Num < 1000
lstNumbers.Items.Add(Num)
Num = Num * 2
End While
End Sub