Loops
Loops
Looping expressions come in three flavors: while, repeat…until, and loop. The while statement syntax looks like:
while (a lt b)
a = a + 1
b = b – 1
… ; next statement after the loop
This loop starts by evaluating the test expression, a < b. If the test evaluates as TRUE, the indented statements are executed in order. After the last indented statement is executed, the test is repeated. As long as the test is TRUE, the loop is repeated.
The repeat…until loop is similar:
repeat
Statement1
Statement2
Statement3
until (Test)
… ; continuing after loop
This works just like you might imagine. The statements are repeated over and over again until the test becomes TRUE. The statements in the repeat…until loop are always executed at least once, unlike those in the while loop, which can be skipped completely.
The last loop is even simpler:
loop
Statement1
Statement2
Statement3
… ; continuing after loop
If you see a problem with this syntax, you’re correct—loop repeats ad nauseam. To escape the endless loop, use the break statement:
loop
a = a – 1
if (a lt 0) break
print(a)
… ; continuing after loop
The break causes the loop to terminate without executing the rest of the statements. This syntax allows you to create any type of loop structure.
There is also a similar continue statement which skips the rest of the statements but doesn’t terminate the loop:
loop
a = a + 1
if (IsPrime(a))
continue
PrintFactors(a)
if (a gt 170)
break
… ; continuing after loop
The break and continue expressions also work with the while and repeat…until loops.
Comments are closed.