Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

do loop

do ... loop repeats a block for as long as a condition says so. The condition can be written at the top, after do, or at the bottom, after loop, and it can be a while or an until:

'' do ... loop repeats a block. The test can go at either end.
dim as int32 n

'' do while tests first, so the body may run zero times.
n = 0
do while n < 3
    print "while"; n
    n += 1
loop

'' do until is the same test with the sense reversed.
n = 0
do until n = 3
    print "until"; n
    n += 1
loop

'' With the test after loop, the body always runs at least once.
n = 10
do
    print "ran once, with n ="; n
    n += 1
loop while n < 3

n = 0
do
    n += 1
loop until n * n > 50
print "first n whose square is over 50:"; n

'' A do with no test at all runs until something leaves it.
n = 0
do
    n += 1
    if n = 4 then exit do
loop
print "left the loop at"; n

Output

while 0
while 1
while 2
until 0
until 1
until 2
ran once, with n = 10
first n whose square is over 50: 8
left the loop at 4
FormTestsBody runs
do while c ... loopbefore each pass; continues while c is truezero or more times
do until c ... loopbefore each pass; continues until c is truezero or more times
do ... loop while cafter each passat least once
do ... loop until cafter each passat least once
do ... loopneveruntil exit do

The third block shows why the position matters. n starts at 10, so n < 3 is false from the beginning, yet the body runs once because the test comes after it. Put the test at the top when the body might not need to run at all, and at the bottom when the body produces the value the test looks at, as the square search does.

A do with no condition runs until something inside it leaves: exit do here, or exit sub, return, or an exit for aimed at an enclosing loop. exit and continue covers those.

Activities

  1. Rewrite the do until n = 3 loop as a do while loop with the same output.
  2. Change loop until n * n > 50 to loop while n * n <= 50. Is the result the same?