CS 150 Introduction to C++ Programming - Spring 1998 

[ Home | Lecture Notes| WebTutor | WebTutor Site Map]


Evaluating Logical Expressions (Exercise 1 Chapter 5)


Logical expressions are similar in many ways to arithmetic expressions, except that they produce a logical (true or false) answer instead of a number.
Logical expressions are used as conditions in "if", "while" and "for" statements (last two are coming soon).
Like arithmetic expressions, logical expressions consist of operators and operands (e.g. a + b, a < b, the first is an arithmetic expression with operator '+' and the second is a logical expression with operator '<').
It is even possible to have both arithmetic and logical operators in the same expression (e.g. a + b < c).
Since there may be ambiguity about which operator to apply first in a complicated expression, we need to apply the rules of precedence and group order.
We saw these concepts for arithmetic expressions in exercise 2 chapter 3 (click here to review this topic).

For C++, the precedence of operators is

Grouping Operators Comments
Parenthesis(2)
(  )
 
Unary Group(2)
-   !
- for negative numbers
! negates (reverses) truth value
Multiplicative Group(3)
*   /   %
% modulus (remainder)
Additive Group(2)
+    -
 
Inequality Group(4)
<  <=   >   >=
<= less or equal
>= greater or equal
Equality Group(2)
==    !=
= = equal

!= not equal

Logical And(1)
      &&
&& logical AND
Logical Or(1)
      ||
| | Logical OR
Assignment(1)
      =
 
For more details see page 197, or A1-2 in the text
BE CAREFUL!!! the Assignment Operator '=' is very different from the Equality operator "= ="
This is one mixup that catches both beginners and experienced programmers alike!

Given these values for the Boolean variables x, y and z.
x = TRUE; y = FALSE; z = TRUE;
Evaluate the following expressions and tell if the result if TRUE or FALSE.

  TRUE FALSE
x && y || x && z
(x || !y) && (!x || z)
x || y && z
!(x || y) && z
Choose one when done
   

Copyright chris wild 1998.
For problems or questions regarding this web contact [Dr. Wild (e-mail:wild@cs.odu.edu].
Last updated: February 21, 1998.