Skip to main content

Section 8.6 Sentinel Loops

A second common pattern for designing a loop (after the counting loop) is the sentinel loop. It is used when we don’t know how many times we will need to repeat a task, but we do know when to stop. In this strategy, the loop continues until a special value is encountered, called the sentinel. (A sentinel is someone who stands guard.)
Here is a program that keeps reading in numbers until it encounters 0. The program does not know, or care, how many numbers it is going to get. So it isn’t really β€œcounting”, it is just continuing until it hits the sentinel value 0.
Listing 8.6.1.
Notice that the loop variable update - where we read in the next value for number - separates the body of the loop into two parts. The part above the update where we are using the current value of the variable, and the part after where we are using the β€œnext” value.
Sometimes, the sentinel is a bool value or function call that returns a bool as the sentinel. Loops like this are very common:
while ( !atEndOfFile() ) {
  // read a line and process it
}
Here, the atEndOfFile function returns true or false and is serving as our sentinel. As long as there are more lines, atEndOfFile() will be false. That means !atEndOfFile() will be true and the loop executes again.
It is important to make sure that the loop eventually reaches the sentinel condition to avoid infinite loops. If our loop control variable might skip past the sentinel value, the loop may never terminate. The program below has this kind of bug. It keep multiplying the loop control variable by 2 and tries to stop when we reach 1000.
Listing 8.6.2.
If you run the program, it will enter an infinite loop because the value of number will never be exactly 1000. It will go from 512 to 1024 without ever equaling 1000. To fix this, we would need to rewrite the condition as something like number < 1000. That way, reaching 1000 will stop the loop, even if we blow right past the sentinel value.

Checkpoint 8.6.1.

Help Goku reach power levels of over 9000! Write the function powerUp which takes powerLevel as a parameter. powerUp checks to see if powerLevel is over 9000. If it isn’t, it repeatedly prints β€œMore power!” and increments powerLevel by 1000 until powerLevel is over 9000. Then powerUp prints β€œIt’s over 9000!”. Put the necessary blocks in the correct order.
You have attempted of activities on this page.