5.1 Logical statements
A logical variable (or Boolean variable) is either 0 (false) or 1 (true).
The basic way to define a logical variable is by relational operators by comparing two expressions. For example, we often ask if a variable x is bigger than a certain number?
A more sophiciated way is to combine two simple logical statements using logical operators.
5.1.1 Relational Operators
It compares two numerical expressions and return a Boolean variable: either 0 (FALSE) or 1 (TRUE). The following table shows the six commonly used relational operators
Relational operator | Interpretation |
---|---|
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
== | equal to |
!= | not equal to |
Precedence of relational operators is lower than arithmetic operators. To avoid confusion, it is good practice to use brackets to control ordering. For example, if we write 2 + 2 1 + 3, then the software we do the arithmetic operators first. This implies we have 4 4, which implies a false statement
5.1.2 Logical Operators
In practice, we often use two or more conditions to decide what to do. For example, scholarship is often given if the candidate has done well in both academic and extra-curricular activities.
To combine different conditions, there are three logical operators: (1) &&, (2) ||, and (3) !.
First, && is similar to AND in English, that is, A && B is true only if both A and B are true. Second, is similar to OR in English, that is, A || B is false only if both A and B are false. Third, ! is similar to NOT in English, that is, !A is true only if A is false.
A | B | A && B | A || B | !A | !B |
---|---|---|---|---|---|
false | false | false | false | true | true |
false | true | false | true | true | false |
true | false | false | true | false | true |
true | true | true | true | false | false |
Different relational operators, the precedence of logical operators can be high. While and and or operators are lower in precedence than relational operators, not has a very high precedence and almost always evaluated first. - Hence, it is always a good practice to use brackets to control operation ordering.