6.6 Constructing Loop Conditions

Constructing the correct loop condition may seem a little counterintuitive. The loop executes as long as the loop condition evaluates to true. Thus, if we want our loop to terminate when we read the sentinel value, then the loop condition should check that the input value is not the sentinel value. In other words, the loop continuation condition is the inverse of the loop termination condition. For a simple sentinel-controlled loop, the condition normally follows this pattern:

while ( inputValue != sentinel )

In fact, we can see that the loop conditions in many of the examples in this chapter use this form of while loop condition.

For some applications, there may be multiple sentinel values. For example, suppose ...

Get Java Illuminated, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.