type description counting loop Uses a loop control variable to count upwards or downwards
(usually by an integer increment).sentinel-controlled loop Loop keeps going until a special value is encountered in the data. result-controlled loop Loop keeps going until a test determines that the desired result has been achieved.
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.
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 reaching a special value. |
result-controlled loop | Read in values until a desired result has been achieved. |
Here is a typical file input problem:
Write a program to add up all the integers in a file except for the first integer in the file which says how many integers follow.
What type of loop is used for this?