Conditions
Choose what to do with if, elseif, else and switch.
if
if temperature > 30 thenwrite("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 Gradeversion '1.0'language Cvariable mark : INTbeginread(mark)if mark >= 16 thenwrite("Very good\n")elseif mark >= 12 thenwrite("Good\n")elseif mark >= 10 thenwrite("Pass\n")elsewrite("Fail\n")end ifendend algorithm
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 Weekdayversion '1.0'language Cvariable day : INTbeginread(day)switch (day) :case 6 :write("Saturday: weekend\n")case 7 :write("Sunday: weekend\n")default :write("Weekday\n")end switchendend algorithm
- The variable must be an
INT, aREAL, aSTRINGor an enum. ABOOLEANis refused: useif. - Each
casevalue appears only once. defaultis required. It runs when nocasematches.- 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.