Program Logic and Design: AND and OR Operators

May 23, 2024

Program Logic and Design: AND and OR Operators

Combining AND and OR Operators

  • Multiple AND conditions: Use when all conditions must be true.

    • Example: To pass a course, each of three test scores must be ≥ 75.
    • Declare constant MinScore = 75.
    • Comparison expression: Score1 ≥ 75 AND Score2 ≥ 75 AND Score3 ≥ 75.
    • Result: All three scores need to be ≥ 75 to pass.
  • Multiple OR conditions: Use when any one condition must be true.

    • Example: To pass a course, at least one of three test scores must be ≥ 75.
    • Declare constant MinScore = 75.
    • Comparison expression: Score1 ≥ 75 OR Score2 ≥ 75 OR Score3 ≥ 75.
    • Result: If one score is ≥ 75, the evaluation short-circuits and the student passes.

Precedence in Combining AND and OR

  • AND takes precedence over OR: In mixed expressions, AND conditions are evaluated first.

    • Example: For a discounted ticket, the expression Age ≥ 65 AND Rating = 'G' is evaluated before Age ≤ 12.
  • Using Parentheses for Clarity:

    • Parentheses override default order of operations and improve clarity.
    • Example: (Age > 12 AND Age < 19) OR ValidID = 'Yes'.
    • Without parentheses: Pet = 'Dog' AND Age > 10 OR Age < 5.
    • With parentheses: Pet = 'Dog' AND (Age > 10 OR Age < 5).

Avoid Mixing AND and OR

  • Nesting IF Statements: Preferred to avoid logic complexity.

    • Example: Nested IF for age checks and movie rating.
      • If Rating = 'G':
        • If Age ≤ 12 or Age ≥ 65, apply discount.
        • Else, no discount.
  • Confidence with OR: If confident, use the OR operator in the first decision.

    • Example: Age ≤ 12 OR Age ≥ 65.
    • If true, apply discount; otherwise, proceed.

That concludes the section on making decisions. Next topic: Loops.