Program Logic and Design: Common Loop Applications

May 23, 2024

Program Logic and Design: Common Loop Applications

Introduction to Loops

  • Loops are commonly used for:
    • Accumulating totals
    • Validating data
  • Examples include:
    • Business reports with totals
    • List of real estate sales and their total value
  • Building a running total as we go in our loop using a cumulative variable

Accumulators

  • Accumulator: Gathers values or totals
    • Similar to a counter, but increments by a specific value
  • Steps for using an accumulator:
    1. Initialize to zero
    2. Alter once for every data set processed
    3. Output at the end of processing

Example: Monthly Sales Report

  • Task: Sum prices and generate a total
  • Method: createReport
    • Initialize accumulatedPrice to 0
    • For each address, add the price to accumulatedPrice
    • Outputs a summary with accumulated prices
  • Process: Playing computer
    • Start with accumulator at 0
    • Add each address's price sequentially
    • Update and store new accumulated price each iteration

Data Validation with Loops

  • Validate data to ensure it falls within an acceptable range
  • Defensive Programming: Prepare for all possible errors
    • Example: Reject invalid month numbers (e.g., less than 1 or greater than 12)
    • Use loops to re-prompt for valid input
  • GIGO (Garbage In, Garbage Out): Invalid input leads to invalid output

Example: Validating Birth Month Input

  • Use if statements to check validity
  • Use loops for multiple re-prompts
  • Limit iterations to avoid user frustration:
    • Give a fixed number of attempts (e.g., 3 chances)
    • Force a default value if invalid input persists

Validating Data Types

  • Ensure correct data type (e.g., numbers instead of strings)
  • Use built-in methods like isNumeric
    • Check validity and prompt user if invalid
    • Use loops to give multiple attempts
    • Force a default value after fixed attempts

Example: Validating Salary Input

  • Check if input is numeric
  • Re-prompt user if not numeric
  • Limit attempts and force a default value if necessary

Conclusion

  • Use loops to:
    • Validate data
    • Ensure reasonableness and consistency
  • Makes programs more user-friendly
  • Next topic: Comparing selections and loops