CS 150 Introduction to C++ Programming - Spring 1998 

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


Logical Expressions (Exercise 2 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 variables i, j, p and q

	i = 10, j = 19, p = TRUE, q = FALSE

Add parenthesis (if necessary) to make the expressions below true
(to automate testing, don't type in any spaces (blanks))
IF THE EXPRESSION IS ALREADY TRUE, TYPE "TRUE" (in upper case)

  1.  i==j||p
  2.  i>=j||i<=j&&p
  3.  !p||p
  4.  !q&&q

 

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 10, 1998.