+ All Categories
Home > Documents > Programming Lecture 02 (I): Boolean Control Structures...

Programming Lecture 02 (I): Boolean Control Structures...

Date post: 06-Feb-2018
Category:
Upload: vanbao
View: 217 times
Download: 1 times
Share this document with a friend
11
Computational Intelligence on Automation Lab @ NCTU UEE1302(1102) F10: Introduction to Computers and Programming Programming Lecture 02 Programming Lecture 02 Flow of Control Flow of Control (I): (I): Boolean Boolean Expression and Selection Expression and Selection PRO_02 PROF. HUNG-PIN(CHARLES) WEN 2 Learning Objectives Learning Objectives You should be able to describe: Relational Expressions Logical Expressions if-else Statement Nested if and if Chain Statements switch Statement Common Programming Errors PRO_02 PROF. HUNG-PIN(CHARLES) WEN 3 Control Structures Control Structures Flow of Control: the order in which a program’s statements are executed –Normal flow is sequential Selection and Repetition statements allow programmer to alter normal flow Selection: selects a particular statement to be executed next selection is from a well-defined set Repetition: allows a set of statements to be repeated PRO_02 PROF. HUNG-PIN(CHARLES) WEN 4 Flow of Execution Flow of Execution statement 1 statement 2 statement N ••• bool_expr stmt_NO stmt_YES false true stop_cond stmt_Loop true false (A) sequence (B) selection (C) repetition
Transcript

Computational Intelligence on Automation Lab @ NCTU

UEE1302(1102) F10: Introduction to Computers

and Programming

Programming Lecture 02 Programming Lecture 02 Flow of Control Flow of Control (I):(I): Boolean Boolean

Expression and SelectionExpression and Selection

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 2

Learning ObjectivesLearning Objectives

You should be able to describe:� Relational Expressions� Logical Expressions� if-else Statement� Nested if and if Chain Statements� switch Statement � Common Programming Errors

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 3

Control StructuresControl Structures

� Flow of Control : the order in which a program’s statements are executed–Normal flow is sequential

� Selection and Repetition statements allow programmer to alter normal flow–Selection: selects a particular statement to

be executed next � selection is from a well-defined set

–Repetition: allows a set of statements to be repeated

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 4

Flow of ExecutionFlow of Execution

statement 1

statement 2

statement N

• • •

bool_expr

stmt_NO stmt_YES

false true

stop_cond

stmt_Loop

true

false

(A) sequence (B) selection (C) repetition

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 5

Relational ExpressionsRelational Expressions

� All computers are able to compare numbers–can be used to create an intelligence-like

facility� Relational Expressions: expressions used to

compare operands– format : a relational operator connecting 2

variables and/or constant operands–examples of valid relational expressions:

� age > 40

� length <= 50

� flag == donePRO_02 PROF. HUNG-PIN(CHARLES) WEN 6

Relational Operators (1/2)Relational Operators (1/2)

Math meaningC++

notationExample

= Equal to == 2*x == 7*y

≠ Not equal to != ans != ‘n’

> Greater than > income > 50000

≥ Greater than or equal to

>= age >= 18

< Less than < count < base + 10

≤ Less than or equal to

<= height <= 170

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 7

Relational Operators (2/2)Relational Operators (2/2)

� Relational Expressions (conditions):–are evaluated to yield a numerical result–condition that is true evaluates to 1–condition that is false evaluates to 0

� Example : –The relationship 2.0>3.3 is always false,

therefore the expression has a value of 0

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 8

Logical Operators (1/2)Logical Operators (1/2)

� More complex conditions can be created using basic logical operations –AND symbol: &&, –OR symbol : ||–NOT symbol : !

� AND operator, &&: –Used with 2 simple expressions–Example : (age > 40) && (term < 10)–Compound condition is true (has value of 1)

only if age > 40 and term < 10

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 9

Logical Operators (2/2)Logical Operators (2/2)

� OR operator, ||:–Used with two simple expressions–Example : (age > 40) || (term < 10)–Compound condition is true if age > 40 or

if term < 10 or if both conditions are true� NOT operator, !:

–Changes an expression to its opposite state

–If expr_A is true, then !expr_A is false

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 10

Precedence of OperationsPrecedence of Operations

Operator Associativity

!(unary), –, ++, –– right to left

*, /, % left to right

+, – left to right

<, <=, >, >= left to right

==, != left to right

&& left to right

|| left to right

=, +=, –=, *=, /= right to left

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 11

Precedence ExamplesPrecedence Examples

� Arithmetic before logical– x + 1 > 2 || x + 1 < -3 means (x + 1) > 2 || (x + 1) < -3

� Short-circuit evaluation– (x >= 0) && (y > 1)

–Be careful with increment operators!Ex: (x > 1) && (y++)

� Integers as Boolean values–All non-zero values � true–Zero value � false

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 12

DeMorgan'sDeMorgan's LawsLaws

� Two propositional logic rules–negation of conjunction : ¬(A∩B) = ¬A∪¬B

–negation of disjunction : ¬(A∪B) = ¬A∩¬B

� Suppose A and B are logical expressions– !(A && B) ⇔ (!A) || (!B)

– !(A || B) ⇔ (!A) && (!B)

� Principle of double negation– !(!A) ⇔ A

� Example: !(YourAge < Min || YourAge > Max)

⇔ (YourAge >= Min && YourAge <= Max)

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 13

Selection (I): OneSelection (I): One --WayWay ifif

� Formal syntax of one-way selection :…if (decision_maker) //no ;;;; here

action_stmt;…

– decision_maker : is a logicalexpression � decides whether to execute the action statement

–if decision_maker is true, execute action_stmt

–if decision_maker is false, bypass action_stmt

decision_maker

action_stmt

false

true

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 14

Example ofExample of OneOne--WayWay ifif

� Example 1: if (score >= 90)

grade = ‘A’;

� Example 2: absolute value…

if (iVar < 0)

iVar = -iVar;

cout << “ absolute value = “ << iVar

<< endl;

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 15

Selection (I): TwoSelection (I): Two --WayWay ifif--elseelse

� Choice of two alternate statements basedon condition expression

� Formal syntax :if (decision_maker) // no semicolon here

action_stmt_yes;else // no semicolon here

action_stmt_no;

– decision_maker: decide which one of two statements to run

–if the evaluation is true, run action_stmt_yes–if the evaluation is false, run action_stmt_no

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 16

Example ofExample of TwoTwo --WayWay ifif--elseelse

� Example 1: pass or failif (score >= 60)

cout << “Pass” << endl;else

cout << “Fail” << endl;

� Example 2: overtime payment…if (hours > 40)

pay = rate*40 + 1.5*rate*(hours-40);else

pay = rate*hours;

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 17

Compound StatementCompound Statement

� What if we want to execute multiple statements in action?

� Compound statement ( a.k.a. a block of statements):

{statement 1;statement 2;…statement n;

}

–a compound statement is treated as a single statement

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 18

Example of Compound StatementsExample of Compound Statements

if (age >= 18)

{

cout << "Eligible to vote." << endl;

cout << "No longer a minor." << endl;

}

else

{

cout << "Not eligible to vote.“ << endl;

cout << "Still a minor." << endl;

}

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 19

Nested Nested ifif

� Nesting: one control statement in another� An else is associated with the most recent if

that has not been paired with an else� Example 1: Tax Computation

…if (income > 5000000.0)

tax = income * 0.50;else

if (income > 1000000.0) tax = income * 0.30;

else if (income > 500000.0)

tax = income * 0.20;else

tax = income * 0.10; …

p21

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 20

Avoid Excessive IndentationAvoid Excessive Indentation

� Use if chain instead of nested if� Example 2: Grading

if (score >= 80.0)

grade = ‘A’;

else if (score >= 70.0)

grade = ‘B’;

else if (score >= 60.0)

grade = ‘C’;

else

grade = ‘F’;

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 21

Compare Compare ifif Chain and Multiple Chain and Multiple ifif

� if Chainif (month == 1)

cout<<“Jan”<<endl;

else if (month == 2)

cout<<“Feb”<<endl;

else if (month == 3)

cout<<“Mar”<<endl;

eles if (month == 11)

cout<<“Nov”<<endl;

else

cout<<“Dec”<<endl;

� Multiple ifif (month == 1)

cout<<“Jan”<<endl;if (month == 2)

cout<<“Feb”<<endl;if (month == 3)

cout<<“Mar”<<endl; …if (month == 11)

cout<<“Nov”<<endl; if (month == 12)

cout<<“Dec”<<endl;

Question: What’s the difference??

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 22

Common Pitfalls on Common Pitfalls on ifif--elseelse

� Operator "=" vs. operator "=="–"assignment“ versus “equality"

� Example: What’s the problem??if (age = 20)

cout<<“Happy 20-year old birthday”<<endl;

else

…………

� Using “=” instead of ”==” in the if-elsestatement causes the most difficult errors–Hard to debug due to no error message

� Nested if statements needs braces {} to clearly indicate the desired structure

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 23

Selection (II): Selection (II): ?:?:

� Conditional operator (?:?:?:?:) takes three arguments (ternary)–equivalent to if-else

� Syntax for the conditional operator:var = expr_1 ? expr_2 : expr_3;

–if expr_1 is true, assign expr_2 to var–if expr_1 is false, assign expr_3 to var

� Ex: bool taxable = (age >=18) ? true:false;

� Exercise: how to rewrite the tax computationexample by using (?:)

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 24

Selection (III): Selection (III): switch switch (1/2)(1/2)

� A new stmt for controlling multiple branches� Syntax format:

switch ( control_expr )

{ // start of compound statement

case literal_1 : //<-terminated with a colon

statement_1;

statement_2;

break;

case literal_2 : //<-terminated with a colon

statement_3;

break;

default : //<-terminated with a colon

statement_n;

} // end of switch and compound stmt

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 25

Selection (III): Selection (III): switchswitch (2/2)(2/2)

� Four new keywords used:– switch, case, default and break

� Function:– control_expr following switch is evaluated� must compare to an literal

–Result compared sequentially to alternative case values until a match is found

–Statements following matched case are executed

–When break reached, switch terminates–If no match found, run default statement

blockPRO_02 PROF. HUNG-PIN(CHARLES) WEN 26

Rewrite Month ExampleRewrite Month Example

� Using if Chainif (month == 1)

cout<<“Jan”<<endl;

else if (month == 2)

cout<<“Feb”<<endl;

else if (month == 3)

cout<<“Mar”<<endl;

eles if (month == 11)

cout<<“Nov”<<endl;

else

cout<<“Dec”<<endl;

� Using switchswitch (month){

case 1:cout<<“Jan”<<endl; break;

case 2:cout<<“Feb”<<endl; break;

…case 11:

cout<<“Nov”<<endl; break;

default:cout<<“Dec”<<endl;

}

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 27

Common Pitfalls on Common Pitfalls on switchswitch

� Forgetting break;–No compiler error–Execution simply falls through other cases

until break; –Ex: if month is equal to 13 in the previous

example, screen still displays " Dec"

� Best usage: Menus–Provides clearer big-picture view–Shows menu structure effectively–Each branch is one menu choice

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 28

switchswitch Menu ExampleMenu Example

switch (response){

case ‘1’:// Execute menu option 1break;

case ‘2’:// Execute menu option 2break;

case ‘3’:// Execute menu option 3break;

default:cerr << "Please enter a valid response.";

}

� Good habit to enumerate all known cases and prompt by cerr if unknown case occurs

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 29

Cable Bill ExerciseCable Bill Exercise

� This programming exercise calculates a customer’s bill for a local cable company

� Residential customer rates:– Bill processing fee: $4.50– Basic service fee: $20.50– Premium channel: $7.50 per channel

� Business customer rates:– 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

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 30

RequirementsRequirements

� Ask user for account number and customer code

� Assume R or r stands for residential customer and B or b stands for business customer

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 31

Input and OutputInput 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

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 32

Program Analysis (1/2)Program Analysis (1/2)

� 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

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 33

Program Analysis (2/2)Program Analysis (2/2)

� 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

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 34

Algorithm DesignAlgorithm 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

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 35

VariablesVariables

// variable to store customer’s account #int accountNumber;

// variable to store customer codechar customerType;

// variable to store # of subscribed// premium channels int numOfPremChannels;

// variable to store # of basi// connectionsint numOfBasicServConn;

// variable to store the billing amountdouble amountDue;

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 36

Named ConstantsNamed Constants

// for residential customersconst double RES_BILL_PROC_FEES = 4.50;const double RES_BASIC_SERV_COST = 20.50;const double RES_COST_PREM_CHANNEL = 7.50;

// for business customersconst double BUS_BILL_PROC_FEES = 15.00;const double BUS_BASIC_SERV_COST = 75.00;const double BUS_BASIC_CONN_COST = 5.00;const double BUS_COST_PREM_CHANNEL = 50.00;

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 37

Bill Formulas (1/2)Bill Formulas (1/2)

Residential customers:

amountDue = RES_BILL_PROC_FEES

+ RES_BASIC_SERV_COST

+ numOfPremChannels

* RES_COST_PREM_CHANNEL;

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 38

Bill Formulas (2/2)Bill Formulas (2/2)

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;

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 39

Main Algorithm (1/3)Main Algorithm (1/3)

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. Prompt user to enter account number3. Get customer account number4. Prompt user to enter customer code5. Get customer code (r, R, b, or B)

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 40

Main Algorithm (2/3)Main Algorithm (2/3)

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

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 41

Main Algorithm (3/3)Main Algorithm (3/3)

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 and exit.

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 42

Summary (1/3)Summary (1/3)

� Boolean expressions can be composed of relational and/or logical operations

� Relational Expressions (conditions): –Are used to compare operands–A condition that is true has a value of 1–A condition that is false has a value of 0

� More complex conditions can be constructed from relational expressions using logicaloperators, && (AND), || (OR), and ! (NOT)–Apply DeMorgan’s Law properly

PRO_02 PROF. HUNG-PIN(CHARLES) WEN 43

Summary (2/3)Summary (2/3)

� if-else statements select between two alternative statements based on the value of an expression

� if-else statements can contain other if-elsestatements � nested if

–If braces are not used, each else statement is associated with the closest unpaired if

� if chain: a multi-way selection statement–Each else statement (except for the final

else) is another if-else statement� Compound statement: any # of individual

statements enclosed within braces {}PRO_02 PROF. HUNG-PIN(CHARLES) WEN 44

Summary (3/3)Summary (3/3)

� Condition operator (?:): equivalent to if-else–Ternary: takes three arguments

� switch statement: multi-way selection–the value of an integer expression is

compared to a sequence of integer or character constants or constant expressions (literals)

–program execution transferred to first matching case

–execution continues until optional breakstatement is encountered


Recommended