DEV Community

Cover image for Which Loop to Use?
Paul Ngugi
Paul Ngugi

Posted on

Which Loop to Use?

You can use a for loop, a while loop, or a do-while loop, whichever is convenient. The while loop and for loop are called pretest loops because the continuation condition is checked before the loop body is executed. The do-while loop is called a posttest loop because the condition is checked after the loop body is executed. The three forms of loop statements—while, do-while, and for—are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the for loop in (b).

Image description

A for loop in (a) in the next figure can generally be converted into the while loop in (b) except in certain special cases.

Image description

Use the loop statement that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known in advance, as, for example, when you need to display a message a hundred times. A while loop may be used if the number of repetitions is not fixed, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before the continuation condition is tested.

Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below in (a). In (a), the semicolon signifies the end of the loop prematurely. The loop body is actually empty, as shown in (b). (a) and (b) are equivalent. Both are incorrect.

Image description

Similarly, the loop in (c) is also wrong. (c) is equivalent to (d). Both are incorrect.

Image description

These errors often occur when you use the next-line block style. Using the end-of-line block style can avoid errors of this type.
In the case of the do-while loop, the semicolon is needed to end the loop.

Image description

Top comments (0)