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
…
Next |
|
N = 1 'Initial value in line 1 of For loop
While N<=5 'Test is in line 1 of For loop
…
N = N + 1 'Increment is in line 3 in For loop
End While |
(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:
'Programmer: Janet Joy
'While loop generates 1,2,4,8,...512
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Num As Integer
ListBox1.Items.Add("Powers of 2")
Num = 1
While Num < 1000
ListBox1.Items.Add(Num)
Num = Num * 2
End While
End Sub
End Class