Until LoopsUntil loops are very similar to the While loops we studied earlier. However, the previous While loops had their loop block executed as long as the test condition ( Expression1 ) was True. Until loops have their statement block executed until the test condition becomes True. The Until loop kind of reverses the normal loop logic. Do UntilLike the While loop, there are two flavors of the Until loop. The first form of the Until has the syntax Do Until Expression1 DoUntilStatementBlock Loop The statement block for the Do Until version executes as long as Expression1 evaluates to logic False. When Expression1 becomes logic True, control is sent to the statement following the Loop keyword. For example, in our coin toss program, we could rewrite the loop to use the Do Until as shown in the following code fragment: Do Until Heads = Target ThisToss = TossACoin() ' Function returns 1 for head If ThisToss = 1 Then Heads += 1 ' It was a Heads Else Heads = 0 ' Tails...start over End If Tosses += 1 ' The toss counter Loop In this case, we enter the loop with Heads not equal to Target . As long as Heads is not equal to Target , the loop statement block continues to execute. When the condition does become logic True, and Heads does equal Target , the loop block no longer executes. The Do Until loop is useful in a "keep-looking-for-something-until-you-find-it" type of situation. Programmer's Tip
Keep in mind that Do Until loops continue to execute as long as the test expression is logic False, not True. Loop UntilThe second type of Until loop is the Loop Until . It has the syntax form: Do LoopUntilStatementBlock Loop Until Expression1 Note that the Loop Until evaluates the test expression at the bottom of the loop. Therefore, Loop Until always executes the loop's statement block at least once. Just like the Until loop, Loop Until continues to execute the loop's statement block until Expression1 becomes logic True. Could we use Loop Until in our coin toss program? Sure. Consider the following code fragment: Do ThisToss = TossACoin() ' Function returns 1 for head If ThisToss = 1 Then Heads += 1 ' It was a Heads Else Heads = 0 ' Tails...start over End If Tosses += 1 ' The toss counter Loop Until Heads = Target txtTossCounter.Text = CStr(Tosses) This change has no real effect on the program, because we always have to make at least one pass through the loop to simulate a coin toss. |