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:

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

INDEX, A Demo loop program, For Loops, Step: change the increment, While Loops, While, cont., Endless loops, Do Loops, Nested Loops, For Each Loops, Graphics with Loops
Next lesson: Arrays in Visual Basic

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

While Loops