Sentinel Logic

Sentinel Logic
Assumes while loops and input statements
Sentinel Logic – uses an indefinite loop
• The for loop is a definite loop – you know how many times it needs to
• There are many situations in life / programming where you do not
know this information (how many times it needs to execute)
• The while loop (indefinite loop) is made for this kind of situation.
• Example: “The loop executes until a sensor gives a value out of range”
• Example: “The user plays a game until they get tired.”
• Example: “The user inputs a value which must be either Y or N,
nothing else.”
A pattern
• A pattern of statements called “sentinel logic” handles this kind of
problem as cleanly as it can be done.
• A sentinel is an indicator that the loop can stop executing, that the data is
used up. It can be a special number (-1, 0, 9999), a string (“stop”), or it can be
a condition (keep looping while sensor > 0 and sensor < 50)
• Pattern
• Input the first data value to be processed
• While the data value is not the sentinel
• Process the data value
• Input the next data value to be processed