Programming Concept

Conditionals

Logical operators, if / if-else / if-else-if statements, and the ternary operator.

Chapter 3 (pp. 65–94) of Computer Science I.

Topics

SectionPageContent
Logical Operators65Comparison, negation, AND, OR, compound statements, short circuiting.
The If Statement75Basic branching.
The If-Else Statement76Two-way branching.
The If-Else-If Statement78Multi-way branching.
Ternary If-Else Operator82Expression-level conditional.
Examples82Meal 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.