Skip to main content
Contents
Search Book
Search Results:
No results.
Readability settings Prev Up Next Scratch ActiveCode Profile
title here
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 5.7 Logical operators
There are three
logical operators in C++: AND, OR and NOT, which are denoted by the symbols ββ&&ββ, ββ||ββ and ββ!ββ. The semantics (meaning) of these operators is similar to their meaning in English. For example ββx > 0 && x < 10ββ is true only if x is greater than zero AND less than 10.
evenFlag || n%3 == 0 is true if
either of the conditions is true, that is, if evenFlag is true OR the number is divisible by 3.
Finally, the NOT operator has the effect of negating or inverting a bool expression, so !evenFlag is true if evenFlag is false; that is, if the number is odd.
Logical operators often provide a way to simplify nested conditional statements.
Checkpoint 5.7.1 .
Multiple Response: How could you re-write the following code using a single conditional?
if (x > 0) {
if (x < 10) {
cout << "x is a positive single digit" << endl;
}
}
if (x > 0 && x < 10) {...
This is exactly what the nested conditionals are saying.
if (x > 0 || x < 10) {...
|| represents "or", but we need both sides of the conditional to be true.
if (x > 0 ! x < 10) {...
The ! operator cannot be used to compare two sides of a conditional.
if ( !(x < 0) && !(x > 10) ) {...
If x = 0 or if x = 10, this expression will return true when it shouldnβt.
if ( !(x <= 0) && !(x >= 10) ) {...
If it IS NOT what we donβt want, then it IS what we want!
Checkpoint 5.7.2 .
Match the conditional statement to the correct boolean and the meaning of the operator in use, given n = 7.
Try again!
(n * 2 > 10 && n >= 7)
true, "and"
(n * 2 > 10 && n < 7)
false, "and"
(n%2 == 1 || n == 8)
true, "or"
(n%2 == 0 || n == 8)
false, "or"
!(n == 7)
false, "not"
!(n >= 10)
true, "not"
Checkpoint 5.7.3 .
You have attempted
of
activities on this page.