Thursday, December 11, 2008

USING Do Loop

The formats are

 
a) Do While condition

Block of one or more VB statements

Loop

b) Do
Block of one or more VB statements
Loop While condition

c) Do Until condition
Block of one or more VB statements
Loop

d) Do
Block of one or more VB statements

Loop Until condition


* 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.

Example 1:
Do while counter <=1000

TextBox1.Text=counter

counter +=1

Loop

 

* The above example will keep on adding until counter >1000.

 

The above example can be rewritten as

Do

TextBox1.Text=counter
counter+=1

Loop until counter>1000

Example2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sum, n As Integer
Do
n += 1
sum += n
ListBox1.Items.Add(n & vbTab & sum)
If n = 100 Then
Exit Do
End If
Loop 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 ListBox1.Items.Add(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.

No comments:

Post a Comment