🔄

Lecture on Loop Control Variables

May 23, 2024

Program and Logic Design

Topic: Loop Control Variables

Definition

  • Loop Control Variable: Helps maintain a condition to stay true so statements in the loop body execute repeatedly.
  • Controls the number of repetitions of a loop.

Steps to Use a Loop Control Variable

  1. Initialize the loop control variable before entering the loop.
  2. Test the loop control variable in the condition of the loop.
  3. Alter the value of the loop control variable within the loop body.

Types of Loops

  • Definite Loop: Executes for a predetermined number of times.
  • Indefinite Loop (Sentinel Value): User decides how many times the loop will execute.

Common Issues

  • Infinite Loop: Occurs when a loop does not have an end, making the program lag. Avoid by properly initializing, testing, and altering the loop control variable.

Definite Loop

  • Counter-Controlled Loop: Counts loop repetitions, hence a definite number of executions.
  • Example: Loop that prints "Hello" 4 times.
    • Initialize count to 0.
    • Check if count < 4 (increments by 1 each time).
    • Print "Hello" until the condition becomes false.

Indefinite Loop

  • Uses a Sentinel Value: Loops a different number of times based on user interaction.
  • Example: Asking user if they want to continue printing "Hello" until they input 'n' to stop.

Steps in a Properly Functioning Loop

  1. Starting Value: Initialize a value for the loop control variable.
    • If starting at 0 to print "Hello" 4 times, the end condition should be count < 4.
  2. Test Condition: Determines repetition count of the loop body.
  3. Alter Control Variable: Changes during each loop iteration to help in testing.

Example: Indefinite Loop in a Payroll Program

  • Sentinel Value: User inputs a name. The loop continues until the user types 'XXX'.
  • Flow: Initialize name, print headings, input new name repeatedly until 'XXX' is entered to quit.

Next Topic: Discussing nested loops