Example 4-5 |
The following program
evaluates and outputs the values of the logical expressions given in Example
4-4. Note that if a logical expression evaluates to true, the
corresponding output is 1; if
the logical expression evaluates to false, the corresponding output is 0, as shown in the output at the end of the program.
Recall that if the value of a logical expression is true, it evaluates to 1, and if the value of the logical expression is false, it evaluates to
0.
//Chapter 4: Logical operators
#include <iostream>
using namespace std;
int main()
{
bool
found = true;
bool
flag = false;
int
num = 1;
double
x = 5.2;
double
y = 3.4;
int
a = 5, b = 8;
int
n = 20;
char
ch = 'B';
cout<<"Line 1: !found evaluates
to "
<<!found<<endl; //Line 1
cout<<"Line 2: x > 4.0
evaluates to "
<<(x > 4.0)<<endl; //Line 2
cout<<"Line 3: !num evaluates to
"
<<!num<<endl; //Line 3
cout<<"Line 4: !found &&
(x >= 0) evaluates to "
<<(!found && (x >=
0))<<endl; //Line 4
cout<<"Line 5: !(found &&
(x >= 0)) evaluates to "
<<(!(found && (x >=
0)))<<endl; //Line 5
cout<<"Line 6: x + y <= 20.5
evaluates to "
<<(x + y <=
20.5)<<endl; //Line 6
cout<<"Line 7: (n >= 0)
&& (n <= 100) evaluates to "
<<((n >= 0) && (n <=
100))<<endl; //Line 7
cout<<"Line 8: ('A' <= ch
&& ch <= 'Z') evaluates to "
<<('A' <= ch && ch
<= 'Z')<<endl; //Line 8
cout<<"Line 9: (a + 2 <= b)
&& !flag evaluates to "
<<((a + 2 <= b) &&
!flag)<<endl; //Line 9
return 0;
}
Output:
Line
1: !found evaluates to 0
Line
2: x > 4.0 evaluates to 1
Line
3: !num evaluates to 0
Line
4: !found && (x >= 0) evaluates to 0
Line
5: !(found && (x >= 0)) evaluates to 0
Line
6: x + y <= 20.5 evaluates to 1
Line
7: (n >= 0) && (n <= 100) evaluates to 1
Line
8: ('A' <= ch && ch <= 'Z') evaluates to 1
Line
9: (a + 2 <= b) && !flag evaluates to 1
You can insert parentheses
into an expression to clarify its meaning. You can also use parentheses to
override the precedence of operators. Using the standard order of precedence,
the expression
11
> 5 || 6 < 15 && 7 >= 8
is equivalent to
11
> 5 || (6 < 15 && 7 >= 8)
In this expression, 11
> 5 is true, 6
< 15 is true, and 7
>= 8 is false. Substitute
these values in the expression 11 > 5 || (6 < 15 && 7 >= 8) to get true
|| (true && false) = true
|| false = true. Therefore, the
expression 11
> 5 || (6 < 15 && 7 >= 8) evaluates to true.