C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

body of the while.


Warning

The two statements in Figure 14.1 are similar, but they don’t do the same thing. while
and if are two separate statements that do two separate things.

You must somehow change a variable inside the while loop’s condition. If you don’t, the
while will loop forever because it will test the same condition each time through the loop.
Therefore, you avoid infinite loops by making sure the body of the while loop changes something in
the condition so that eventually the condition becomes false and the program continues with
the statements that follow the while loop.


FIGURE 14.1 The if body executes once; the while body can repeat more than once.

Note

As with if, the while might never execute! If the condition is false going into
while the first time, the body of the while doesn’t execute.

Using while


If you want to repeat a section of code until a certain condition becomes false, while is the way to
go. Let’s revisit the counter up and down program for a fourth go-round and use while loops this
time:


Click here to view code image

Free download pdf