...

/

Sentinel Loops

Sentinel Loops

Learn and practice loops controlled by a sentinel value.

The sentinel value

Sometimes, the loop doesn’t have a fixed number of repetitions. Instead, an indicator value stops the loop. This special value is called the sentinel value. For example, we don’t know how much data is in a file without reading it all. However, we know that every file ends with an end-of-file (EOF) mark. So, the EOF mark is the sentinel value in this case.

Note: We should select a sentinel value that’s not expected in the normal input.

The while loop

We use the while loop when the termination of the loop depends on the sentinel value instead of a definite number of iterations. As a simple example, we want to display the reverse sequence of digits in a positive integer value input by the user.

Remember: For some programs, once you run the program, it will require your input to execute. A pop-up box will appear to type the input in that box first to get the desired results. You must type the inputs one after the other for more than one input.

In the program above:

  • In ...