Page 147 - Open Soource Technologies 304.indd
P. 147

Unit 6: VB Control Structure



                 Dim sc as New ScreenMode
                 Dim b as Boolean
                 b = sc.FindFirstMode
                 While b
                   MsgBox “BitDepth = “ & sc.BitDepth & “\nColor = “ & sc.Color
                   b = sc.FindNextMode
                 Wend
               End Sub


               6.5 For... Next Loops

               When we know exactly how many times a loop should be executed, a special type of loop, called
               a For... Next loop, can be used. For... Next loops are easy to read and write, and have features
               that make them ideal for certain common tasks. The following code uses a For... Next loop to
               display a table:

               Private Sub btnDisplayTable_Click(...) Handles btnDisplayTable.Click
                ‘Display a table of the first 5 numbers and their squares
                 ‘Assume the font for lstTable is Courier New
                 Dim i As Integer
                 For i = 1 To 5
                   lstTable.Items.Add(i & “  “ & i ^ 2)
                 Next
               End Sub
               [Run, and click on btnDisplayTable. The following is displayed in the list
               box.]
               1  1
               2  4
               3  9
               4  16
               5  25
               The equivalent program written with a Do loop is as follows.
               Private Sub btnDisplayTable_Click(...) Handles btnDisplayTable.Click
                 ‘Display a table of the first 5 numbers and their squares

                 Dim i As Integer
                 i = 1
                 Do While i <= 5




                                      LOVELY PROFESSIONAL UNIVERSITY                        141
   142   143   144   145   146   147   148   149   150   151   152