0% found this document useful (0 votes)
17 views15 pages

ch03 Notes

Chapter 3 introduces control statements in programming, emphasizing the importance of understanding problems and planning solutions before coding. It covers algorithms, pseudocode, and the three main control structures: sequence, selection, and repetition, using C++ as the primary language for examples. The chapter also details specific control statements like if, if...else, and switch, along with their implementations and usage in structured programming.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views15 pages

ch03 Notes

Chapter 3 introduces control statements in programming, emphasizing the importance of understanding problems and planning solutions before coding. It covers algorithms, pseudocode, and the three main control structures: sequence, selection, and repetition, using C++ as the primary language for examples. The chapter also details specific control statements like if, if...else, and switch, along with their implementations and usage in structured programming.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

2023/3/5

Chapter 3,
Control Statements: Part
1

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

1 2

3.1 Introduction
Before writing a program to solve a problem, we must
have a thorough understanding of the problem and a
carefully planned approach to solving it.
When writing a program, we must also understand the
types of building blocks that are available and employ
proven program construction techniques.
In this chapter and in Chapter 4, Control Statements:
Part 2, we discuss these issues as we present the theory
and principles of structured programming.

3 4

3.2 Algorithms 3.3 Pseudocode


Any solvable computing problem can be solved by the Pseudocode (or “fake” code) is an artificial and informal
execution of a series of actions in a specific order. language that helps you develop algorithms.
Similar to everyday English
An algorithm is procedure for solving a problem in
Convenient and user friendly.
terms of
Helps you “think out” a program before attempting to write it.
◦ the actions to execute and
Carefully prepared pseudocode can easily be converted to a
◦ the order in which the actions execute
corresponding C++ program.
Specifying the order in which statements (actions) Normally describes only executable statements.
execute in a computer program is called program Declarations (that do not have initializers or do not involve
control. constructor calls) are not executable statements.
This chapter investigates program control using C++’s Fig. 3.1 corresponds to the algorithm that inputs two integers
control statements. from the user, adds these integers and displays their sum.

5 6

1
2023/3/5

3.4 Control Structures


Normally, statements in a program execute one after the other in
the order in which they’re written.
◦ Called sequential execution.
Various C++ statements enable you to specify that the next
statement to execute may be other than the next one in sequence.
◦ Called transfer of control.
All programs could be written in terms of only three control
structures
◦ the sequence structure
◦ the selection structure and
◦ the repetition structure
When we introduce C++’s implementations of control structures,
we’ll refer to them in the terminology of the C++ standard
document as “control statements.”

7 8

3.4 Control Structures (cont.)


Unless directed otherwise, the computer executes C++
statements one after the other in the order in which
they’re written—that is, in sequence.
The Unified Modeling Language (UML) activity
diagram of Fig. 3.2 illustrates a typical sequence
structure in which two calculations are performed in
order.
C++ allows us to have as many actions as we want in a
sequence structure.
Anywhere a single action may be placed, we may place
several actions in sequence.

9 10

3.4 Control Structures (cont.) 3.4 Control Structures (cont.)


An activity diagram models the workflow (also called the The arrows in the activity diagram are called transition
activity) of a portion of a software system.
arrows.
Such workflows may include a portion of an algorithm, such as
the sequence structure in Fig. 3.2. ◦ Represent transitions, which indicate the order in which the
Activity diagrams are composed of special-purpose symbols, actions represented by the action states occur.
such as action state symbols (a rectangle with its left and right The solid circle at the top of the diagram represents the
sides replaced with arcs curving outward), diamonds and small activity’s initial- state—the beginning of the workflow
circles; these symbols are connected by transition arrows, which
represent the flow of the activity. before the program performs the modeled activities.
Activity diagrams help you develop and represent algorithms, but The solid circle surrounded by a hollow circle that
many programmers prefer pseudocode. appears at the bottom of the activity diagram represents
Activity diagrams clearly show how control structures operate.
the final state—the end of the workflow after the
Action states represent actions to perform.
◦ Each contains an action expression that specifies a particular action to program performs its activities.
perform.

11 12

2
2023/3/5

3.4 Control Structures (cont.) 3.4 Control Structures (cont.)


Rectangles with the upper-right corners folded over are C++ provides three types of selection statements
called notes in the UML. (discussed in this chapter and Chapter 4).
◦ Explanatory remarks that describe the purpose of symbols in The if selection statement either performs (selects) an
the diagram. action if a condition (predicate) is true or skips the
◦ Notes can be used in any UML diagram. action if the condition is false.
Figure 3.2 uses UML notes to show the C++ code The if…else selection statement performs an action if a
associated with each action state in the activity condition is true or performs a different action if the
condition is false.
diagram.
The switch selection statement (Chapter 4) performs
A dotted line connects each note with the element that
one of many different actions, depending on the value
the note describes. of an integer expression.

13 14

3.4 Control Structures (cont.) 3.4 Control Structures (cont.)


The if selection statement is a single-selection C++ provides three types of repetition statements (also
statement because it selects or ignores a single action called looping statements or loops) for performing
(or, as we’ll soon see, a single group of actions). statements repeatedly while a condition (called the
The if…else statement is called a double-selection loop-continuation condition) remains true.
statement because it selects between two different These are the while, do…while and for statements.
actions (or groups of actions). The while and for statements perform the action (or
The switch selection statement is called a multiple- group of actions) in their bodies zero or more times.
selection statement because it selects among many The do…while statement performs the action (or group
different actions (or groups of actions). of actions) in its body at least once.

15 16

3.4 Control Structures (cont.)


Each of the words if, else, switch, while, do and for is
a C++ keyword.
These words are reserved by the C++ programming
language to implement various features, such as C++’s
control statements.
Keywords must not be used as identifiers, such as
variable names.
Figure 3.3 provides a complete list of C++ keywords-.

17 18

3
2023/3/5

3.4 Control Structures (cont.) 3.5 if Selection Statement


Each program combines control statements as appropriate Programs use selection statements to choose among
for the algorithm the program implements. alternative courses of action.
Cn model each control statement as an activity diagram The following pseudocode determines whether “student’s
grade is greater than or equal to 60” is true or false.
with an initial state and a final state that represent a control
If student’s grade is greater than or equal to 60
statement’s entry point and exit point, respectively. Print “Passed”
Single-entry/single-exit control statements ◦ If true, “Passed” is printed and the next pseudocode statement in
order is “performed” (remember that pseudocode is not a real
◦ Control statements are attached to one another by con-necting the programming language).
exit point of one to the entry point of the next. ◦ If false, the print statement is ignored and the next pseudocode
◦ Called control-statement stacking. statement in order is performed.
◦ Only one other way to connect control statements—called control- ◦ The indentation of the second line is optional, but it’s recommended
statement nesting, in which one control statement is contained inside because it emphasizes the inherent structure of structured programs.
another.

19 20

3.5 if Selection Statement (cont.) 3.5 if Selection Statement (cont.)


The preceding pseudocode If statement can be written in A decision can be based on any expression—if the
C++ as
● if ( grade >= 60 )
expression evaluates to zero, it’s treated as false; if the
cout << "Passed"; expression evaluates to nonzero, it’s treated as true.
Figure 3.4 illustrates the single-selection if statement. C++ provides the data type bool for variables that can
The diamond or decision symbol indicates that a decision is hold only the values true and false—each of these is a
to be made. C++ keyword.
◦ The workflow will continue along a path determined by the symbol’s
associated guard conditions, which can be true or false.
◦ Each transition arrow emerging from a decision symbol has a guard
condition in square brackets above or next to the transition arrow.
◦ If a guard condition is true, the workflow enters the action state to
which that transition arrow points.

21 22

3.6 if…else Double-Selection Statement


3.6 if…else Double-Selection Statement
(cont.)
if…else double-selection statement Figure 3.5 illustrates the the if…else statement’s flow
◦ specifies an action to perform when the condition is true and a different action to
perform when the condition is false. of control.
The following pseudocode prints “Passed” if the student’s grade is
greater than or equal to 60, or “Failed” if the student’s grade is less
than 60.
If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”
In either case, after printing occurs, the next pseudocode statement in
sequence is “performed.”
The preceding pseudocode If…Else statement can be written in C++ as
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";

23 24

4
2023/3/5

3.6 if…else Double-Selection Statement


(cont.)
Conditional operator (?:)
◦ Closely related to the if…else statement.
C++’s only ternary operator—it takes three operands.
The operands, together with the conditional operator,
form a conditional expression.
◦ The first operand is a condition
◦ The second operand is the value for the entire conditional
expression if the condition is true
◦ The third operand is the value for the entire conditional
expression if the condition is false.
The values in a conditional expression also can be
actions to execute.

25 26

3.6 if…else Double-Selection Statement 3.6 if…else Double-Selection Statement


(cont.) (cont.)
Nested if…else statements test for multiple cases by This pseudocode can be written in C++ as
placing if…else selection statements inside other if…else if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
selection statements. else
If student’s grade is greater than or equal to 90 if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
Print “A” else
Else if ( studentGrade >= 70 ) // 70-79 gets "C"
If student’s grade is greater than or equal to 80 cout << "C";
Print “B” else
Else if ( studentGrade >= 60 ) // 60-69 gets "D"
If student’s grade is greater than or equal to 70 cout << "D";
Print “C” else // less than 60 gets "F"
cout << "F";
Else
If student’s grade is greater than or equal to 60 If studentGrade is greater than or equal to 90, the first four
Print “D” conditions are true, but only the output statement after the first
Else test executes. Then, the program skips the else-part of the
Print “F” “outermost” if…else statement.

27 28

3.6 if…else Double-Selection Statement 3.6 if…else Double-Selection Statement


(cont.) (cont.)
Most write the preceding if…else statement as The C++ compiler always associates an else with the
● if ( studentGrade >= 90 ) // 90 and above gets "A" immediately preceding if unless told to do otherwise by the
cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B" placement of braces ({ and }).
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C" This behavior can lead to what’s referred to as the dangling-
cout << "C"; else problem.
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D"; ● if ( x > 5 )
else // less than 60 gets "F" if ( y > 5 )
cout << "F"; cout << "x and y are > 5";
The two forms are identical except for the spacing and else
indentation, which the compiler ignores. cout << "x is <= 5";
The latter form is popular because it avoids deep indentation of appears to indicate that if x is greater than 5, the nested if
the code to the right, which can force lines to wrap. statement determines whether y is also greater than 5.

©1992-2011 by Pearson Education, Inc.


All Rights Reserved.

29 30

5
2023/3/5

3.6 if…else Double-Selection Statement 3.6 if…else Double-Selection Statement


(cont.) (cont.)
The compiler actually interprets the statement as The if selection statement expects only one statement in
● if ( x > 5 )
if ( y > 5 ) its body.
cout << "x and y are > 5";
else Similarly, the if and else parts of an if…else statement
cout << "x is <= 5";
To force the nested if…else statement to execute as intended, each expect only one body statement.
use: To in-clude several statements in the body of an if or in
● if ( x > 5 )
{ either part of an if…else, enclose the statements in
if ( y > 5 )
cout << "x and y are > 5"; braces ({ and }).
}
else A set of statements contained within a pair of braces is
cout << "x is <= 5";
Braces ({}) indicate that the second if statement is in the body of called a compound statement or a block.
the first if and that the else is associated with the first if.

31 32

3.6 if…else Double-Selection Statement


3.7 while Repetition Statement
(cont.)
Just as a block can be placed anywhere a single A repetition statement (also called a looping statement or a
loop) allows you to specify that a program should repeat an
statement can be placed, it’s also possible to have no
action while some condition remains true.
statement at all—called a null statement (or an empty While there are more items on my shopping list
statement). Purchase next item and cross it off my list
“There are more items on my shopping list” is true or false.
The null statement is represented by placing a
◦ If true, “Purchase next item and cross it off my list” is performed.
semicolon (;) where a statement would normally be. ● Performed repeatedly while the condition remains true.
◦ The statement contained in the While repetition statement constitutes
the body of the While, which can be a single statement or a block.
◦ Eventually, the condition will become false, the repetition will
terminate, and the first pseudocode statement after the repetition
statement will execute.

33 34

3.7 while Repetition Statement (cont.) 3.7 while Repetition Statement (cont.)

Consider a program segment designed to find the first The UML activity diagram of Fig. 3.6 illustrates the flow of
power of 3 larger than 100. Suppose the integer control that corresponds to the preceding while statement.
variable product has been initialized to 3. This diagram introduces the UML’s merge symbol, which
When the following while repetition statement finishes joins two flows of activity into one flow of activity.
executing, product contains the result: The UML represents both the merge symbol and the
● int product = 3; decision symbol as diamonds.
The merge symbol joins the transitions from the initial state
while ( product <= 100 ) and from the action state, so they both flow into the
product = 3 * product; decision that determines whether the loop should begin (or
continue) executing.

35 36

6
2023/3/5

3.7 while Repetition Statement (cont.)


The decision and merge symbols can be distinguished by
the number of “incoming” and “outgoing” transition
arrows.
◦ A decision symbol has one transition arrow pointing to the diamond
and two or more transition arrows pointing out from the diamond to
indicate possible transitions from that point.
◦ Each transition arrow has a guard condition next to it.
A merge symbol has two or more transition arrows pointing
to the diamond and only one transition arrow pointing from
the diamond, to indicate multiple activity flows merging to
continue the activity.
◦ Unlike the decision symbol, the merge symbol does not have a
counterpart in C++ code.

37 38

3.8 Formulating Algorithms: Counter- 3.8 Formulating Algorithms: Counter-


Controlled Repetition Controlled Repetition (cont.)
Consider the following problem statement: We use counter-controlled repetition to input the grades
◦ A class of ten students took a quiz. The grades (integers in the one at a time.
range 0 to 100) for this quiz are available to you. Calculate and ◦ This technique uses a variable called a counter to control the
display the total of all student grades and the class average on number of times a group of statements will execute (also
the quiz. known as the number of iterations of the loop).
The class average is equal to the sum of the grades ◦ Often called definite repetition because the number of
divided by the number of students. repetitions is known before the loop begins exe-cut-ing.
The algorithm for solving this problem on a computer
must input each of the grades, calculate the average and
print the result.

39 40

3.8 Formulating Algorithms: Counter-


Controlled Repetition (cont.)
A total is a variable used to accumulate the sum of
several values.
A counter is a variable used to count—in this case, the
grade counter indicates which of the 10 grades is about
to be entered by the user.
Variables used to store totals are normally initialized to
zero before being used in a program; otherwise, the
sum would in-clude the previous value stored in the
total’s memory location.

41 42

7
2023/3/5

43 44

3.8 Formulating Algorithms: Counter- 3.8 Formulating Algorithms: Counter-


Controlled Repetition (cont.) Controlled Repetition (cont.)
The averaging calculation is performed in member Counter variables are normally initialized to zero or
function determineClass-Average using local one, depending on their use.
variables—we do not preserve any information about An uninitialized variable contains a “garbage” value
student grades in the class’s data members. (also called an undefined value)—the value last stored
◦ In Chapter 7, Arrays and Vectors, we modify class in the memory location reserved for that variable.
GradeBook to maintain the grades in memory using a data
The variables grade and average (for the user input
member that refers to a data structure known as an array.
and calculated average, respectively) need not be
initialized before they’re used—their values will be
assigned as they’re input or calculated later in the
function.

45 46

3.8 Formulating Algorithms: Counter- 3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.) Controlled Repetition
The averaging calculation performed in response to the Let’s generalize the class average problem.
◦ Develop a class average program that processes grades for an
function call in line 12 of Fig. 3.10 produces an integer arbitrary number of students each time it’s run.
result. The program must process an arbitrary number of grades.
Dividing two integers results in integer division—any ◦ How can the program determine when to stop the input of grades?
fractional part of the calculation is lost (i.e., truncated). Can use a special value called a sentinel value (also called a
signal value, a dummy value or a flag value) to indicate
“end of data entry.”
Sentinel-controlled repetition is often called indefinite
repetition
◦ the number of repetitions is not known in advance.
The sentinel value must not be an acceptable input value.

47 48

8
2023/3/5

3.9 Formulating Algorithms: Sentinel- 3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.) Controlled Repetition (cont.)
We approach the class average program with a technique We divide the top into a series of smaller tasks and list
called top-down, stepwise refinement, a technique that is these in the order in which they need to be performed.
essential to the development of well-structured programs. This results in the following first refinement.
We begin with a pseudocode representation of the top—a Initialize variables
single statement that conveys the overall function of the Input, sum and count the quiz grades
program: Calculate and print the total of all student grades and the class average
◦ Determine the class average for the quiz for an arbitrary number of This refinement uses only the sequence structure—
students these steps execute in order.
The top is, in effect, a complete representation of a
program.
◦ Rarely conveys sufficient detail from which to write a pro-gram.

49 50

3.9 Formulating Algorithms: Sentinel- 3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.) Controlled Repetition (cont.)
In the second refinement, we commit to specific The pseudocode statement
Input, sum and count the quiz grades
variables.
requires a repetition statement (i.e., a loop) that
Only the variables total and counter need to be successively inputs each grade.
initialized before they’re used. We don’t know in advance how many grades are to be
The variables average and grade (for the calculated processed, so we’ll use sentinel-controlled repetition.
average and the user input, respectively) need not be The user enters legitimate grades one at a time.
initialized, because their values will be replaced as After entering the last legitimate grade, the user enters the
sentinel value.
they’re calculated or input.
The program tests for the sentinel value after each grade is
input and terminates the loop when the user enters the
sentinel value.

51 52

3.9 Formulating Algorithms: Sentinel- 3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.) Controlled Repetition (cont.)
The second refinement of the preceding pseudocode The pseudocode statement
Calculate and print the total of all student grades and the class average
statement is then
Prompt the user to enter the first grade can be refined as follows:
Input the first grade (possibly the sentinel) If the counter is not equal to zero
Set the average to the total divided by the counter
While the user has not yet entered the sentinel Print the total of the grades for all students in the class
Print the class average
Add this grade into the running total
Else
Add one to the grade counter Print “No grades were entered”
Prompt the user to enter the next grade
Test for the possibility of division by zero
Input the next grade (possibly the sentinel)
◦ Normally a fatal logic error that, if undetected, would cause the
program to fail (often called “crashing”).

53 54

9
2023/3/5

3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.)
An averaging calculation is likely to produce a number with
a decimal point—a real number or floating-point number
(e.g., 7.33, 0.0975 or 1000.12345).
Type int cannot represent such a number.
C++ provides several data types for storing floating-point
numbers in memory, including float and double.
Compared to float variables, double variables can typically
store numbers with larger magnitude and finer detail
◦ more digits to the right of the decimal point—also known as the
number’s precision.
Cast operator can be used to force the averaging calculation
to produce a floating-point numeric result.

55 56

57 58

3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.)
Notice the block in the while loop in Fig. 3.13.
Without the braces, the last three statements in the body
of the loop would fall outside the loop, causing the
computer to interpret this code incorrectly, as follows:
// loop until sentinel value read from user
while ( grade != -1 )
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter

// prompt for input and read next grade from user


cout << "Enter grade or -1 to quit: ";
cin >> grade;
This would cause an infinite loop in the program if the
user did not input –1 for the first grade (in line 57).

59 60

10
2023/3/5

3.9 Formulating Algorithms: Sentinel- 3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.) Controlled Repetition (cont.)
Variables of type float represent single-precision floating- The variable average is declared to be of type double to
point numbers and have seven significant digits on most 32- capture the fractional result of our calculation.
bit systems. total and gradeCounter are both integer variables.
Variables of type double represent double-precision
Recall that dividing two integers results in integer division,
floating-point numbers.
◦ These require twice as much memory as float variables and provide in which any fractional part of the calculation is lost (i.e.,
15 significant digits on most 32-bit systems truncated).
◦ Approximately double the precision of float variables In the following statement the division occurs first—the
C++ treats all floating-point numbers in a program’s source result’s fractional part is lost before it’s assigned to
code as double values by default. average:
◦ Known as floating-point constants.
● average = total / gradeCounter;
Floating-point numbers often arise as a result of division.

61 62

3.9 Formulating Algorithms: Sentinel- 3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.) Controlled Repetition (cont.)
To perform a floating-point calculation with integers, The calculation now consists of a floating-point value
create temporary floating-point values. divided by the integer gradeCounter.
Unary cast operator accomplishes this task. ◦ The compiler knows how to evaluate only expressions in
which the operand types of are identical.
The cast operation static_cast<double>(total)
◦ Compiler performs promotion (also called implicit conversion)
creates a temporary floating-point copy of its operand
on selected operands.
in parentheses. ◦ In an expression containing values of data types int and
◦ Known as explicit conversion. double, C++ promotes int operands to double values.
◦ The value stored in total is still an integer. Cast operators are available for use with every data
type and with class types as well.

63 64

3.9 Formulating Algorithms: Sentinel- 3.9 Formulating Algorithms: Sentinel-


Controlled Repetition (cont.) Controlled Repetition (cont.)
The call to setprecision in line 79 (with an argument Stream manipulator fixed indicates that floating-point
of 2) indicates that double values should be printed values should be output in fixed-point format, as
with two digits of precision to the right of the decimal opposed to scientific notation.
point (e.g., 92.37). Fixed-point formatting is used to force a floating-point
◦ Parameterized stream manipulator (argument in parentheses). number to display a specific number of digits.
◦ Programs that use these must include the header <iomanip>.
Specifying fixed-point formatting also forces the
endl is a nonparameterized stream manipulator and decimal point and trailing zeros to print, even if the
does not require the <iomanip> header file. value is a whole number amount, such as 88.00.
If the precision is not specified, floating-point values ◦ Without the fixed-point formatting option, such a value prints
are normally output with six digits of precision. in C++ as 88 without the trailing zeros and decimal point.

65 66

11
2023/3/5

3.9 Formulating Algorithms: Sentinel- 3.10 Formulating Algorithms: Nested


Controlled Repetition (cont.) Control Statements
When the stream manipulators fixed and setprecision Consider the following problem statement:
◦ A college offers a course that prepares students for the state licensing
are used in a program, the printed value is rounded to exam for real es-tate brokers. Last year, ten of the students who
the number of decimal positions indicated by the value completed this course took the exam. The college wants to know how
well its students did on the exam. You’ve been asked to write a program
passed to setprecision (e.g., the value 2 in line 79), to summarize the results. You’ve been given a list of these 10 students.
although the value in memory re-mains unaltered. Next to each name is written a 1 if the student passed the exam or a 2 if
the student failed.
It’s also possible to force a decimal point to appear by ◦ Your program should analyze the results of the exam as follows:
using stream manipulator showpoint. ◦ 1.Input each test result (i.e., a 1 or a 2). Display the prompting message
“Enter result” each time the program requests another test result.
◦ If showpoint is specified without fixed, then trailing zeros ◦ 2.Count the number of test results of each type.
will not print. ◦ 3.Display a summary of the test results indicating the number of students
◦ Both can be found in header <iostream>. who passed and the number who failed.
◦ 4.If more than eight students passed the exam, print the message “Bonus
to instructor!”

67 68

3.10 Formulating Algorithms: Nested 3.10 Formulating Algorithms: Nested


Control Statements (cont.) Control Statements (cont.)
After reading the problem statement carefully, we make the Pseudocode representation of the top:
following observations: Analyze exam results and decide whether tuition should be raised
◦ Must process test results for 10 students. A counter-controlled loop
can be used because the number of test results is known in advance. Once again, it’s important to emphasize that the top is a
◦ Each test result is a number—either a 1 or a 2. Each time the complete representation of the program, but several
program reads a test result, the program must determine whether the refinements are likely to be needed before the
number is a 1 or a 2. We test for a 1 in our algorithm. If the number
is not a 1, we assume that it’s a 2. (Exercise 3.20 considers the pseudocode evolves naturally into a C++ program.
consequences of this assumption.) Our first refinement is
◦ Two counters keep track of the exam results—one to count the Initialize variables
number of students who passed and one to count the number of
students who failed. Input the 10 exam results, and count passes and failures
Print a summary of the exam results and decide if tuition should be
◦ After the program has processed all the results, it must decide
raised
whether more than eight students passed the exam.
Further refinement is necessary.

69 70

3.10 Formulating Algorithms: Nested 3.10 Formulating Algorithms: Nested


Control Statements (cont.) Control Statements (cont.)
Counters are needed to record the passes and failures, a The following pseudocode statement requires a loop that successively
inputs the result of each exam
counter will be used to control the looping process and Input the 10 exam results, and count passes and failures
10 exam results, so counter-controlled looping is appropriate.
a variable is needed to store the user input. Nested inside the loop, an if…else statement will determine whether
The pseudocode statement each exam result is a pass or a failure and will increment the
appropriate counter.
Initialize variables
The refinement of the preceding pseudocode statement is then
can be refined as follows: While student counter is less than or equal to 10
Prompt the user to enter the next exam result
Initialize passes to zero Input the next exam result
Initialize failures to zero
If the student passed
Initialize student counter to one Add one to passes
Else
Add one to failures

Add one to student counter

71 72

12
2023/3/5

3.10 Formulating Algorithms: Nested


Control Statements (cont.)
The pseudocode statement
Print a summary of the exam results and decide whether tuition should be
raised
can be refined as follows:
Print the number of passes
Print the number of failures

If more than eight students passed


Print “Bonus to instructor!”
The complete second refinement appears in Fig. 3.15.

73 74

75 76

77 78

13
2023/3/5

3.10 Formulating Algorithms: Nested


3.11 Assignment Operators
Control Statements (cont.)
C++ allows variable initialization to be incorporated C++ provides several assignment operators for abbreviating assignment
expressions.
into declarations. The += operator adds the value of the expression on the right of the
operator to the value of the variable on the left of the operator and
The if…else statement (lines 22–25) for processing stores the result in the variable on the left of the operator.
each result is nested in the while statement. Any statement of the form
● variable = variable operator expression;
The if statement in lines 35–36 determines whether in which the same variable appears on both sides of the assignment
more than eight students passed the exam and, if so, operator and operator is one of the binary operators +, -, *, /, or % (or
others we’ll discuss later in the text), can be written in the form
outputs the message "Bonus to instructor!". ● variable operator= expression;
Thus the assignment c += 3 adds 3 to c.
Figure 3.17 shows the arithmetic assignment operators, sample
expressions using these operators and explanations.

79 80

3.12 Increment and Decrement


Operators
C++ also provides two unary operators for adding 1 to
or subtracting 1 from the value of a numeric variable.
These are the unary increment operator, ++, and the
unary decrement operator, --, which are summarized in
Fig. 3.18.

81 82

83 84

14
2023/3/5

3.12 Increment and Decrement


Operators (cont.)
When you increment (++) or decrement (--) a variable in a
statement by itself, the preincrement and postincrement
forms have the same effect, and the predecrement and
postdecrement forms have the same effect.
It’s only when a variable appears in the context of a larger
expression that preincrementing the variable and
postincrementing the variable have different effects (and
similarly for predecrementing and post-decrementing).
Figure 3.20 shows the precedence and associativity of the
operators introduced to this point.

85 86

87

15

You might also like