Control Structures: Repetition in Algorithms

Mithat Konar
2019-02-11

Introduction

  • Counter control
  • Sentinel/flag control
  • Input validation
  • Menus
  • Iterators

Counter-controlled repetition

  • “Repeat something a known number of times.”
  • Uses a counter variable.
  • Pseudocode:
    Set counter's initial value
    While counter has not yet exceeded the STOP_VALUE
        Do something
        Increment counter

Sentinel control

  • Sentinel:
    • Value(s) that indicate(s) a special condition — a “special value”

Sentinel-controlled repetition

  • “Repeat as long as a sentinel condition is not matched.”
  • Pseudocode:
    Get value
    While value is not SENTINEL value
        Do something
        Get value
  • Input validation might be considered a special case of sentinel controlled repetition.
  • Flag:
    • Sometimes used as a synonym for sentinel
    • Sometimes means a sentinel that is a Boolean value

Input validation

  • “Prevent moving to next section until user has entered valid data.”
  • Pseudocode:
    Get input value from user
    While input value is not valid
        Get input value from user

Menus

  • Repeating menus can be implemented with sentinel control.
  • Pseudocode:
    Show menu
    Get menu choice from user
    While input value is not QUIT value
        Process the menu choice
        Show menu
        Get menu choice from user

Iterators

  • Do something to every item in a collection.
  • Pseudocode:
    For each item in collection
        Do something with or to the item