Learning Loops in VB.NET for Game Development - Do...Loop continued
(Page 4 of 4 )
Earlier, I pointed out the Do While example and the While example looked and performed very similarly. Actually, though, there's one important difference: the Do loop can test the expression after the loop's instructions are run. Consider, for example, the following While loop:
While False
Console.WriteLine("Hello.")
End While
Since the expression is False, the call to WriteLine within the loop will never actually be executed. Execution will essentially skip right over the loop. Sometimes, this is appropriate behavior since we may never want a loop to run if the expression comes out False in the beginning. However, there are situations where we want the loop to run at least once, and the While loop is not fitted to these situations. This can all be fixed if, instead of checking the expression before each iteration, we check the expression after each iteration. To enable this behavior in a Do loop, we simply need to specify the expression after Loop rather than after Do. The following loop, for example, will execute exactly once, even though the expression is False:
Do
Console.WriteLine("Hello.")
Loop While False
We can make use of this behavior with our previous example, too. Before, we had to assign a blank string to input because its value was checked before the user was able to actually input anything. We can eliminate the need for this assignment, however, by checking the expression after the loop iterates. At this point, the user will have entered something and the variable will have been assigned a value:
' No assignment:
Dim input As String
Do
input = Console.ReadLine()
Console.WriteLine(input)
Loop While input.ToLower() <> "quit"
This behavior also works with Until :
Dim input As String
Do
input = Console.ReadLine()
Console.WriteLine(input)
Loop Until input.ToLower() = "quit"
This behavior models the behavior of the generic do loop in other languages, so it's the behavior with which most programmers will be familiar. As you've seen, though, the Visual Basic version of the loop is more flexible. However, a Do loop should not be used in situations where a simple While loop will suffice.
Next up are the For loop and the For Each loop.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |