AP® Computer Science A · Unit 2 · Topic 2.7
Sentinel Loops and Reading Until a Signal
A sentinel loop keeps reading input until it sees a special stop value, called the sentinel, instead of running a fixed number of times. The sentinel itself is never treated as real data.
Some loops can't know in advance how many times they'll run. You don't know how many numbers a user wants to sum, or how many lines are left in a file. A sentinel loop solves this by watching for a special value that means stop, rather than counting up to some fixed limit. The loop reads a value, checks whether it's the sentinel, and only processes it as real data if it isn't.
The mechanism depends on checking before acting. Each pass reads an input, tests it against the sentinel, and only then decides whether to use it or quit. That order matters: if you added the value first and checked second, the sentinel would sneak into your results. This is why many sentinel loops read one value before the loop even starts (a priming read), so the condition has something to test the very first time it's checked.
Sentinel loops connect directly to indefinite iteration with while loops, since the number of passes depends entirely on when the sentinel shows up, not on a counter. They also sit next to boolean conditions from earlier in the unit: the loop's condition is just checking equality against one specific value. The catch worth carrying forward is validity of choice. A sentinel only works if it's a value that could never appear as genuine data. Pick one that overlaps with real input, and the loop will stop too early and throw away data silently, no error, no warning.
Key terms
- sentinel value
- A special input value that signals a loop to stop, chosen because it can't be confused with real data.
- priming read
- An initial read of input performed before a sentinel loop begins, so the loop's condition has a value to check immediately.
- indefinite iteration
- Looping where the number of passes isn't fixed in advance but depends on a condition evaluated each time.
- running total
- A variable that accumulates a sum across multiple loop passes, updated only when the current value isn't the sentinel.
Watch it explained
- How it worksHow does a sentinel value act as a stop sign the loop watches for on every pass?
- Worked exampleTrace a loop that sums numbers until -1 is entered, given the inputs 4, 9, 2, -1.
- Common mistakeWhy doesn't the sentinel value itself belong in the running total?
- Going furtherWhat changes when the sentinel could legitimately turn up inside the real data?
Check yourself
End of topic.