AlgoML
FR

Conditions

Choose what to do with if, elseif, else and switch.

if

if temperature > 30 then
write("It is hot\n")
end if

The condition must be a BOOLEAN: a comparison, a BOOLEAN variable or a combination with AND, OR and NOT. if n then is refused when n is a number: write if n <> 0 then.

elseif and else

Add as many elseif blocks as you need, and one else at the end. The first condition that is true wins, the others are skipped.

Algorithm Grade
version '1.0'
language C
variable mark : INT
begin
read(mark)
if mark >= 16 then
write("Very good\n")
elseif mark >= 12 then
write("Good\n")
elseif mark >= 10 then
write("Pass\n")
else
write("Fail\n")
end if
end
end algorithm
Input 13Output Goodgrade.aml on GitHubTry itSoon

With a mark of 13, the first test (13 >= 16) is false, the second one (13 >= 12) is true: the program displays Good and skips the rest.

switch

switch compares one variable with several values. It is shorter than a long chain of elseif when every test is an equality.

Algorithm Weekday
version '1.0'
language C
variable day : INT
begin
read(day)
switch (day) :
case 6 :
write("Saturday: weekend\n")
case 7 :
write("Sunday: weekend\n")
default :
write("Weekday\n")
end switch
end
end algorithm
Input 7Output Sunday: weekendweekday.aml on GitHubTry itSoon
  • The variable must be an INT, a REAL, a STRING or an enum. A BOOLEAN is refused: use if.
  • Each case value appears only once.
  • default is required. It runs when no case matches.
  • Only the matching case runs: there is no fall-through as in C.

Exercise

Exercise

Read three whole numbers and display the largest one. Try it with 7, 19 and 4.

Report a problem with this page