Logical Operators Example

Figure 5.18 demonstrates the logical operators by producing their truth tables. The output shows each expression that’s evaluated and its bool result. By default, bool values true and false are displayed by cout and the stream insertion operator as 1 and 0, respectively. We use stream manipulator boolalpha (a sticky manipulator) in line 9 to specify that the value of each bool expression should be displayed as either the word “true” or the word “false.” For example, the result of the expression false && false in line 10 is false, so the second line of output includes the word “false.” Lines 9–13 produce the truth table for &&. Lines 16–20 produce the truth table for ||. Lines 23–25 produce the truth table for !.


 1   // Fig. 5.18: fig05_18.cpp
 2   // Logical operators.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main()
 7   {
 8      // create truth table for && (logical AND) operator
 9      cout << boolalpha << "Logical AND (&&)"
10         << " false && false: " << ( false && false )
11         << " false && true: " << ( false && true )
12         << " true && false: " << ( true && false )
13         << " true && true: " << ( true && true ) << " ";
14
15      // create truth table for || (logical OR) operator
16      cout << "Logical OR (||)"
17         << " false || false: " << ( false || false )
18         << " false || true: " << ( false || true )
19         << " true || false: " << ( true || false )
20         << " true || true: " << ( true || true ) << " ";
21
22      // create truth table for ! (logical negation) operator
23      cout << "Logical NOT (!)"
24         << " !false: " << ( !false )
25         << " !true: " << ( !true ) << endl;
26   } // end main


Logical AND (&&)
false && false: false
false && true: false
true && false: false
true && true: true

Logical OR (||)
false || false: false
false || true: true
true || false: true
true || true: true

Logical NOT (!)
!false: true
!true: false


Fig. 5.18. Logical operators.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.76.250