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.
Codelens doesnโt handle input, so we are printing out information inside the loop about what is going on. This can be a useful way to debug loops even if you have a debugger that you can use to step through the code. It can be useful to see all the iterations of a loop at once so you can track patterns in what happens from one iteration to the next. Here, each iteration starts by printing --------------, and then updates us about what each line did.
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.
Later on, we will often see this strategy implemented with 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.
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.