Using Loop Control Variables

May 23, 2024

Using Loop Control Variables

Overview

  • Discussing the concept and use of loop control variables in loop structures.
  • Loop control variable: A condition to control the number of repetitions in a loop.

Steps to Control Loop Repetitions

  1. Initialize Loop Control Variable: Before entering the loop.
  2. Test Control Variable: Done in the condition of the loop.
  3. Alter Control Variable: Modify in the loop body.

Types of Loops

1. Definite Loop

  • Executes a predetermined number of times.
  • Counter-controlled loop: Programm counts loop repetitions.
  • Alter by incrementing or decrementing (typically by 1).
  • Example of Counter:
    • Initialize count to 0.
    • Evaluate if Count is less than a specified number.
    • Increment count after executing the loop body.
    • Example provided in lecture outputs "hello" four times.

2. Infinite Loop

  • When the program endlessly runs the loop.
  • Strategies to avoid: Proper initialization, testing, and alteration.

3. Indefinite Loop

  • Uses Sentinel value (user decides the number of repetitions).
  • Example:
    • User is prompted to continue or stop the loop.
    • Loop control variable is modified based on user input.

Strategy for Proper Loops

  1. Starting Value: Provide an initial value for control variable.
  2. Testing the Loop Variable: Check meaningful conditions to determine repetitions.
  3. Altering Control Variable: Update the count to keep track of iterations.

Example: Payroll Program

  • Sentinel value in the form of a name.
  • Loop until a specific quit condition (e.g., xxx).

Conclusion

  • Key points covered: Loop control variables, definite loops, infinite loops, and indefinite loops.
  • Next topic: Nested loops.