|
|
Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called looping . 9.1 Do Loop
The format are a) Do While condition Block of one or more VB statements Loop b) Do c) Do Until condition d) Do Loop Until condition
9.2 Exiting the Loop Sometime we need exit to exit a loop prematurely because of a certain condition is fulfilled. The syntax to use is known as Exit Do. Lets examine the folowing example 9.3 For....Next LoopThe format is:
Pease refer to example 9.3a,9.3b and 9.3 c Sometimes the user might want to get out from the loop before the whole repetitive process is executed, the command to use is Exit For. To exit a For….Next Loop, you can place the Exit For statement within the loop; and it is normally used together with the If…..Then… statement. Let’s examine example 9.3 d.
|
Example 9.1 Do while counter <=1000 num.Text=counter counter =counter+1 Loop * The above example will keep on adding until counter >1000. The above example can be rewritten as Do
num.Text=counter Loop until counter>1000
Example 9.2
Dim sum, n As Integer Private Sub Form_Activate() List1.AddItem "n" & vbTab & "sum" Do n = n + 1 Sum = Sum + n List1.AddItem n & vbTab & Sum If n = 100 Then Exit Do End If Loop End Sub
Explanation In the above example, we find the summation of 1+2+3+4+……+100. In the design stage, you need to insert a ListBox into the form for displaying the output, named List1. The program uses the AddItem method to populate the ListBox. The statement List1.AddItem "n" & vbTab & "sum" will display the headings in the ListBox, where it uses the vbTab function to create a space between the headings n and sum.
|
|