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
| Form | Tests | Body runs |
|---|---|---|
do while c ... loop | before each pass; continues while c is true | zero or more times |
do until c ... loop | before each pass; continues until c is true | zero or more times |
do ... loop while c | after each pass | at least once |
do ... loop until c | after each pass | at least once |
do ... loop | never | until 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
- Rewrite the
do until n = 3loop as ado whileloop with the same output. - Change
loop until n * n > 50toloop while n * n <= 50. Is the result the same?