Suppose an ASP.NET page has the following code:
<script runat=server>
Sub Page_Load(obj As Object,ea As EventArgs)
Dim iNum As Integer=1
Do
Response.Write(iNum & " ")
iNum=iNum+1
Loop Until iNum<10
End Sub
</script>
The above code, when viewed in a browser, outputs only 1 but shouldn't the output be
1 2 3 4 5 6 7 8 9
becauseResponse.Write will first output 1. TheniNum equals 2. Now 2 is less than 10; thus the conditioniNum<10 evaluates toTrue. Hence the loop should continue &Response.Write should now output 2. TheniNum equals 3. Now 3 is less than 10; thus the conditioniNum<10 evaluates toTrue. Hence the loop should continue &Response.Write should now output 3 so on & so forth tilliNum equals 9. WheniNum equals 10, the conditioniNum<10 evaluates toFalse & hence theDo loop should exit. So how come the browser outputs only 1?
You have the operator backwards.LoopUNITIL. What that means is it stops when that condition is true, it doesn't execute while it is true, it stops when it is true. and 1 < 10 obvously, so it stops after one. The reason the 1 is printed is because a Do loop is always executed once even if the expression is false. So your code should look like this:
Sub Page_Load(objAs Object, eaAs EventArgs)Dim iNumAs Integer=1Do Response.Write(iNum &" ") iNum=iNum+1Loop UntiliNum > 9End Sub
In other words, when Do loop is used withUntil, the loop goes on executing as long as the loop condition evaluates toFalse but as soon as the loop condition evaluates toTrue, the loop exits. Am I right?
vcsjones:
What that means is it stops when that condition is true
Correct. Seems backwards, espeically if you are a former C++ or C# user.
0 comments:
Post a Comment