LtrinhC-Chap4
LtrinhC-Chap4
4
C Program
Control
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.
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.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
1
2
3
4
5
6
7
8
9
10
Sum is 2550
1 2 3 4 5 6 7 8 9 10
1 2 3 4
Broke out of loop at x == 5
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1
Fig. 4.13 | Truth table for the && (logical AND) operator.
0 0 0
0 nonzero 1
nonzero 0 1
nonzero nonzero 1
expression !expression
0 1
nonzero 0
rvalues
– Expressions that can only appear on the right side of an equation
– Constants, such as numbers
- Cannot write 4 = x;
- Must write x = 4;
– lvalues can be used as rvalues, but not vice versa
- y = x;
Structured programming
– Easier than unstructured programs to understand, test,
debug and, modify programs
Fig. 4.20 | Repeatedly applying rule 2 of Fig. 4.18 to the simplest flowchart.