CSCI 201 Study Aid: Logical Operators

Logical Operators

C++ provides logical operators that may be used to form more complex conditions by combining simple conditions. The logical operators are:

The following examples illustrate the use of each logical operator.


The AND (&&) operator:

When the AND operator, &&, is used with two simple expressions, the condition is true only if both individual expressions are true by themselves. Thus the compound condition

   if ( ( age > 40 ) && ( term < 10 ) )
      {
      cout << "age is greater than 40 AND"
      cout << "term is less than 10"
      }

is read as "if age is greater than 40 AND term is less than 10". This condition is true (has a non-zero value) only if age is greater than 40 and term is less than 10.


The OR (||) operator:

The logical OR operator, ||, is also applied between two expressions. When using the OR operator, the condition is satisfied if either one or both of the two expressions is true. Thus the compound condition

   if ( ( age > 40 ) || ( term < 10 ) )
      {
      cout << "age is greater than 40 OR"
      cout << "term is less than 10"
      }

will be true if either age is greater than 40, term is less than 10, or both conditions are true.


The NOT (!) operator:

The NOT operator is used to change an expression to its opposite state; that is, if the expression has any nonzero value (true), !expression produces a zero value (false). If an expression is false to begin with (has a zero value), !expression is true and evaluates to 1. For example, assuming the object age has a value of 26, the expression ( age > 40 ) has a value of zero (it is false), while the expression !( age > 40 ) has a value of 1.

   if !( age > 40 )
      cout << "age is NOT greater than 40"

Questions

Assume:

 i = 2, j = 7, k = 6, and m = 1

What does each of the following statements print?

  1. cout << ( i == 10 ) << endl;
    
    
  2. cout << ( j == 7 ) << endl;
    
    
  3. cout << ( i >= 6 && j < 2 ) << endl;
    
    
  4. cout << ( m <= 1 && k < m ) << endl;
    
    
  5. cout << ( j >= i || k == m ) << endl;
    
    
  6. cout << ( k + m < j || 4 - j >= k ) << endl;
    
    
  7. cout << ( ! m ) << endl;
    
    
  8. cout << ( !( j - m ) ) << endl;
    
    
  9. cout << ( !( k > m ) ) << endl;
Solution