Skip to content
๐Ÿ” Loop Control โ€” Sentinel vs Counter

๐Ÿ” Loop Control โ€” Sentinel vs Counter

๐Ÿ›‘ Sentinel-Controlled Loop

Used when the number of iterations is unknown. Loop continues until a special value (sentinel) is encountered.

sentinel = -999
total = 0

num = int(input("Enter a number (-999 to stop): "))
while num != sentinel:
    total += num
    num = int(input("Enter a number (-999 to stop): "))

print("Total sum:", total)

๐Ÿ” Termination is data-driven, not count-driven.


๐Ÿ”ข Counter-Controlled Loop

Used when the number of iterations is known in advance. Loop runs a fixed number of times.

total = 0

for i in range(5):
    num = int(input(f"Enter number {i+1}: "))
    total += num

print("Total sum:", total)

๐Ÿ” Termination is count-driven, not data-triggered.


๐Ÿง  Semantic Summary

FeatureSentinel-ControlledCounter-Controlled
Termination TriggerSpecial value (e.g., -999)Fixed iteration count (e.g., 5)
PredictabilityโŒ Unknownโœ… Known
Use CaseStream/input processingStructured iteration
RiskSentinel misplacementOff-by-one errors

๐Ÿงฉ Use sentinel loops for indefinite repetition, and counter loops for bounded iteration. Document clearly to avoid semantic drift.

Last updated on