ch03 controal statement i - 國立臺灣大學ccf.ee.ntu.edu.tw/~ypchiou/cpp_programming/ch03...
TRANSCRIPT
-
Photonic Modeling and Design Lab.Graduate Institute of Photonics and Optoelectronics &Department of Electrical EngineeringNational Taiwan University
C++ ProgrammingChapter 3 Control Statements: Part 1
Yih-Peng ChiouRoom 617, BL Building
(02) [email protected]
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA2
Objectives
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA3
Outline
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
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
4
3.1 Introduction
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Any solvable computing problem can be solved by the execution of a series of actions in a specific order.
Algorithm: procedure for solving a problem in terms of the actions to execute the order in which the actions execute
Program Control: specifying the order in which statements (actions) execute in a computer program
This chapter investigates program control using C++’s control statements.
5
3.2 Algorithms (演算法)
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Pseudocode (or “fake” code): an artificial and informal languagehelping you develop algorithms.
Similar to everyday English Convenient and user friendly. Helps you “think out” a program before attempting to write it. Carefully prepared pseudocode can easily be converted to a
corresponding C++ program. Normally describes only
executable statements. Declarations (that do not
have initializers or do not involve constructor calls) arenot executable statements.
6
3.3 Pseudocode
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Sequence Execution statements in a program execute one after the other in the order in which
they’re written Transfer of Control
Various C++ statements enable you to specify that the next statement to execute may be other than the next one in sequence
Three control Structures - All programs could be written using them Sequence structureSelection structureRepetition structure
7
3.4 Control Structure
goto elimination
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Sequence Structure in C++Unless directed otherwise, the computer executes C++ statements
one after the other in the order in which they’re written Unified Modeling Language (UML) activity diagram
workflow (also called the activity) action state symbols (a rectangle) diamonds and small circles, etc
8
3.4 Control Structure
connected by transition arrows
initial-state
final-state
notes
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
if selection statement single-selection statement selects or ignores a single action (or a group of actions)
if…else statementdouble-selection statement selects between two different actions (or groups of actions)
switch selection statementmultiple-selection statement selects among many different actions (or groups of actions)
Three types of repetition statementsalso called looping statements or loopswhile and for statements: perform the action (or group of
actions) in their bodies zero or more timesdo…while statement: performs it (them) at least once
9
3.4 Control Structure
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA10
3.4 Control Structure
Keywords must not be used as identifiers, such as variable names.
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Single-entry/single-exit control statementsconnecting the exit point of one to the entry point of the nextcalled control-statement stackingonly one other way to connect control statements—called
control-statement nesting, in which one control statement is contained inside another.
11
3.4 Control Structure
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA12
3.4 Control Structure
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Single-selection statement Selects or ignores a single action (or a group of actions) Ex: whether “student’s grade is greater than or equal to 60” is true or false
Pseudocode: If student’s grade is greater than or equal to 60Print “Passed”
If true, “Passed” is printed. If false, the print statement is ignored C++ code if ( grade >= 60 )
cout
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Specifies an action to perform when the condition is true and a different action to perform when the condition is false.
Ex:
15
3.6 if…else Double-Selection Statement
If student’s grade is greater than or equal to 60Print “Passed”
ElsePrint “Failed”
psedocode
if ( grade >= 60 ) cout
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Conditional operator (?:)C++’s only ternary operator—it takes three operands.
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 falseThe values in a conditional expression also can be actions to
execute. Ex:
17
3.6 if…else Double-Selection Statement
cout = 60) ? ”Passed” : “Failed“);if ( grade >= 60 ) cout
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
C++ code
if ( studentGrade >= 90 ) // 90 and above gets "A"cout = 80 ) // 80-89 gets "B"
cout = 70 ) // 70-79 gets "C"cout = 60 ) // 60-69 gets "D"
cout
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA21
3.6 if…else Double-Selection Statement
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Dangling-else problem if ( x > 5 )
if ( y > 5 )cout 5 )
cout 5 )cout
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA23
3.6 if…else Double-Selection Statement
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
To include several statements in the body of an if or in either part of an if…else, enclose the statements in braces ({ and }).
A set of statements contained within a pair of braces is called a compound statement or a block.
Null statement or an empty statement It’s also possible to have no statement at all.The null statement is represented by placing a semicolon (;)
where a statement would normally be.
24
3.6 if…else Double-Selection Statement
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Repetition statement (also called looping statement or a loop) repeat an action while some condition remains true
While there are more items on my shopping listPurchase next item and cross it off my list
Eventually, the condition will become false, the repetition will terminate, and the first statement after the repetition will execute
Find the first power of 3 larger than 100int product = 3;
while ( product
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Often called definite repetition The number of repetition is known before the loop begins executing. Use a variable, counter, to control the number of times a group of
statements will execute (a.k.a. the number of iterations of the loop) The class average of quiz grades
27
3.8 Formulating Algorithms: Counter-Controlled Repetition
counter: 計數器
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA28
// gradeCounter =11 after while loop
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
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 (garbage value or undefined value).
Counter variables are normally initialized to 0 or 1, depending on their use. The variables grade and average need not be initialized before they’re
used — will be assigned as they’re input or calculated later in the function. Dividing two integers results in integer division—any fractional part of the
calculation is lost (i.e., truncated).29
3.8 Formulating Algorithms: Counter-Controlled Repetition
Q: how to store grades? A: arrays and vectors in ch. 7.
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA30
3.8 Formulating Algorithms: Counter-Controlled Repetition
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA31
3.8 Formulating Algorithms: Counter-Controlled Repetition
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Often called indefinite repetition the number of repetitions is not known in advance 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.” The sentinel value must not be an acceptable input value.
Ex: Develop a class average program that processes grades for an arbitrary number of students each time it’s run
Develop pseudocode algorithm w. Top-down, stepwise refinement Top: a complete representation of a program
Determine the class average for the quiz for an arbitrary number of students
First refinement: divide the top into a series of smaller tasks and list these in the order Initialize variablesInput, sum and count the quiz gradesCalculate and print the total of all student grades and the class
average32
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Second refinement: commit specific variables
33
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
Input, sum and count the quiz grades
Calculate and print the total Of all student grades and the class average
Initialize variables
First refinement
(= -1?)
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
This would cause an infinite loop in the program if the user did not input –1 for the first grade
Test for the possibility of division by zeroNormally a fatal logic error that, if undetected, would cause the
program to fail (often called “crashing”).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).
C++ floating-point numbers in memory: float: single-precision, 4 Bytes, 7 significant digits on most 32-bit
systems.double: double-precision, 8 Bytes, 15 significant digits ……
C++ treats all floating-point numbers in a program’s source code as double values by default.Known as floating-point constants.
Floating-point numbers often arise as a result of division
34
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA35
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA36
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
average = total / gradeCounter;
integer division, fractional part of the calculation is lost (truncated)Unary cast operator ( unary vs. binary)
static_cast(total) creates a temporary floating-point copy of its operand in parentheses.
Explicit conversion. The value stored in total is still an integer.A floating-point value divided by the integer gradeCounter.
The compiler knows how to evaluate only expressions in which the operand types of are identical.
Compiler performs promotion (also called implicit conversion) on selected operands.
In an expression containing values of data types int and double, C++ promotes int operands to double values.
Cast operators are available for use with every data type and with class types as well.
37
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Parameterized stream manipulator (argument in parentheses). Include the header .Setprecision(2)
Rounded to 2 digits of precision to the right of the decimal point (e.g., 92.37, 12345.78, 0.17)
Precision not specified: normally output with 6 digitsStream manipulator fixed: output in fixed-point format, as
opposed to scientific notation (scientific,e.g. 9.24e+001, 1.23e+004, 1.73e-001)
Also possible to force a decimal point to appear by using stream manipulator showpoint
38
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA39
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA40
3.9 Formulating Algorithms: Sentinel-Controlled Repetition
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
41
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Nesting one control statement within another
42
3.10 Formulating Algorithms: Nested Control Statements
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
43
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA44
3.10 Formulating Algorithms: Nested Control Statements
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Assignment operators for abbreviating assignment expressionsvariable = variable operator expression;
variable operator= expression;
45
3.11 Assignment Operators
// equivalently
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
Increment operator, ++: adding 1 from the value of a numeric variable Decrement operator, --: subtracting 1 ……
46
3.12 Increment and Decrement Operators
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA47
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA
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 postincrementingthe variable have different effects (and similarly for predecrementing and post-decrementing).
48
3.12 Increment and Decrement Operators
-
YPC - NTU GIPO & EE Introduction to C++ ProgrammingNTU BA49
3.12 Increment and Decrement Operators