Chapter 3 (pp. 65–94) of Computer Science I.
Topics
| Section | Page | Content |
|---|---|---|
| Logical Operators | 65 | Comparison, negation, AND, OR, compound statements, short circuiting. |
| The If Statement | 75 | Basic branching. |
| The If-Else Statement | 76 | Two-way branching. |
| The If-Else-If Statement | 78 | Multi-way branching. |
| Ternary If-Else Operator | 82 | Expression-level conditional. |
| Examples | 82 | Meal Discount, Look Before You Leap, Comparing Elements, Life & Taxes. |
Key Ideas
- Short circuiting — evaluation stops once the result is determined; matters for guarding (e.g. null-check before dereference).
- Life & Taxes example recurs in C, Java, and PHP parts.
- Comparing elements motivates the comparator idea developed in searching & sorting.
Examples
Multi-way branching
if score ≥ 90:
grade ← "A"
else if score ≥ 80:
grade ← "B"
else:
grade ← "C"
Short circuiting as a guard
if x ≠ 0 and (10 / x) > 1:
print "safe"
The right side runs only when x ≠ 0, so there is no division by zero.
In Java
String grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else grade = "C";
if (x != 0 && 10 / x > 1) // && short-circuits: right side skipped when x == 0
System.out.println("safe");
Citations
[1] Computer Science I, Ch. 3, pp. 65–94.