Logical Expressions
-
Because the compiler recognizes
10 < value
already as an expression, it expects a comma after it to accept it as a legal argument towriteln
. Using parentheses around the whole expression would not work either, because this time a closing parenthesis would be expected after the same expression. - Grouping the expression as
(10 < value) < 20
removes the compilation error, because in this case first10 < value
is evaluated and then its result is used with< 20
.We know that the value of a logical expression like
10 < value
is eitherfalse
ortrue
.false
andtrue
take part in integer expressions as 0 and 1, respectively. (We will see automatic type conversions in a later chapter.) As a result, the whole expression is the equivalent of either0 < 20
or1 < 20
, both of which evaluate totrue
. - The expression "greater than the lower value and less than the upper value" can be coded as follows:
writeln("Is between: ", (value > 10) && (value < 20));
- "There is a bicycle for everyone" can be coded as
personCount <= bicycleCount
orbicycleCount >= personCount
. The rest of the logical expression can directly be translated to D from the exercise:writeln("We are going to the beach: ", ((distance < 10) && (bicycleCount >= personCount)) || ((personCount <= 5) && existsCar && existsLicense) );
Note the placement of the
||
operator to help with readability by separating the two main conditions.