1
6-5 Loops in C
C has three loop statements: the C has three loop statements: the whilewhile, the , the forfor, and the , and the
do…whiledo…while. The first two are pretest loops, and the. The first two are pretest loops, and the
the third is a post-test loop. We can use all of themthe third is a post-test loop. We can use all of them
for event-controlled and counter-controlled loops.for event-controlled and counter-controlled loops.
The while Loop
The for Loop
The do…while Loop
The Comma Expression
Topics discussed in this section:Topics discussed in this section:
2
FIGURE 6-9 C Loop Constructs
3
FIGURE 6-10 The while Statement
4
FIGURE 6-11 Compound while Statement
5
PROGRAM 6-1Process-control System Example
6
PROGRAM 6-2A while Loop to Print Numbers
7
PROGRAM 6-2A while Loop to Print Numbers
8
PROGRAM 6-3Adding a List of Numbers
9
PROGRAM 6-3Adding a List of Numbers
10
A for loop is used when a loop is to be executed a known
number of times. We can do the same thing with a while
loop, but the for loop is easier to read and
more natural for counting loops.
NoteNote