The syntax of the while statement is as follows:
while (expression) statement
After the statement block has been processed, the expression is evaluated again. If it’s still true, the statement block is executed again. This process is repeated until the expression evaluates to false.
When you’re creating while statements, you must be sure to add code within the executed statement block that will eventually turn the expression that’s controlling the while statement false. If you don’t do this, you’ll probably create an infinite loop. Once the execution of an infinite loop starts, it’ll never terminate and go round and round forever until the application or computer is shut down, usually because it has run out of resources. This is one of the easiest kinds of programming mistakes to make and can be frustrating, so watch out for it.
Do It Right!—To Create a While Statement That Counts Down from 10 to 1:
|Try This at Home|| |
As with conditional statements, it’s always a good practice to build the scaffolding of a loop before you start populating it with actual statements and expressions.
|Do It Right!|| |
So-called “one-off” errors—in which a loop counter is off by one—are one of the most common and pesky programming bugs. Make sure you haven’t introduced one-off bugs into your loops by testing “boundary” values of your counter variables—typically those one greater than and one less than the value at which the expression is supposed to fail. For example, in the program shown in Listing 4-2, if you changed the condition to (counter > = 0), you’d get a countdown to zero instead of one. That’s fine if it’s what you want, but not otherwise. The point is, the difference can be confusing, and you should be sure to “dial up” the precise condition that’s necessary to make your program work right.
Generally, the expression that’s being evaluated can be written in many ways that are logically equivalent. For example, asking if the counter is greater than zero (counter > 0) is equivalent to asking if the counter is not less than one (!(counter < 1)).
That said, it’s best if you create the expression that’s used by a while statement as simple and unconvoluted as possible. The easier it is to understand, the less likely you are to make a mistake.