1
6-5 Loops in C
C has three loop statements: the
C has three loop statements: the while
while, the
, the for
for, and the
, and the
do…while
do…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 them
the 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-1 Process-control System Example
6
PROGRAM 6-2 A while Loop to Print Numbers
7
PROGRAM 6-2 A while Loop to Print Numbers
8
PROGRAM 6-3 Adding a List of Numbers
9
PROGRAM 6-3 Adding 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.
Note
Note
11
FIGURE 6-14 Comparing for and while Loops
12
PROGRAM 6-4 Example of a for Loop
13
PROGRAM 6-4 Example of a for Loop
14
PROGRAM 6-5 A Simple Nested for Loop
15
PROGRAM 6-5 A Simple Nested for Loop
16
FIGURE 6-15 do…while Statement
17
PROGRAM 6-6 Two Simple Loops
18
PROGRAM 6-6 Two Simple Loops
19
FIGURE 6-16 Pre- and Post-test Loops
20
PROGRAM 6-7 Adding a List with the do…while
21
PROGRAM 6-7 Adding a List with the do…while
22
FIGURE 6-17 Nested Comma Expression
23
PROGRAM 6-8 Comparison of while and do…while
24
PROGRAM 6-8 Comparison of while and do…while

how to use loops in c(for,while and do while).ppt