Expressions and operators
Arithmetic, comparisons, logic, operator priority and compound assignment.
Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | Add, subtract, multiply | 7 * 2 | 14 |
/ | Division, always a REAL | 7 / 2 | 3.5 |
div | Integer quotient | 7 div 2 | 3 |
mod | Remainder | 7 mod 2 | 1 |
div and mod work on INT values. To keep an integer result, use div rather than /.
Comparisons
| Operator | Meaning |
|---|---|
= | equal |
<> | different |
< <= | lower, lower or equal |
> >= | greater, greater or equal |
Note that = compares and <- assigns. A comparison gives a BOOLEAN.
Logic
AND, OR and NOT combine BOOLEAN values. Their operands must be BOOLEAN: NOT 5 is an error.
Algorithm Operatorsversion '1.0'language Cvariable a : INTvariable b : INTvariable even : BOOLEANbegina <- 17b <- 5write(a div b, "\n")write(a mod b, "\n")even <- a mod 2 = 0if NOT even AND a > b thenwrite("a is odd and greater than b\n")end ifa +<- 3write(a, "\n")endend algorithm
Output
3 2 a is odd and greater than b 20operators.aml on GitHubTry itSoonPriority
From the highest to the lowest:
NOTand the unary-*,/,div,mod+,-- comparisons
AND,OR, from left to right
So a mod 2 = 0 is read as (a mod 2) = 0. When in doubt, add parentheses: they make the intention clear and change nothing in the generated code.
Compound assignment
| Short form | Same as |
|---|---|
x +<- 3 | x <- x + 3 |
x -<- 3 | x <- x - 3 |
x *<- 3 | x <- x * 3 |
x /<- 3 | x <- x / 3 |
They work on INT and REAL variables. Remember that / gives a REAL: x /<- 2 is refused when x is an INT.