Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

ch04_notes

Chapter 4 of 'C++ How to Program' covers control statements, including for, do...while, and switch statements, as well as break and continue statements. It details the structure and usage of counter-controlled repetition, logical operators, and common pitfalls in C++ programming. The chapter also provides examples and explanations of how to implement these control structures effectively.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

ch04_notes

Chapter 4 of 'C++ How to Program' covers control statements, including for, do...while, and switch statements, as well as break and continue statements. It details the structure and usage of counter-controlled repetition, logical operators, and common pitfalls in C++ programming. The chapter also provides examples and explanations of how to implement these control structures effectively.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

2023/3/13

Chapter 4,
Control Statements:
Part 2
C++ How to Program,
Late Objects Version, 7/e

©1992-2011 by Pearson Education, Inc. All Rights Reserved.

1 2

4.1 Introduction
for, do…while and switch statements.
counter-controlled repetition.
Introduce the break and continue program control
statements.
Logical operators for more powerful conditional
expressions.
Examine the common error of confusing the equality
(==) and assignment (=) operators, and how to avoid
it.
Summarize C++’s control statements.

3 4

4.2 Essentials of Counter-Controlled


Repetition
Counter-controlled repetition requires
◦ the name of a control variable (or loop counter)
◦ the initial value of the control variable
◦ the loop-continuation condition that tests for the final value of
the control variable (i.e., whether looping should continue)
◦ the increment (or decrement) by which the control variable is
modified each time through the loop.
In C++, it’s more precise to call a declaration that also
reserves memory a definition.

5 6

1
2023/3/13

4.3 for Repetition Statement


The for repetition statement specifies the counter-
controlled repetition details in a single line of code.
The initialization occurs once when the loop is encountered.
The condition is tested next and each time the body
completes.
The body executes if the condition is true.
The increment occurs after the body executes.
Then, the condition is tested again.
If there is more than one statement in the body of the for,
braces are required to enclose the body of the loop.

7 8

4.3 for Repetition Statement (cont.)


The general form of the for statement is
● for ( initialization; loopContinuationCondition; increment )
statement
where the initialization expression initializes the loop’s control
variable, loopContinuationCondition determines whether the
loop should continue executing and increment increments the
control variable.
In most cases, the for statement can be represented by an
equivalent while statement, as follows:
● initialization;
while ( loopContinuationCondition )
{
statement
increment;
}

9 10

4.3 for Repetition Statement (cont.) 4.3 for Repetition Statement (cont.)
If the initialization expression declares the control The initialization and increment expressions can be
variable, the control variable can be used only in the comma-separated lists of expressions.
body of the for statement—the control variable will be The commas, as used in these expressions, are comma
unknown outside the for statement. operators, which guarantee that lists of expressions
This restricted use of the control variable name is evaluate from left to right.
known as the variable’s scope. ◦ The lowest precedence of all C++ operators.
The scope of a variable specifies where it can be used The value and type of a comma-separated list of
in a program. expressions is the value and type of the rightmost
expression.

11 12

2
2023/3/13

4.3 for Repetition Statement (cont.) 4.3 for Repetition Statement (cont.)
The three expressions in the for statement header are The increment expression in the for statement acts as a
optional (but the two semicolon separators are standalone statement at the end of the body of the for.
required). The expressions
If the loopContinuationCondition is omitted, C++ ● counter = counter + 1
assumes that the condition is true, thus creating an counter += 1
infinite loop. ++counter
One might omit the initialization expression if the counter++
control variable is initialized earlier in the program. are all equivalent in the incrementing portion of the for
One might omit the increment expression if the statement’s header (when no other code appears there).
increment is calculated by statements in the body of the
for or if no increment is needed.

13 14

4.3 for Repetition Statement (cont.) 4.3 for Repetition Statement (cont.)
The initialization, loop-continuation condition and The for repetition statement’s UML activity diagram is
increment expressions of a for statement can contain similar to that of the while statement (Fig. 4.6).
arithmetic expressions. Figure 4.4 shows the activity diagram of the for
The “increment” of a for statement can be negative, in statement in Fig. 4.2.
which case the loop actually counts downward. The diagram makes it clear that initialization occurs
If the loop-continuation condition is initially false, the once before the loop-continuation test is evaluated the
body of the for statement is not performed. first time, and that incrementing occurs each time
through the loop after the body statement executes.

15 16

4.4 Examples Using the for Statement


Vary the control variable from 1 to 100 in increments of 1.
● for ( int i = 1; i <= 100; i++ )
Vary the control variable from 100 down to 1 in decrements of
1.
● for ( int i = 100; i >= 1; i-- )
Vary the control variable from 7 to 77 in steps of 7.
● for ( int i = 7; i <= 77; i += 7 )
Vary the control variable from 20 down to 2 in steps of -2.
● for ( int i = 20; i >= 2; i -= 2 )
Vary the control variable over the following sequence of values:
2, 5, 8, 11, 14, 17.
● for ( int i = 2; i <= 17; i += 3 )
Vary the control variable over the following sequence of values:
99, 88, 77, 66, 55.
● for ( int i = 99; i >= 55; i -= 11 )

17 18

3
2023/3/13

4.4 Examples Using the for Statement


(cont.)
The program of Fig. 4.5 uses a for statement to sum the
even integers from 2 to 20.

19 20

4.4 Examples Using the for Statement


(cont.)
Consider the following problem statement:
◦ A person invests $1000.00 in a savings account yielding 5 percent
interest. Assuming that all interest is left on deposit in the account,
calculate and print the amount of money in the account at the end of
each year for 10 years. Use the following formula for determining
these amounts:
a = p ( 1 + r )n
where
p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year.
◦ This problem involves a loop that performs the indicated calculation
for each of the 10 years the money remains on deposit.

21 22

4.4 Examples Using the for Statement


(cont.)
C++ does not include an exponentiation opera-tor, so
we use the standard library function pow.
◦ pow(x, y) calculates the value of x raised to the yth power.
◦ Takes two arguments of type double and returns a double
value.
This program will not compile without including
header file <cmath>.
◦ Includes information that tells the compiler to convert the
value of year to a temporary double representation before
calling the function.
◦ Contained in pow’s function prototype.

23 24

4
2023/3/13

4.4 Examples Using the for Statement 4.4 Examples Using the for Statement
(cont.) (cont.)
Parameterized stream manipulators setprecision- and Stream manipulator fixed indicates that floating-point
setw and the nonparameterized stream manipulator fixed.
The stream manipulator setw(4) specifies that the next values should be output as fixed-point values with
value output should appear in a field width of 4—i.e., cout decimal points.
prints the value with at least 4 character positions. Stream manipulator setprecision specifies the number
◦ If less than 4 character positions wide, the value is right justified in
the field by default. of digits to the right of the decimal point.
◦ If more than 4 character positions wide, the field width is extended
to accom-modate the entire value. Stream manipulators fixed and setprecision remain in
To indicate that values should be output left justified, effect until they’re changed—such settings are called
simply output nonparameterized stream manipulator left . sticky settings.
Right justification can be restored by outputting
The field width specified with setw applies only to the
nonparameterized stream manipulator right.
next value output.

25 26

4.5 do…while Repetition Statement


Similar to the while statement.
The do…while statement tests the loop-continuation
con-dition after the loop body executes; therefore, the
loop body always executes at least once.
It’s not necessary to use braces in the do…while
statement if there is only one statement in the body.
◦ Most programmers include the braces to avoid confusion
between the while and do…while statements.
Must end a do…while statement with a semicolon.

27 28

4.5 do…while Repetition Statement


Figure 4.8 contains the do…while statement’s UML
activity diagram, which makes it clear that the loop-
continuation condition is not evaluated until after the
loop performs its body at least once.

29 30

5
2023/3/13

4.6 switch Multiple-Selection Statement

The switch multiple-selection statement performs


many different actions based on the possible values of a
variable or expression.
Each action is associated with the value of a constant
integral expression (i.e., any combination of character
and integer constants that evaluates to a constant
integer value).

31 32

33 34

35 36

6
2023/3/13

4.6 switch Multiple-Selection Statement 4.6 switch Multiple-Selection Statement


(cont.) (cont.)
The cin.get() function reads one character from the keyboard. Generally, assignment statements have the value that is
Normally, characters are stored in variables of type char; however,
characters can be stored in any integer data type, because types short, assigned to the variable on the left side of the =.
int and long are guaranteed to be at least as big as type char.
Can treat a character either as an integer or as a character, depending EOF stands for “end-of-file”. Commonly used as a
on its use. sentinel value.
For example, the stat-ment
● cout << "The character (" << 'a' << ") has the value "
◦ However, you do not type the value –1, nor do you type the
<< static_cast< int > ( 'a' ) << endl; letters EOF as the sentinel value.
prints the character a and its integer value as follows: ◦ You type a system-dependent keystroke combination that
● The character (a) has the value 97
The integer 97 is the character’s numerical representation in the means “end-of-file” to indicate that you have no more data to
computer. enter.
EOF is a symbolic integer constant defined in the
<iostream> header file.

37 38

4.6 switch Multiple-Selection Statement 4.6 switch Multiple-Selection Statement


(cont.) (cont.)
The switch statement consists of a series of case Listing cases consecutively with no statements between
labels and an optional default case. them enables the cases to perform the same set of
When the flow of control reaches the switch, the statements.
program evaluates the expression in the parentheses. Each case can have multiple statements.
◦ The switch selection statement does not require braces around
◦ The controlling expression.
multiple statements in each case.
The switch statement compares the value of the Without break statements, each time a match occurs in the
controlling expression with each case label. switch, the statements for that case and subsequent cases
If a match occurs, the program executes the statements execute until a break statement or the end of the switch is
for that case. encountered.
The break statement causes program control to proceed ◦ Referred to as “falling through” to the statements in subsequent
cases.
with the first statement af-ter the switch.

39 40

4.6 switch Multiple-Selection Statement 4.6 switch Multiple-Selection Statement


(cont.) (cont.)
If no match occurs between the controlling Reading characters one at a time can cause some
expression’s value and a case label, the default case problems.
executes. To have the program read the characters, we must send
If no match occurs in a switch statement that does not them to the computer by pressing the Enter key.
contain a default case, program control continues with This places a newline character in the input after the
the first statement after the switch. character we wish to process.
Often, this newline character must be specially
processed.

41 42

7
2023/3/13

4.6 switch Multiple-Selection Statement


(cont.)
Figure 4.12 shows the UML activity diagram for the general
switch multiple-selection statement.
Most switch statements use a break in each case to terminate
the switch statement after processing the case.
Figure 4.12 emphasizes this by including break statements in the
activity diagram.
Without the break statement, control would not transfer to the
first statement after the switch statement after a case is
processed.
Instead, control would transfer to the next case’s actions.
The diagram makes it clear that the break statement at the end of
a case causes control to exit the switch statement immediately.

43 44

4.6 switch Multiple-Selection Statement 4.6 switch Multiple-Selection Statement


(cont.) (cont.)
C++ has flexible data type sizes (see Appendix C, Fundamental On most computers, ints are equivalent either to short
Types).
C++ provides several integer types. or to long.
The range of integer values for each type depends on the The range of values for an int is at least the same as
particular computer’s hardware.
In addition to the types int and char, C++ provides the types that for short integers and no larger than that for long
short (an abbreviation of short int) and long (an abbreviation of integers.
long int).
The data type char can be used to represent any of the
The minimum range of values for short integers is –32,768 to
32,767. characters in the computer’s character set.
For the vast majority of integer calculations, long integers are It also can be used to represent small integers.
sufficient.
The minimum range of values for long integers is –
2,147,483,648 to 2,147,483,647.

45 46

4.7 break and continue Statements

The break statement, when executed in a while, for,


do…while or switch statement, causes immediate exit
from that statement.
Program execution continues with the next statement.
Common uses of the break statement are to escape
early from a loop or to skip the remainder of a switch
statement.

47 48

8
2023/3/13

4.7 break and continue Statements


(cont.)
The continue statement, when executed in a while,
for or do…while statement, skips the remaining
statements in the body of that statement and proceeds
with the next iteration of the loop.
In while and do…while statements, the loop-
continuation test evaluates immediately after the
continue statement executes.
In the for statement, the increment expression executes,
then the loop-continuation test evaluates.

49 50

4.8 Logical Operators 4.8 Logical Operators (cont.)


C++ provides logical operators that are used to form The && (logical AND) operator is used to ensure that
more complex conditions by combining simple two conditions are both true before we choose a certain
conditions. path of execution.
The logical operators are && (logical AND), || (logical The simple condition to the left of the && operator
OR) and ! (logical NOT, also called logical negation). evaluates first.
If necessary, the simple condition to the right of the
&& operator evaluates next.
The right side of a logical AND expression is evaluated
only if the left side is true.

51 52

4.8 Logical Operators (cont.)


Figure 4.15 summarizes the && operator.
The table shows all four possible combinations of false
and true values for expression1 and expression2.
Such tables are often called truth tables.
C++ evaluates to false or true all expressions that in-
clude relational operators, equality operators and/or
logical operators.

53 54

9
2023/3/13

4.8 Logical Operators (cont.)


The || (logical OR) operator determines if either or both of
two conditions are true before we choose a certain path of
execution.
Figure 4.16 is a truth table for the logical OR operator (||).
The && operator has a higher precedence than the ||
operator.
Both operators associate from left to right.
An expression containing && or || operators evaluates only
until the truth or falsehood of the expression is known.
◦ This performance feature for the evaluation of logical AND and
logical OR expressions is called short-circuit evaluation.

55 56

4.8 Logical Operators (cont.)


C++ provides the ! (logical NOT, also called logical
negation) operator to “reverse” a condition’s meaning.
The unary logical negation operator has only a single
condition as an operand.
You can often avoid the ! operator by using an
appropriate relational or equality operator.
Figure 4.17 is a truth table for the logical negation
operator (!).

57 58

4.8 Logical Operators (cont.)


Figure 4.18 demonstrates the logical operators by
producing their truth tables.
The output shows each expression that is evaluated and
its bool result.
By default, bool values true and false are displayed by
cout and the stream insertion operator as 1 and 0,
respectively.
Stream manipulator boolalpha (a sticky manipulator)
specifies that the value of each bool expression should
be displayed as either the word “true” or the word
“false.”

59 60

10
2023/3/13

61 62

4.9 Confusing the Equality (==) and 4.9 Confusing the Equality (==) and
Assignment (=) Operators Assignment (=) Operators (cont.)
Accidentally swapping the operators == (equality) and = Variable names are said to be lvalues (for “left values”)
(assignment).
Damaging because they ordinarily do not cause syntax errors. because they can be used on the left side of an
Rather, statements with these errors tend to compile correctly and assignment operator.
the programs run to completion, often generating incorrect
results through runtime logic errors. Constants are said to be rvalues (for “right values”)
[Note: Some compilers issue a warning when = is used in a because they can be used on only the right side of an
context where == typically is expected.] assignment operator.
Two aspects of C++ contribute to these problems.
◦ One is that any expression that produces a value can be used in the Lvalues can also be used as rvalues, but not vice versa.
decision portion of any control statement.
◦ The second is that assignments produce a value—namely, the value
assigned to the variable on the left side of the assignment operator.
Any nonzero value is interpreted as true

63 64

4.10 Structured Programming Summary

We’ve learned that structured programming produces


programs that are easier than unstructured programs to
understand, test, debug, modify, and even prove correct
in a mathematical sense.
Figure 4.20 uses activity diagrams to summarize C++’s
control statements.
The initial and final states indicate the single entry
point and the single exit point of each control
statement.

65 66

11
2023/3/13

4.10 Structured Programming Summary


(cont.)
Figure 4.21 shows the rules for forming structured
programs.
The rules assume that action states may be used to indicate
any action.
The rules also assume that we begin with the so-called
simplest activity diagram (Fig. 4.22), consisting of only an
initial state, an action state, a final state and transition
arrows.
Applying the rules of Fig. 4.21 always results in an activity
diagram with a neat, building-block appearance.
Rule 2 generates a stack of control statements, so let’s call
Rule 2 the stacking rule.
Rule 3 is the nesting rule.

67 68

69 70

71 72

12
2023/3/13

73

13

You might also like