Skip to content

DO...LOOP

Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgDoloop Last revised: 2021-09-28

Control flow statement for looping.

Syntax

Do [{ Until | While } condition]

    [statement block]

Loop

or

Do

    [statement block]

Loop [{ Until | While } condition]

Description

The Do statement executes the statements in the following statement block until/while the condition evaluates to true.

  • Until — stops repetition when condition evaluates to true.
  • While — stops the loop when condition evaluates to false.
  • If both condition and Until/While are omitted, the loop runs indefinitely.

Exit Do: Terminates the loop; execution resumes after the Loop statement.

Continue Do: Skips the rest of the statement block and resumes at the Do statement.

In the first syntax, the condition is checked when the Do statement is first encountered; if the condition is met, the statement block will be skipped. In the second syntax, the condition is checked after the statement block executes — guaranteeing the block runs at least once.

condition may be any valid expression that evaluates to False (zero) or True (non-zero).

Examples

Example 1: Count total odd numbers 1–10

vb
Dim As Integer n = 1
Dim As Integer total_odd = 0
Do Until( n > 10 )
  If( ( n Mod 2 ) > 0 ) Then total_odd += 1
  n += 1
Loop
Print "total odd numbers: " ; total_odd  '' prints '5'

End 0

Example 2: Infinite loop with Exit Do

vb
Dim As Integer n = 1
Dim As Integer total_even = 0
Do
    If( n > 10 ) Then Exit Do
    If( ( n Mod 2 ) = 0 ) Then total_even += 1
    n += 1
Loop
Print "total even numbers: " ; total_even  '' prints '5'

End 0

Dialect Differences

  • In -lang qb and -lang fblite, variables declared inside a Do..Loop block have procedure-wide scope.
  • In -lang fb and -lang deprecated, variables are visible only inside the block.

Differences from QB

  • None.

See Also

Translated from FreeBASIC official docs. Contact us for removal if infringed.
FreeBASIC is an open-source project, not affiliated with Microsoft