teach-ict.com logo

THE education site for computer science and ICT

Sequence Selection Iteration

3. Selection: Comparisons

Other than for the most basic tasks, most programs involve having to make choices. Maybe you want to do one thing if a condition is true and another if it is not. The process of determining which choice to take is called 'selection'.

Comparison operators

Selection always involves a comparison operation, where you check whether certain conditions are met. The comparison operators are

 

Meaning Symbol
Greater than
>
Less than
<
Greater than or equal to
>=
Less than or equal to
<=
Not equal to
!=
Are the same
==

The last one (==) is often confused with the equal sign =. They are not the same thing.

If you use =, you are setting (aka assigning) one value to be equal to another.

If you use ==, you are comparing one value to another to see if they are equal.

For example if you say "chalk = cheese", then you are telling the computer that chalk is cheese. If you say "chalk == cheese", you are asking the computer to check whether chalk is cheese.

Comparison - Boolean operators

This is a logical comparion, the result is either logical TRUE or logical FALSE.

The comparison is laid out for the AND operator as

Expression 1 AND Expression 2

The OR operator is similar with

Expression 1 OR Expression 2

The NOT operator only uses one expression

NOT (Expression)

The boolean operators are

Meaning Symbol
Both sides must be true for the result to be true
AND
Either or both sides are true for the result to be true
OR
The result is the opposite of the expression. If expression is true, the result is false. If the expression is false, the result is true
NOT

For example (Expression 1 AND Expression 2) the comparison leads to a TRUE result only if both expressions are also TRUE, otherwise the comparison leads to FALSE

And for the OR operator, the statement (Expression 1 OR Expression 2) is TRUE if either one or both is TRUE. If both expressions are FALSE then the comparison is also FALSE

Combine comparisons

You can combine size operators with a boolean operator to make two comparisons in the same statement, like this

                     (a < 2) AND (b > 4)

The boolean AND operator means that both expressions need to be true for the evaluation to be true.

 

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: What is selection in programming?