Fundamentals of Programming – Lesson 4 Notes

The Selection Structure

  • Purpose: one of the three basic control structures; starts with evaluating a Boolean expression and branches based on the outcome.
  • Dual-alternative selection (if-then-else): actions on two mutually exclusive outcomes (left vs right branches).
    • Example: Depending on the Boolean decision, flow goes to one of two alternatives.
    • Key characteristic: mutually exclusive outcomes; exactly one path is taken.
  • Single-alternative selection (if-then): action is required for only one outcome; no else action.
  • Real-world analogy: medical-diagnosis or route-selection programs illustrate decision-making in software.
  • Program example (described in Figure 4-3): interactive program computing pay for employees at a fixed hourly rate (15.0015.00) with overtime pay for hours > 40 per week.
    • Mainline calls housekeeping(), detailLoop(), and finish() modules.
    • detailLoop() contains a dual-alternative decision: if worked > 40 hours, pay overtime at 1.5×; else pay regular rate.
    • The if-then clause handles the overtime calculation; the else clause handles the regular calculation.
  • Important terminology:
    • if-then: action(s) when condition is true.
    • else: action(s) when condition is false.
    • Nested decisions can implement AND logic within a single flow.

Relational Comparison Operators

  • Six operators used across languages (binary):
    • equality: a=ba = b
    • greater than: a > b
    • less than: a < b
    • greater than or equal: aba \,\ge\, b (written as aba \ge b in LaTeX)
    • less than or equal: aba \le b
    • not equal: aba \neq b (or sometimes a <> b)
  • Operands must be of the same data type (numbers vs numbers; strings vs strings).
  • Examples in the transcript:
    • currentTotal = 100 evaluates to true/false depending on value.
    • Comparing strings: "black" precedes "blue" alphabetically; strings are often case-sensitive unless specified.
    • It is generally not useful to compare two literals (e.g., 20=2020 = 20) because result is always true.
  • String comparisons: many languages compare strings by alphabetic order; identical strings include exact spacing and case.
  • Decisions are driven by combinations of three basic comparisons: equal, greater than, less than. The additional operators (>=, <=, !=) are conveniences.
  • Common guidance:
    • Use greater-or-equal-to (≥) when policy says "65 or older" rather than strictly > 64.
    • Be careful with not-equal (<>, !=) as it can be confusing and prone to logic errors.
  • Boundary and interpretation issues:
    • If a boss says "over 65" vs "65 or older", clarify whether 65 is included. Double-check intended meaning with end users or supervisors.
  • Practical note: mixing constants with variables in expressions illustrates true/false outcomes; avoid comparing two literals.

AND Logic

  • Purpose: evaluate more than one expression to determine whether an action should occur.
  • Compound condition: both parts must be true for the action to occur.
  • Real-world example (cell-phone billing):
    • Base bill: 30.0030.00; Premiums apply if (callsMade > CALLS) AND (callMinutes > MINUTES).
    • Premium: 20.0020.00 added when both conditions true; otherwise, no premium.
    • Nested or cascading if statements implement the AND logic.
  • Efficiency & short-circuit evaluation:
    • Truth table and short-circuit concept: evaluation proceeds left to right; if the first condition is false, the second is not evaluated.
    • This can improve performance when one condition is much more likely to fail.
  • Strategies for AND:
    • Use AND to combine two or more Boolean expressions in a single expression, e.g., callsMade > CALLS \,\land\, callMinutes > MINUTES.
    • When both parts are needed, you can also implement via nested if statements (cascading ifs).
    • If you know which condition is less likely to be true, evaluate it first to reduce the number of evaluations.
  • Truth table (concept): x AND y is true only if both x and y are true.
  • Short-circuit behavior:
    • If the first part is false, the second part is not evaluated.
  • Benefits of using AND: conciseness, fewer errors, clearer intent.

Avoiding Common Errors in an AND Selection

  • Ensure that decisions that should be nested are nested; do not mix separate decisions in a way that yields incorrect or duplicate results.
  • Complete Boolean expressions on each side of the AND operator; both sides must be complete Boolean expressions.
  • Avoid trivial (tautological) expressions where both sides can never be true simultaneously; such expressions produce no effect.
  • Example pitfalls shown in Figures 4-11 and 4-12: incorrect nesting or evaluation order can cause incorrect or duplicate results.

OR Logic

  • Purpose: action should occur if at least one of two conditions is true.
  • OR decision requires only one condition to be true for the action to take place.
  • Example: new billing scheme where premium applies if (callsMade > CALLS) OR (textsSent > TEXTS).
    • If calls exceed threshold, premium is added; otherwise, check texts.
  • Efficiency considerations:
    • If one condition is more likely to be true, evaluate it first to reduce the number of evaluations.
    • Like AND, short-circuit evaluation applies: evaluation stops once a true condition is found.
  • Important notes:
    • When using OR, ensure boolean expressions on both sides are complete (e.g., (callsMade > CALLS) OR (textsSent > TEXTS)).
    • It’s easy to misuse OR by creating dead branches or duplicating logic; ensure structured and non-redundant design.

Writing OR Selections for Efficiency

  • You can use a single combined expression with OR, or use two separate nested selections; languages typically support both.
  • Example efficiency comparison:
    • If 900 of 1000 customers exceed calls, testing calls first reduces subsequent checks for many customers.
    • If 500 customers pass the first test, testing texts second yields 450 premiums; overall decisions differ but end result is the same.
  • Rule of thumb: In an OR decision, evaluate the condition that is more likely to be true first to minimize total decisions.

Make Sure that Boolean Expressions Are Complete

  • Each side of an OR (or AND) must be a complete Boolean expression.
  • Example: invalid: callsMade 5 0 OR callsMade > 2000 (second side missing full expression).
  • Use parentheses for clarity if needed, e.g., if (callsMade > CALLS) OR (textsSent > TEXTS) then …

Making Selections within Ranges

  • Range checks use a series of values as the boundaries of ranges (e.g., discount rates by itemQuantity).
  • Two common approaches:
    • Use the low ends of the ranges: e.g., test if itemQuantity < 11, then < 25, then < 51.
    • Use the high ends of the ranges: test if itemQuantity <= 10, then <= 24, then <= 50.
  • Example (high ends): the program checks RANGE1 (low end of range) first; if itemOrdered <= RANGE1, assign DISCOUNT1; else test RANGE2, etc.
  • Pseudocode pattern (high ends):
    • if itemOrdered <= RANGE1 then discount = DISCOUNT1
    • else if itemOrdered <= RANGE2 then discount = DISCOUNT2
    • else if itemOrdered <= RANGE3 then discount = DISCOUNT3
    • else discount = DISCOUNT4
  • Common errors and optimization:
    • Dead paths: testing a range limit that's already implied by a previous test.
    • Unnecessary questioning: testing both LIMITs when one test already determines outcome.
    • Not using else to terminate a path can lead to unreachable or redundant checks.
  • Range-check design tips:
    • Eliminate dead paths; do not test a limit that is already implied by earlier checks.
    • Avoid testing the same range limit multiple times; restructure with else-if chains.

Understanding Precedence When Combining AND and OR Operators

  • Precedence rule: AND operators take precedence over OR operators.
  • Example (three tests): if score1 >= MINSCORE AND score2 >= MINSCORE AND score3 >= MIN_SCORE then classGrade = "Pass" else classGrade = "Fail" endif
  • If you only need one of three tests to pass: if score1 >= MINSCORE OR score2 >= MINSCORE OR score3 >= MIN_SCORE then classGrade = "Pass" else classGrade = "Fail" endif
  • Complications arise when combining AND and OR in a single expression; AND binds tighter than OR.
  • Problem scenario: movie theater discount for children and senior citizens (G-rated movies):
    • Without parentheses, a 10-year-old with an R-rated movie could mistakenly receive a discount.
    • Correct approach uses parentheses to ensure age condition is evaluated in conjunction with rating: if (age
  • Techniques to avoid confusion:
    • Use parentheses to override precedence when needed.
    • Use nested if statements to avoid complex mixed-operator expressions.
    • The flowchart in Figure 4-24 demonstrates that OR can be scoped inside the rating decision for clarity.

Understanding NOT Logic

  • NOT is a unary operator that reverses the meaning of a Boolean expression.
  • Example: output "Can register to vote" when age is >= 18 using NOT:
    • if NOT (age < 18) then output "Can register to vote" endif
  • NOT Truth Table: inverts the truth value of a single Boolean expression.
  • Common pitfalls:
    • NOT can lead to confusing double negatives; keep expressions readable.
    • Avoid trivial NOT expressions that always evaluate to a fixed result.
  • NOT with range logic examples:
    • Incorrect approach: NOT (employeeDept = 1) OR NOT (employeeDept = 2) can still produce true for some inputs, causing incorrect output.
    • Correct approach: NOT (employeeDept = 1 OR employeeDept = 2) ensures the message only appears if the department is neither 1 nor 2.

Making Selections within Ranges (Continued)

  • Range checks (discounts by quantity) using high-end values: RANGE1 = 10, RANGE2 = 24, RANGE3 = 50; DISCOUNT1 = 0, DISCOUNT2 = 0.10, DISCOUNT3 = 0.15, DISCOUNT4 = 0.20
  • Example walk-through: for itemsOrdered = 30, test against high ends; approach yields the correct discount DISCOUNT3 (0.15).
  • Avoiding common errors in range logic:
    • Dead path detection (Figure 4-22): avoid testing RANGE3 if previous tests already imply itemOrdered > RANGE3.
    • Do not test multiple times the same boundary (Figure 4-23): once a boundary is known to be exceeded, subsequent tests on that boundary are unnecessary.

Case Structure

  • What is it? A specialized selection structure used when there are several distinct values for a single variable, with a different action for each value.
  • Example: tuition varies by year (freshman, sophomore, junior, senior). A case structure tests year against a list of values and executes corresponding actions.
  • Advantage: can be easier to read and can execute faster in many languages than a long series of if-else statements.
  • Rule of use: use a case structure only when a single expression determines multiple distinct outcomes. If multiple expressions are tested, a nested series of decisions is appropriate.

Lesson Summary (Key Points)

  • Decisions are made by evaluating Boolean expressions; if-then-else or if-then structures provide two outcomes.
  • Relational operators compare operands of the same data type: =, >, <, \ge, \le, \neq.
  • In an AND decision, two conditions must be true; nesting or an AND operator is typically used; start with the condition less likely to be true for efficiency.
  • In an OR decision, at least one condition must be true; start with the condition more likely to be true for efficiency.
  • NOT reverses the meaning of a Boolean expression; it is unary, so it applies to a single expression.
  • Range checks compare a variable to the ends of ranges; test the low end or the high end, using either approach, and avoid dead paths or repeated checks.
  • When combining AND and OR, AND has precedence; use parentheses to override or to clarify precedence when needed.
  • The case structure is a specialized selection mechanism used when several distinct values for a single variable exist; it can improve readability and efficiency.

Practice and Assessment Tasks (Overview of Exercises)

  • Exercise 1 (Boolean expressions): evaluate a set of mixed operands (numbers and strings) for truth, falsity, or illegality across various operators and type constraints.
  • Exercise 2: design a flowchart or pseudocode for a two-number comparison that outputs which is larger or if they are equal.
  • Exercise 3: design a flowchart or pseudocode for a three-number problem that detects whether the sum of any two equals the third.
  • Exercise 4: Cecilia’s Boutique—design programs to identify high performers by items sold (>200), or by items worth >$1,000; handle sentinel values for continuous data entry; produce lists under various criteria.
  • Exercise 5: ShoppingBay—design reports based on auction item data (minimum bid, etc.) with multiple conditions and sentinel-based data entry.
  • Exercise 6: The Dash Cell Phone Company—calculate monthly bills with tiered text-message pricing and tax; design for data entry with sentinel values and area-code filtering.
  • Exercise 7: Drive-Rite Insurance—multiple programs to validate policy data, filter cohorts by age, due dates, and other criteria; use sentinel values for continuous input; support complex conditions.
  • Exercise 8: The Barking Lot dog day care—billing by weight tiers; incremental data entry; generate reports for various conditions.
  • Exercise 9: Mark Daniels signs—pricing logic by wood type, length of sign, and lettering; include design for specific scenarios (oak with five white letters; pine with gold-leaf and more than 10 characters).
  • Exercise 10: Carpool optimization—determine eligibility based on towns; generate candidate/ineligible lists with efficient decision-making.
  • These exercises emphasize: constructing and evaluating complex Boolean logic, using AND/OR/NOT, employing range checks, understanding precedence, and designing efficient, structured solutions.

References and Further Reading

  • The material draws on Fundamentals of Programming, Lesson 4, including discussions of selection structures, relational operators, AND/OR/NOT logic, range checks, precedence, and the case structure.
  • For further reading, reference the listed sources in the transcript (e.g., Farrel, 2024; Sebesta, 2020; Horstmann, 2019; Ellison, 2022; etc.).