An Overview of Boolean Expressions

advertisement
Boolean Expressions and Selection
Relational Operators
There are six relational operators that can be used to form boolean expressions
from numeric primitive data types. These are:
< , > , <= , >= , == , 𝑎𝑛𝑑 ! = , and they represent less than, greater than,
less than or equal, greater than or equal, equal, and not equal.
expression1 relational_operator expression2
The relational operator is used to compare the value of expression1 to the value of
expression 2 and provides a value of either true or false.
Logical Operators
Logical operators are used to compute a boolean value based on one or more
boolean expressions. Suppose A and B represent boolean expressions and consider
the following:
A && B
true if and only if A is true and B is true
A || B
true if A is true, or B is true, or both A and B are true.
!A
true if A is false and false if A is true (negation)
Examples:
p <= q || p == 0
!p || q
b <= 5 && c >= 12 || x == 12
Selection
We will consider three forms of the if statement. What does each do?
if(boolean expression)
{
block of code
}
This is a single selection. If the boolean expression is true, the block is executed;
otherwise, it is skipped.
-------------------------------------------------
if(boolean expression)
{
block_1 of code
}
else{
block_2 of code
}
This is a two-way selection. If the expression is true, block_1 is executed; otherwise,
block_2 is executed.
------------------------------------------------if(boolean expression_1)
{
block_1 of code
}
else if(boolean expression_2)
{
block_2 of code
}
else if(boolean expression_3)
{
block_3 of code
}
...
else if (boolean expression_n)
{
block_n of code
}
else
{
last block of code
}
This is a multi-way selection which selects only the block of code associated with the
first boolean expression that is true. It may be that the final else block is not
included. If it is there, then it becomes the default code if none of the boolean
expressions is true. If it isn’t there and none of the expressions is true, then nothing
is executed.
-------------------------------------------------
Download