CHTP5e 04-Program Control
CHTP5e 04-Program Control
4
C Program
Control
2
OBJECTIVES
In this chapter you will learn:
The essentials of counter-controlled repetition.
To use the for and do...while repetition statements to
execute statements in a program repeatedly.
To understand multiple selection using the switch
selection statement.
To use the break and continue program control statements
to alter the flow of control.
To use the logical operators to form complex conditional
expressions in control statements.
To avoid the consequences of confusing the equality and
assignment operators.
3
4.1 Introduction
4.2 Repetition Essentials
4.3 Counter-Controlled Repetition
4.4 for Repetition Statement
4.5 for Statement: Notes and Observations
4.6 Examples Using the for Statement
4.7 switch Multiple-Selection Statement
4.8 do...while Repetition Statement
4.9 break and continue Statements
4.10 Logical Operators
4.11 Confusing Equality (==) and Assignment (=) Operators
4.12 Structured Programming Summary
4
4.1 Introduction
This chapter introduces
– Additional repetition control structures
- for
- do…while
– switch multiple selection statement
– break statement
- Used for exiting immediately and rapidly from certain
control structures
– continue statement
- Used for skipping the remainder of the body of a repetition
structure and proceeding with the next iteration of the loop
5
1
2
3
4
5
6
7
8
9
10
9
Sum is 2550
24
Portability Tip
Error-Prevention Tip
1 2 3 4 5 6 7 8 9 10
44
1 2 3 4
Broke out of loop at x == 5
47
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
49
Performance Tip
The break and continue statements,
when used properly, perform faster than the
corresponding structured techniques that we
will soon learn.
50
0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1
0 0 0
0 nonzero 1
nonzero 0 1
nonzero nonzero 1
expression !expression
0 1
nonzero 0
Performance Tip
Structured programming
– Easier than unstructured programs to understand, test,
debug and, modify programs
64
Fig. 4.20 | Repeatedly applying rule 2 of Fig. 4.18 to the simplest flowchart.
67