Loops
Repeat instructions with for, while and repeat until.
There are three kinds of loops in AlgoML: for, while and repeat ... until.
for
for counts from the first value to the last one, and both values are included. Add step 2 to count in twos, or a negative step to count down.
Algorithm Loopsversion '1.0'language Cvariable i : INTvariable n : INTbeginn <- 3for i in 1 to n dowrite(i, "\n")end forfor i in 1 to 9 step 2 dowrite(i, "\n")end forendend algorithm
1 2 3 1 3 5 7 9loops.aml on GitHubTry itSoon| Loop | Values of i |
|---|---|
for i in 1 to 3 | 1, 2, 3 |
for i in 1 to 9 step 2 | 1, 3, 5, 7, 9 |
for i in 3 to 1 step -1 | 3, 2, 1 |
for i in 5 to 4 | none: the body is skipped |
The counter must be an INT variable, declared like any other variable. Since the cells of an array are numbered from 1, for i in 1 to n goes through an array of size n.
If you know Python
range(1, n) stops at n - 1. In AlgoML, for i in 1 to n stops at n, so the generated Python uses range(1, n + 1).
while
while tests the condition before each turn. If it is false at the start, the body never runs. Use it when you do not know in advance how many turns are needed.
Algorithm Gcdversion '1.0'language Cfunction gcd(a : INT, b : INT) : INTvariable r : INTbeginwhile b <> 0 dor <- a mod ba <- bb <- rend whilereturn aend functionvariable x : INTvariable y : INTbeginread(x)read(y)write("gcd = ", gcd(x, y), "\n")endend algorithm
Something in the body must eventually make the condition false. Here b gets smaller at each turn until it reaches 0.
repeat until
repeat ... until runs the body once, then again until the condition becomes true. It is the right choice when the body must run at least once, for example to ask for a value until it is valid.
Algorithm Positiveversion '1.0'language Cvariable n : INTbeginrepeatwrite("Enter a positive number: ")read(n)until n > 0write("Thank you, you entered ", n, "\n")endend algorithm
-4 0 9Output Enter a positive number: Enter a positive number: Enter a positive number: Thank you, you entered 9positive.aml on GitHubTry itSoonNote the difference: while continues while the condition is true, repeat continues until it becomes true.
Which loop to choose
| Situation | Loop |
|---|---|
| You know the number of turns, or you go through an array | for |
| The loop may not run at all | while |
| The loop must run at least once | repeat ... until |
Exercise
Exercise
Display the even numbers from 2 to 20, one per line, with a for loop from 1 to 10.