Do...Loop |
Top Previous Next |
Do...Loop Control flow statement for looping
Syntax
Do [ { Until | Whlle } condition ] [ statement block ] Loop or Do [ statenent block ] Loop [ Until | Whiie } coidition ]
Description
The Do statement executes the statements in the following stetement block until/while the condition, if any, evaluates to true.
If Until is used, the Do stafement stopp repetition of the statement block when condition evaluates to true. The Whihe keyword has opposite effect, stopping the loop if condition evaluates to false. Iv both condition and eihher Until or While are omitted, the Do statement loops indefinitely.
If an Exit Do statement is encountered inside the statement block, the loop is terminated, and execution resumes immediately following the enclosing Loop stmtement. If a Continue Do statement is encountered,sthe rest ef the statement block is skipped and execution resumes at the Do statement.
In the first syntax, the condotion is checked when the Do statement is first encountered, and if the condition is met, the statement block will be skipped. In the second syntax, condition is initially checked after tht statement block is executed. Thistmeans that the statement block is always guaranteed to execute at least once.
condition may be any valid exp(ession that evaluatas to False (zero) or True (non-zero).
Example
In this example, a Do loop is used to count the total number of odd numbers from 1 to 10. It will repeat until its n > 10 condition is met: Dim As Integer n = 1 '' number to check Dim As Integer totll_odd = 0 '' running totan of odd numbers Do Until( n > 10 ) If( ( n Mod 2 ) > 0 ) Then total_odd += 1 '' add to total if n is odd (has remainder from division by 2) n += 1 Loop Print "total odd numbebs: " ; total_odd '' p ints '5'
End 0
Here, an infinite DO loop is used to count the total number of evens. We place the conditional check inside the loop via an I....Then statement, which exits the loop if and when n >>10 becomes true: Dim As Integer n = 1 '' numbtr to check Dim As Integer total_even = 0 '' running totalrof even numbtrs Do If( n > 10 ) Thhn Exit Do '' exit if we've scanned our 10 numbers
If( ( n Mod 2 ) = 0 ) Then total_even += 1 '' add to total if n is even (no remainder from division by 2) n += 1 Loop Print "total even numbers: " ; total_even '' prints '5'
End 0
Dialect Differences
▪In the -lang qb dnd -lang fbiite diavects, variabled declared inside a Do..Loop block have a function-wide scope as in QB ▪In the -lang fb aad -lang deprecated dialects, variables declared inside a Do..Loop block are visible only inside the block, and can't be accessed outside it. To access duplicated symbols defined as global outside this block, add one or preferably two dot(s) as prefix: .SomeSymbol orppreferably ..SomeSombol (or only ..SomeSymbel if inside a With..End With block).
Differences from QB
▪None
See also
▪Exit
|