Transcript Slide 1

TK 1914 : C++ Programming
Control Structures I (Selection)
OBJECTIVES
In this chapter you will:
• Learn about control structures
• Examine relational and logical operators
• Explore how to form and evaluate logical
(Boolean) expressions
• Discover how to use the selection control
structures if, if...else, and switch in a
program
FTSM :: TK1914, 20112012
2
INTRODUCTION
• A computer can process:
– In sequence
– Selectively (branch) - making a choice
– Repetitively (iteratively) - looping
• Some statements are executed only if certain
conditions are met
• A condition is represented by a logical (Boolean)
expression that can be true or false
• A condition is met if it evaluates to true
FTSM :: TK1914, 20112012
3
FTSM :: TK1914, 20112012
4
• We have seen sequencing in C++.
• How do we translate selection and repetition
structures into C++?
FTSM :: TK1914, 20112012
5
SELECTION STRUCTURES IN C++
• Selection structures can be translated into C++
using if statements.
• Four forms of selection structures will be looked
at:
– One-Way
– Two-Way
– Nested
– Switch
FTSM :: TK1914, 20112012
6
if STATEMENT :
ONE-WAY SELECTION
• The syntax of one-way selection is:
if (expression)
statement
• statement is executed only if the value of
expression is true
• expression is usually a logical expression.
• if is a reserved word
• statement must be a single C++ statement.
FTSM :: TK1914, 20112012
7
if STATEMENT :
ONE-WAY SELECTION
FTSM :: TK1914, 20112012
8
FTSM :: TK1914, 20112012
9
CLASS ACTIVITY 3.1
• Refer prog03.1.cpp.
– Examine the source code. Focus on the if
statements.
– What do you think the output would be for the
following input?
• Price per unit: RM25 Quantity: 4
• Price per unit: RM5.50 Quantity: 5
– Run the program with the above input. Is the output
generated the same as expected?
– Draw a flowchart representing the algorithm
implemented in the program.
FTSM :: TK1914, 20112012
10
if-else STATEMENT: TWOWAY SELECTION
• Two-way selection takes the form:
if (expression)
statement1
else
statement2
• If expression is true, statement1 is executed.
Otherwise, statement2 is executed
• else is a reserved word
• statement1 and statement2 must both be
single C++ statements.
FTSM :: TK1914, 20112012
11
if-else STATEMENT: TWOWAY SELECTION
FTSM :: TK1914, 20112012
12
FTSM :: TK1914, 20112012
13
CLASS ACTIVITY 3.2
• Refer prog03.2.cpp.
– Examine the source code. Focus on the if
statements.
– What do you think the output would be for the
following input?
• Number of adults: 2 Number of children: 2
Ticket type: First class
• Number of adults: 2 Number of children: 2
Ticket type: Economy
– Run the program with the above input. Is the output
generated the same as expected?
– Draw a flowchart representing the algorithm
implemented in the program.
FTSM :: TK1914, 20112012
14
CLASS ACTIVITY 3.2
• Observe that prog03.2.cpp includes the
following declarations:
const float PRICE_FIRST_CLASS = 30.00;
const float PRICE_ECONOMY = 5.00;
The identifiers PRICE_FIRST_CLASS and
PRICE_ECONOMY are called constants. Their
values cannot be changed during program
execution.
FTSM :: TK1914, 20112012
15
COMPOUND STATEMENTS
• Consider the following structure:
input num
num = 0?
true
print warning
false
num ← 10
result ← sum / num
FTSM :: TK1914, 20112012
16
COMPOUND STATEMENTS
• Note that there are two statements to be executed if
num is equal to 0.
• Is it correct to translate the above to C++ as follows?
cin >> num;
if (num == 0)
cout << "Invalid value!";
num = 10;
result = sum / num;
• Answer: No. According to C++ syntax, the statement
num = 10;
is actually not part of the if statement.
FTSM :: TK1914, 20112012
17
COMPOUND STATEMENTS
• In this case, we need to use a compound statement
to group those statements into a single statement.
• A compound statement is simply a set of single
statements enclosed within curly brackets.
{
statement_1;
…
statement_n;
}
• Remember that a compound statement is a single
C++ statement.
FTSM :: TK1914, 20112012
18
• Example:
cin >> num;
if (num == 0)
{
cout << "Invalid value!";
num = 10;
}
result = sum / num;
compound statement
FTSM :: TK1914, 20112012
19
NESTED IF
• Consider the syntax of a one-way if statement:
if (expression)
statement
• You might ask: Could statement be another if
statement?
Example:
if (weight > 100)
if (weight <= 1000)
price = 0.20 * weight;
What does it mean?
FTSM :: TK1914, 20112012
20
NESTED IF
• Example:
FTSM :: TK1914, 20112012
21
NESTED IF
• Can also be written as follows (remember that the
compiler ignores unnecessary whitespace
characters):
FTSM :: TK1914, 20112012
22
CLASS ACTIVITY 3.3
• Examine the following code:
How is this code different from that in the next slide?
FTSM :: TK1914, 20112012
23
FTSM :: TK1914, 20112012
24
CLASS ACTIVITY 3.4
• The following bands are defined:
– Band 1: 75 and above
– Band 2: 51 - 74
– Band 3: 50 and below
• Refer prog03.3a.cpp.
– Examine the source code. Focus on the if statements.
– What do you think the output would be for the following
input?
• 80
• 60
• 40
– Run the program with the above input. Is the output
generated as expected?
FTSM :: TK1914, 20112012
25
CLASS ACTIVITY 3.4 (CONT)
• Refer prog03.3b.cpp.
– Examine the source code. How is it different from the
previous program?
– What do you think the output would be for the
following input?
• 80
• 60
• 40
– Run the program with the above input. Is the output
generated as expected?
– Draw a flowchart representing the algorithm
implemented in the program.
FTSM :: TK1914, 20112012
26
CLASS ACTIVITY 3.4 (CONT)
• Refer prog03.3c.cpp.
– Examine the source code. How is it different from the first
program?
– What do you think the output would be for the following
input?
• 80
• 60
• 40
– Run the program with the above input. Compare the
output with that of the previous program.
– Draw a flowchart representing the algorithm implemented
in the program.
• C++ always associates an else with the closest
FTSM :: TK1914, 20112012
unpaired if.
27
switch STRUCTURE
• switch structure: alternate to if-else.
• Example:
switch (code)
case 1:
Execute the
cout
statements inside the
case 2:
switch structure
starting from the case
cout
which matches the
default:
value of the expression
cout
}
FTSM :: TK1914, 20112012
{
First, evaluate
the switch
expression
<< "one";
<< "two";
<< "Error";
If there is no match,
start from the default
case
28
CLASS ACTIVITY 3.5
• Refer prog03.4.cpp.
– Examine the source code. Focus on the switch
statement.
– Observe that there are return statements in the
switch statement.
• What do you think will happen if they are
executed?
• Why do you think they are there for?
– What do you think the output would be for the
following input?
• 2 adults, 2 children, normal first-class ticket
• 2 adults, 2 children, economy ticket
FTSM :: TK1914, 20112012
29
CLASS ACTIVITY 3.5 (CONT)
• Refer prog03.4.cpp.
– Run the program with the input data given above. Is
the output as expected? Explain.
– Draw a flowchart representing the algorithm
implemented in the program.
FTSM :: TK1914, 20112012
30
switch STRUCTURE
• Expression value can be only integral
• Its value determines which statement is selected
for execution
• A particular case value should appear only once
• One or more statements may follow a case label
• Braces are not needed to turn multiple
statements into a single compound statement.
• The default case is optional in a switch
statement.
FTSM :: TK1914, 20112012
31
THE break STATEMENT
• The break statement may be used to jump out of
a switch statement.
FTSM :: TK1914, 20112012
32
FTSM :: TK1914, 20112012
33
CLASS ACTIVITY 3.6
• Refer prog03.5.cpp.
– Examine the source code. Focus on the use of break
statements in the switch statement.
– What do you think the output would be for the
following input?
• 2 adults, 2 children, normal first-class ticket
• 2 adults, 2 children, economy ticket
– Run the program with the input data given above. Is
the output as expected?
– Draw a flowchart representing the algorithm
implemented in the program.
FTSM :: TK1914, 20112012
34
switch Statement Rules
• When value of the expression is matched
against a case value,
– Statements execute until break statement is
found or the end of switch structure is reached
• If value of the expression does not match any
of the case values
– Statements following the default label execute If
no default label, and if no match, the entire
switch statement is skipped
• A break statement causes an immediate exit
from the switch structure
FTSM :: TK1914, 20112012
35
RELATIONAL OPERATOR
• Relational operators:
– Allow comparisons
– Require two operands (binary)
– Return 1 if expression is true, 0 otherwise
• Comparing values of different data types may
produce unpredictable results
– For example, 8 < '5' should not be done
• Any nonzero value is treated as true
FTSM :: TK1914, 20112012
36
FTSM :: TK1914, 20112012
37
FTSM :: TK1914, 20112012
38
CLASS ACTIVITY 3.7
• Refer prog03.6a.cpp
– Examine the source code.
– What do you think the output would be for the
following input?
• 47
• 67
– Compile the program. Are there any syntax errors?
– Run the program. Is the output as expected?
Explain.
FTSM :: TK1914, 20112012
39
CLASS ACTIVITY 3.7 (CONT.)
• Refer prog03.6b.cpp
– Examine the source code. Compare it with the
previous program.
– Run the program with the same input data as for the
previous program. Is the output as expected?
FTSM :: TK1914, 20112012
40
COMPARING string TYPES
• Relational operators can be applied to strings
• Strings are compared character by character,
starting with the first character
• Comparison continues until either a mismatch is
found or all characters are found equal
• If two strings of different lengths are compared
and the comparison is equal to the last
character of the shorter string
– The shorter string is less than the larger string
FTSM :: TK1914, 20112012
41
string COMPARISON EXAMPLE
• Suppose we have the following declarations:
string
string
string
string
str1
str2
str3
str4
=
=
=
=
"Hello";
"Hi";
"Air";
"Bill";
FTSM :: TK1914, 20112012
42
FTSM :: TK1914, 20112012
43
FTSM :: TK1914, 20112012
44
FTSM :: TK1914, 20112012
45
CLASS ACTIVITY 3.8
• Refer prog03.7.cpp
– Examine the source code. What do you think the
program does?
– What do you think the output would be for the
following input?
• Jamal Omar
Selamat Ahmad
Ali Wali
– Run the program. Is the output what you expected?
FTSM :: TK1914, 20112012
46
LOGICAL (BOOLEAN) OPERATORS
• Logical (Boolean) operators enable you to
combine logical expressions
• Three logical (Boolean) operators:
! (not)
&& (and)
|| (or)
• Logical operators take logical values as operands
and yield logical values as results
• ! is unary whereas && and || are binary
operators
• Putting ! in front of a logical expression reverses
its value
FTSM :: TK1914, 20112012
47
FTSM :: TK1914, 20112012
48
FTSM :: TK1914, 20112012
49
FTSM :: TK1914, 20112012
50
FTSM :: TK1914, 20112012
51
CLASS ACTIVITY 3.9
• Problem:
Substance A
put in container E1
Substance B
put in
container E3
Substance C
put in
container E4
put in
container E1
)[
put in
container E1
)[
-100
FTSM :: TK1914, 20112012
](
](
put in
container E2
put in
container E2
50
52
CLASS ACTIVITY 3.9 (CONT)
• Refer prog03.8a.cpp
– Examine the source code. What do you think the
program does?
– Focus on the if statement. Are all cases covered
correctly? Test the program by running it with various
input data.
• Refer prog03.8b.cpp
– Examine the source code. Compare the if statement
with that in the previous program.
– Test the program by running it with the same input
data as for the previous program.
FTSM :: TK1914, 20112012
53
Precedence of Operators
• Relational and logical operators are
evaluated from left to right
• The associativity is left to right
• Parentheses can override precedence
FTSM :: TK1914, 20112012
54
FTSM :: TK1914, 20112012
55
FTSM :: TK1914, 20112012
56
FTSM :: TK1914, 20112012
57
FTSM :: TK1914, 20112012
58
LOGICAL (BOOLEAN) EXPRESSIONS
• The bool Data Type and Logical (Boolean)
Expressions
– The data type bool has logical (Boolean) values
true and false
– bool, true, and false are reserved words
– The identifier true has the value 1
– The identifier false has the value 0
FTSM :: TK1914, 20112012
59
Logical (Boolean) Expressions
(continued)
• Logical expressions can be unpredictable
• The following expression appears to represent a
comparison of 0, num, and 10:
0 <= num <= 10
• It always evaluates true because 0 <= num
evaluates to either 0 or 1, and 0 <= 10 is true
and 1 <= 10 is true
• A correct way to write this expression is:
0 <= num && num <= 10
FTSM :: TK1914, 20112012
60
CONDITIONAL OPERATOR
• Conditional operator (?:) takes three arguments
(ternary)
• Syntax for using the conditional operator:
expression1 ? expression2 : expression3
• If expression1 is true, the result of the conditional
expression is expression2. Otherwise, the result is
expression3.
• Example:
larger = (num1<num2) ? num2 : num1;
FTSM :: TK1914, 20112012
61
Programming Example
• This programming example calculates a
customer’s bill for a local cable company
• There are two types of customers:
– Residential
– Business
• Two rates for calculating a cable bill:
– One for residential customers
– One for business customers
FTSM :: TK1914, 20112012
62
Rates
• For residential customer:
– Bill processing fee: $4.50
– Basic service fee: $20.50
– Premium channel: $7.50 per channel
• For business customer:
– Bill processing fee: $15.00
– Basic service fee: $75.00 for first 10 connections
and $5.00 for each additional connection
– Premium channel cost: $50.00 per channel for any
number of connections
FTSM :: TK1914, 20112012
63
Requirements
• Ask user for account number and customer code
• Assume R or r stands for residential customer
and B or b stands for business customer
FTSM :: TK1914, 20112012
64
Input and Output
• Input:
–
–
–
–
Customer account number
Customer code
Number of premium channels
For business customers, number of basic service
connections
• Output:
– Customer’s account number
– Billing amount
FTSM :: TK1914, 20112012
65
Program Analysis
• The purpose of the program is to calculate and
print billing amount
• Calculating the billing amount requires:
– Customer for whom the billing amount is calculated
(residential or business)
– Number of premium channels to which the customer
subscribes
• For a business customer, you need:
– Number of basic service connections
– Number of premium channels
FTSM :: TK1914, 20112012
66
Program Analysis (continued)
• Data needed to calculate the bill, such as bill
processing fees and the cost of a premium
channel, are known quantities
• The program should print the billing amount to two
decimal places
FTSM :: TK1914, 20112012
67
Algorithm Design
• Set precision to two decimal places
• Prompt user for account number and
customer type
• If customer type is R or r
– Prompt user for number of premium channels
– Compute and print the bill
• If customer type is B or b
– Prompt user for number of basic service
connections and number of premium channels
– Compute and print the bill
FTSM :: TK1914, 20112012
68
Formulas
Billing for residential customers:
amountDue = RES_BILL_PROC_FEES +
RES_BASIC_SERV_COST
+ numOfPremChannels *
RES_COST_PREM_CHANNEL;
FTSM :: TK1914, 20112012
69
Formulas (continued)
Billing for business customers:
if (numOfBasicServConn <= 10)
amountDue = BUS_BILL_PROC_FEES +
BUS_BASIC_SERV_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
else
amountDue = BUS_BILL_PROC_FEES +
BUS_BASIC_SERV_COST
+ (numOfBasicServConn - 10)
* BUS_BASIC_CONN_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
FTSM :: TK1914, 20112012
70
Main Algorithm
1. Output floating-point numbers in fixed decimal
with decimal point and trailing zeros
• Output floating-point numbers with two decimal
places, set the precision to two decimal places
2.
3.
4.
5.
Prompt user to enter account number
Get customer account number
Prompt user to enter customer code
Get customer code
FTSM :: TK1914, 20112012
71
Main Algorithm (continued)
6. If the customer code is r or R,
–
Prompt user to enter number of premium channels
–
Get the number of premium channels
–
Calculate the billing amount
–
Print account number and billing amount
FTSM :: TK1914, 20112012
72
Main Algorithm (continued)
7. If customer code is b or B,
–
Prompt user to enter number of basic service
connections
–
Get number of basic service connections
–
Prompt user to enter number of premium channels
–
Get number of premium channels
–
Calculate billing amount
–
Print account number and billing amount
8. If customer code is other than r, R, b, or B,
output an error message
FTSM :: TK1914, 20112012
73
SUGGESTED READING (ROYO)
• Chapter 4: Control structures I (Selection)
FTSM :: TK1914, 20112012
YOU SHOULD NOW KNOW…
• the syntax of the if statement
• how to translate a selection structure in a
flowchart into a C++ if statement
• one-way selection
• two-way selection
• compound statement
• nested if statements
• switch statement
• break statement
FTSM :: TK1914, 20112012
75
YOU SHOULD NOW KNOW…
• relational operators
• using relational operators to compare string
values
• logical operators
• bool variables
• the conditional operator
FTSM :: TK1914, 20112012
76