Sentinel Loops

 Consider the following problem. You want to read in data values and process them as long as they are nonzero. At the first data value which is zero, you will stop. The zero tells the program that there are no more data values and serves as a sentinel.

What sort of things do we want to do in our loop?

  1. Read a data value.
  2. If the data value is positive process it.

Clearly we must read at least one data value. But we may not have to process any data values. If the first data value is zero, then nothing will be processed. Since the do loop has one-trip behavior, we would need to use an if statement inside to avoid processing the zero data. The traditional way to handle this problem is to use a while loop with the operations that must be done at least once performed before the loop and inside the loop.

   a. Display a prompt for data;
   b. Input data;
   c. Loop (pretest), so long as data is not the sentinel:
      1) Process data.
      2) Display a prompt for data;
      3) Input data; 
   End loop.

By performing steps a and b outside of the loop, we ensure they are executed at least once. By performing steps 1 , 2, and 3 inside the pretest loop, they will be executed zero times, if the user enters a valid value in step b.

The drawback to this approach is its redundance: steps 2 and 3 are exactly the same as steps a and b. This is not too much of an inefficiency, so long as one does not mind the extra typing. In the final part of this exercise, we will see a way to avoid this redundancy.


Back to the Exercise

Back to This Lab's Table of Contents

Back to the Table of Contents

Back to the Introduction

Copyright 2000 by Prentice Hall. All rights reserved.