The For Statement
2. Fundamental Loops
type description counting loop
Uses a loop control variable to count upwards or downwards (usually by an integer increment.)
Loop keeps going until a special value is encountered in the data.
Loop keeps going until a test determines that the desired result has been achieved.
Each type of loop can be built using the
with other statements. There are three things (in every type of loop) that must be done correctly:
- The loop must be initialized.
- A condition must be tested.
- The loop body must change something that is tested.
Overlooking one of these aspects results in a defective loop. But usually each of these aspects is found in a different place in a program. No wonder that loops often go wrong!
The flow chart to the right shows what all loops must do. It could be for any of the three types of loops. The ellipses (. . . .) shows where the loop body does additional computation.
Would it be convenient to have all three aspects combined into one statement?