Thursday, December 11, 2008

USING THE FOR . . . NEXT LOOP

The format is:

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next

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.

Example 1:
Dim counter as Integer

For counter=1 to 10

ListBox1.Items.Add (counter)

Next

* The program will enter number 1 to 10 into the list box.

Example 2:

Dim counter , sum As Integer

For counter=1 to 100 step 10

sum+=counter

ListBox1.Items.Add (sum)

Next

 

* The program will calculate the sum of the numbers as follows:

sum=0+10+20+30+40+......

Example 3:

Dim counter, sum As Integer
sum = 1000
For counter = 100 To 5 Step -5
sum - = counter
ListBox1.Items.Add(sum)
Next


*Notice that increment can be negative.

The program will compute the subtraction as follow:

1000-100-95-90-..........

Example 4:

Dim n as Integer

For n=1 to 10

If n>6 then

Exit For

End If

Else

ListBox1.Items.Add ( n)

Next

End If


Next

The process will stop when n greater than 6.

No comments:

Post a Comment