Computational Intelligence on Automation Lab @ NCTU UEE1302(1102) F10: Introduction to Computers and Programming Programming Lecture 02 Flow of Control (I): Boolean Expression and Selection Learning Objectives You should be able to describe: Relational Expressions Logical Expressions if- Statement Nested if and if Chain Statements switch Statement Common Programming Errors PRO_02 PROF. HUNG-PIN(CHARLES) WEN 2 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 statement 1 statement 2 statement N Flow of Execution false stmt_no bool_expr true stmt_yes true stop_cond false stmt_loop (A) sequence (B) selection (C) repetition PRO_02 PROF. HUNG-PIN(CHARLES) WEN 3 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 4
Relational 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 == done PRO_02 PROF. HUNG-PIN(CHARLES) WEN 5 Math Relational Operators (1/2) meaning C++ notation Example = 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 6 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 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 7 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 8
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 Precedence of Operations Operator!(unary),, ++, Associativity 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 9 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 10 Precedence 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 11 DeMorgan's Laws 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 12
Selection (I): One-Way if Example of One-Way if false decision_ maker true action_stmt Formal syntax of one-way selection : if (decision_maker) //no ; here action_stmt; decision_maker : is a logical expression decides whether to execute the action statement if decision_maker is true, execute action_stmt if decision_maker is false, bypass action_stmt 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 13 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 14 Selection (I): Two-Way if- Choice of two alternate statements based on condition expression Formal syntax : if (decision_maker) // no semicolon here action_stmt_yes; // 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 Example of Two-Way if- Example 1: pass or fail if (score >= 60) cout << Pass << endl; cout << Fail << endl; Example 2: overtime payment if (hours > 40) pay = rate*40 + 1.5*rate*(hours-40); pay = rate*hours; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 15 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 16
Compound 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 Example of Compound Statements if (age >= 18) { } { } cout << "Eligible to vote." << endl; cout << "No longer a minor." << endl; cout << "Not eligible to vote. << endl; cout << "Still a minor." << endl; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 17 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 18 Nested if Nesting: one control statement in another An is associated with the most recent if that has not been paired with an Example 1: Tax Computation if (income > 5000000.0) tax = income * 0.50; if (income > 1000000.0) tax = income * 0.30; if (income > 500000.0) tax = income * 0.20; tax = income * 0.10; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 19 p21 Avoid Excessive Indentation Use if chain instead of nested if Example 2: Grading if (score >= 80.0) grade = A ; if (score >= 70.0) grade = B ; if (score >= 60.0) grade = C ; grade = F ; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 20
Compare if Chain and Multiple if Question: What s the difference?? if Chain if (month == 1) cout<< Jan <<endl; if (month == 2) cout<< Feb <<endl; if (month == 3) cout<< Mar <<endl; eles if (month == 11) cout<< Nov <<endl; cout<< Dec <<endl; Multiple if if (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; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 21 Common Pitfalls on if- Operator "=" vs. operator "==" "assignment versus equality" Example: What s the problem?? if (age = 20) cout<< Happy 20-year old birthday <<endl; Using = instead of == in the if- statement 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 22 Selection (II):?: Selection (III): switch (1/2) Conditional operator (?:?:) takes three arguments (ternary) equivalent to if- 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 computation example by using (?:) PRO_02 PROF. HUNG-PIN(CHARLES) WEN 23 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; case literal_2 : //<-terminated with a colon statement_3; default : //<-terminated with a colon statement_n; } // end of switch and compound stmt PRO_02 PROF. HUNG-PIN(CHARLES) WEN 24
Selection (III): switch (2/2) Rewrite Month Example 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 block Using if Chain if (month == 1) cout<< Jan <<endl; if (month == 2) cout<< Feb <<endl; if (month == 3) cout<< Mar <<endl; eles if (month == 11) cout<< Nov <<endl; cout<< Dec <<endl; Using switch switch (month) { case 1: cout<< Jan <<endl; case 2: cout<< Feb <<endl; case 11: cout<< Nov <<endl; default: cout<< Dec <<endl; } PRO_02 PROF. HUNG-PIN(CHARLES) WEN 25 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 26 Common Pitfalls on switch Forgetting No compiler error Execution simply falls through other cases until 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 switch Menu Example switch (response) { case 1 : // Execute menu option 1 case 2 : // Execute menu option 2 case 3 : // Execute menu option 3 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 27 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 28
Cable 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 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 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 29 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 30 Input: Input and Output Customer account number Customer code Number of premium channels For business customers, number of basic service connections Output: Customer s account number Billing amount 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 31 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 32
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 33 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 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 34 Variables // variable to store customer s account # int accountnumber; // variable to store customer code char customertype; // variable to store # of subscribed // premium channels int numofpremchannels; // variable to store # of basi // connections int numofbasicservconn; Named Constants // for residential customers const 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 customers const 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; // variable to store the billing amount double amountdue; PRO_02 PROF. HUNG-PIN(CHARLES) WEN 35 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 36
Residential customers: Bill Formulas (1/2) Business customers: Bill Formulas (2/2) amountdue = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + numofpremchannels * RES_COST_PREM_CHANNEL; if (numofbasicservconn <= 10) amountdue = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST + numofpremchannels * BUS_COST_PREM_CHANNEL; 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 37 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 38 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 number 3. Get customer account number 4. Prompt user to enter customer code 5. Get customer code (r, R, b, or B) 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 39 PRO_02 PROF. HUNG-PIN(CHARLES) WEN 40
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 41 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 logical operators, && (AND), (OR), and! (NOT) Apply DeMorgan s Law properly PRO_02 PROF. HUNG-PIN(CHARLES) WEN 42 Summary (2/3) if- statements select between two alternative statements based on the value of an expression if- statements can contain other if- statements nested if If braces are not used, each statement is associated with the closest unpaired if if chain: a multi-way selection statement Each statement (except for the final ) is another if- statement Compound statement: any # of individual statements enclosed within braces {} PRO_02 PROF. HUNG-PIN(CHARLES) WEN 43 Summary (3/3) Condition operator (?:): equivalent to if- 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 break statement is encountered PRO_02 PROF. HUNG-PIN(CHARLES) WEN 44