We finished up Chapter 6.1 in class today. We learned that we could use loops in order to accomplish tasks that should be done several times using Loops. We learned about three types of loop structures:
Do Until
Do While
For NextWe can write a loop using any of these three structures and any loop written in one of these structures can be rewritten using one of the other two. The basic syntax for each of these loops are:
For variable = (starting point) To (ending point)
'Do statements until we reach the ending point
Next 'Update condition variable
'**************************************
'Set condition before entering loop
Do While condition
'Do statements until condition is false
'Update the condition
Loop
'**************************************
'Set condition before entering loop
Do
'Do statements until condition is true
'Update the condition
Loop Until condition
In all three loop structures we have three parts that are the same:
1) A starting point for the condition we are checking
2) An endpoint for the condition
3) An update for the condition
We must have all three things for the loop to execute and end execution. Without (3) from above for example, we would have an infinite loop which is
definitely not what was intended.
Also notice that the
Do While and the
Do Until loops are opposites.
Do While loops until the
condition is
False whereas the
Do Until loop will loop
until the condition is True. Also the
Do Until is
always guaranteed to loop at least once. We have no such guarantee with the
Do While loop.
Do While Examples
Dim i As Integer = 1
Do While i <= 10
'List out the numbers from 1 to 10
lstOut.Items.Add( i )
i += 1
Loop
Dim i As Integer = 1
Dim num As Integer
num = CInt(InputBox("Enter a #:",""))
Do While i <= num
'List out the numbers from 1 to num
lstOut.Items.Add( i )
i += 1
Loop
Do Until Examples
Dim i As Integer = 1
Do
'List out the numbers from 1 to 10
lstOut.Items.Add( i )
i += 1
Loop Until i > 10
Dim i As Integer = 1
Dim num As Integer
num = CInt(InputBox("Enter a #:",""))
Do
'List out the numbers from 1 to num
lstOut.Items.Add( i )
i += 1
Loop Until i > num
For Next Examples
For( i As Integer = 1 To 10)
'List out the numbers from 1 to 10
lstOut.Items.Add( i )
Next
Dim num As Integer
num = CInt(InputBox("Enter a #:",""))
For( i As Integer = 1 To num)
'List out the numbers from 1 to num
lstOut.Items.Add( i )
Next