Operators and Expressions · Cambridge syllabus 8.1 · Lesson 2 of 4
Relational Operators
Relational operators compare values and produce Boolean results. Equality, inequality, greater-than and less-than comparisons are used in decisions and loops. Use inclusive comparisons when the boundary belongs to the accepted range.
By the end, you can
- Compare values using equality and inequality.
- Use greater-than and less-than comparisons.
- Build Boolean conditions.
Comparison
A relational operator compares two values and produces a Boolean. There are six: = for equal, <> for not equal, < less than, > greater than, <= less than or equal, and >= greater than or equal.
The result is TRUE or FALSE, nothing else, which is why a comparison can be used directly as a condition and can also be stored: IsAdult ← Age >= 18 is a perfectly ordinary assignment.
Comparison and assignment must not be confused. In pseudocode the arrow assigns and = compares, which keeps them apart; in languages where = assigns and == compares, writing one for the other is a classic bug that sometimes even compiles.
What the operators mean depends on the type. Numbers compare by value. Strings compare character by character using their character codes, so "apple" < "banana" as expected, but "Zebra" < "apple" as well, because upper-case letters have lower codes — which is why case-insensitive comparison converts both to the same case first. Booleans are compared with = and <>, so IF IsValid = TRUE tests a Boolean variable.
Two cautions. Never test two real numbers for exact equality, because they are stored approximately; test whether the difference between them is small enough instead. And "25" is not 25: comparing a string with a number either fails or gives nonsense, so convert first.
Worth remembering
- Six operators: =, <>, <, >, <=, >=, each giving TRUE or FALSE.
- Strings compare by character code, so case matters unless it is removed first.
- Never test two reals for exact equality; compare the difference instead.
Worked example
Age >= 12 includes 12, whereas Age > 12 does not.
Practice
Warm-up · not marked
Check your understanding
Answer in your own words, then compare with the worked answer. Nothing here is saved or scored.
Worked answer
Number >= 1 AND Number <= 10.
Check your method, units and explanation against it.
Marked practice
Set 1 of 4 · easiest first · Checked as you go, with the worked answer. Sign in or create a free account to save your progress.