I l @ ve RuBoard |
When you decide you need a loop, which one should you use? First, decide whether you need an entry-condition loop or an exit-condition loop. Your answer should usually be an entry-condition loop. There are several reasons computer scientists consider an entry-condition loop superior . One is the general principle that it is better to look before you leap (or loop) than after. A second is that a program is easier to read if the loop test is found at the beginning of the loop. Finally, in many uses, it is important that the loop be skipped entirely if the test is not initially met.
Assume you need an entry-condition loop. Should it be a for or a while ? This is partly a matter of taste, because what you can do with one, you can do with the other. To make a for loop like a while , you can omit the first and third expressions. For example,
for ( ;test; )
is the same as
while (test)
To make a while like a for , preface it with an initialization and include update statements. For example,
initialize; while (test) {; body; update; }
is the same as
for (initialize; test; update) body;
In terms of style, a for loop is appropriate when the loop involves initializing and updating a variable, and a while loop is better when the conditions are otherwise . A while loop is natural for the following condition:
while (scanf("%ld", #) == 1)
The for loop is a more natural choice for loops involving counting with an index:
for (count = 1; count <= 100; count++)
I l @ ve RuBoard |