type | description |
---|---|
counting loop | Increment a counter after each value is read. Stop when the correct number of values have been read. |
sentinel-controlled loop | Read in values until reading a special value. |
result-controlled loop | Read in values until a desired result has been achieved. |
The three types of loops are used for I/O processing, as in the table. Input from a file is usually done inside a loop that looks like this:
while ( ..... ) { data = scan.nextInt(); ..... }
This is an ordinary loop with an input statement in its body. Depending on how it is implemented, it can be any of the three types of loops. The table shows how the three types of loops are used for input loops. The first two types are the most common.
Here is a typical file input problem:
The first integer in a text file says how many integers follow it. Add up all integers in the file except the first.
What type of loop is used for this?