Study Notes on Boolean Variables and Operators
Boolean Variables and Operators
- Evaluate logical conditions in programming using boolean variables.
- Boolean variables can hold two values: TRUE or FALSE.
- Boolean operations express complicated conditions.
Boolean Data Type in C++
bool type represents Boolean values.- Values:
true and false, not strings or integers. - Example of defining a Boolean variable:
bool isLegalAge = false;
Boolean Operations
- AND (&&): Evaluates to true if both operands are true.
- Example:
if (shark_free && sunny) - OR (||): Evaluates to true if at least one operand is true.
- Example:
if (sharks || rainy) - NOT (!): Evaluates to true if the operand is false.
- Example:
if (!shark_free)
Complex Conditions
- Use parentheses to define order of evaluation in complex conditions.
- Common errors include misusing
&& and ||.
DeMorgan’s Law
- Defines how to negate expressions:
-
!(A && B) = !A || !B
- !(A || B) = !A && !B
- Validate user input to prevent errors in programs (e.g., invalid floor number).
- Check for input failures with
cin.fail().
Implementing Decisions with if Statements
- Use
if statements to execute different actions based on conditions. - Use relational operators for comparisons:
<, <=, >, >=, ==, !=. - Nested
if statements allow for complex decision-making.
Summary
- Store conditions with
bool, combine conditions with &&, ||, and invert with !. - Validate and test user input to ensure correctness.