Chapter Summary
This chapter introduces selection, the fundamental programming concept that allows programs to execute different code paths based on conditions. Selection is essential because real-world problems often require different actions depending on specific circumstances.
Key Concepts
-
Boolean Expressions and Comparison Operators
- Comparison operators:
(==, !=, <, >, <=, >=)compare values and produce truthy or falsey results - Truthy and Falsey: In C, zero (0) is falsey; all other values are truthy
- Common pitfall: Distinguish between assignment
(=)and equivalence(==)operators
- Comparison operators:
-
Logical Operators
- And (&&): True only when both operands are true
- Or (||): True when at least one operand is true
- Not (!): Reverses the truth value of an expression
-
Control Structures
- if/else statement: Executes one block if a condition is true, another if false
- if/else if/else statement: Handles multiple mutually exclusive conditions in sequence
- Independent conditions if/if/.../if: Use separate if statements when choices are not mutually exclusive
-
Practical Applications
- Mutually exclusive conditions: When only one of several options can be true (e.g., age categories for transit fares)
- Default values: Initialize variables with default values and modify them only when specific conditions are met
- Independent conditions: When multiple options can be true simultaneously (e.g., adding toppings to a drink)
- Testing if x is between a and b inclusive:
x >= a && x <= b - Testing if x is outside of range from a and b:
(x < a) || (x > b)