AlgoML
FR

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 Loops
version '1.0'
language C
variable i : INT
variable n : INT
begin
n <- 3
for i in 1 to n do
write(i, "\n")
end for
for i in 1 to 9 step 2 do
write(i, "\n")
end for
end
end algorithm
Output 1 2 3 1 3 5 7 9loops.aml on GitHubTry itSoon
LoopValues of i
for i in 1 to 31, 2, 3
for i in 1 to 9 step 21, 3, 5, 7, 9
for i in 3 to 1 step -13, 2, 1
for i in 5 to 4none: 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 Gcd
version '1.0'
language C
function gcd(a : INT, b : INT) : INT
variable r : INT
begin
while b <> 0 do
r <- a mod b
a <- b
b <- r
end while
return a
end function
variable x : INT
variable y : INT
begin
read(x)
read(y)
write("gcd = ", gcd(x, y), "\n")
end
end algorithm
Input 48 36Output gcd = 12gcd.aml on GitHubTry itSoon

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 Positive
version '1.0'
language C
variable n : INT
begin
repeat
write("Enter a positive number: ")
read(n)
until n > 0
write("Thank you, you entered ", n, "\n")
end
end algorithm
Input -4 0 9Output Enter a positive number: Enter a positive number: Enter a positive number: Thank you, you entered 9positive.aml on GitHubTry itSoon

Note the difference: while continues while the condition is true, repeat continues until it becomes true.

Which loop to choose

SituationLoop
You know the number of turns, or you go through an arrayfor
The loop may not run at allwhile
The loop must run at least oncerepeat ... until

Exercise

Exercise

Display the even numbers from 2 to 20, one per line, with a for loop from 1 to 10.

Report a problem with this page