Presentation is loading. Please wait.

Presentation is loading. Please wait.

TK 1914 : C++ Programming Control Structures I (Selection)

Similar presentations


Presentation on theme: "TK 1914 : C++ Programming Control Structures I (Selection)"— Presentation transcript:

1 TK 1914 : C++ Programming Control Structures I (Selection)

2 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, 201120122

3 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, 201120123

4 4

5 We have seen sequencing in C++. How do we translate selection and repetition structures into C++? FTSM :: TK1914, 201120125

6 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, 201120126

7 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, 201120127

8 8 if STATEMENT : ONE-WAY SELECTION

9 FTSM :: TK1914, 201120129

10 CLASS ACTIVITY 3.1 Refer prog03.1.cpp. 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, 2011201210

11 if-else STATEMENT: TWO- WAY 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, 2011201211

12 FTSM :: TK1914, 2011201212 if-else STATEMENT: TWO- WAY SELECTION

13 FTSM :: TK1914, 2011201213

14 CLASS ACTIVITY 3.2 Refer prog03.2.cpp. 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, 2011201214

15 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, 2011201215

16 Consider the following structure: FTSM :: TK1914, 2011201216 num = 0? print warning input num result ← sum / num num ← 10 true false COMPOUND STATEMENTS

17 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, 2011201217

18 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, 2011201218 COMPOUND STATEMENTS

19 Example: cin >> num; if (num == 0) { cout << "Invalid value!"; num = 10; } result = sum / num; FTSM :: TK1914, 2011201219 compound statement

20 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, 2011201220

21 NESTED IF Example: FTSM :: TK1914, 2011201221

22 NESTED IF Can also be written as follows (remember that the compiler ignores unnecessary whitespace characters): FTSM :: TK1914, 2011201222

23 CLASS ACTIVITY 3.3 Examine the following code: How is this code different from that in the next slide? FTSM :: TK1914, 2011201223

24 FTSM :: TK1914, 2011201224

25 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. 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, 2011201225

26 CLASS ACTIVITY 3.4 (CONT) Refer prog03.3b.cpp. 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, 2011201226

27 CLASS ACTIVITY 3.4 (CONT) Refer prog03.3c.cpp. 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 unpaired if. FTSM :: TK1914, 2011201227

28 switch STRUCTURE switch structure: alternate to if-else. Example: switch (code) { case 1: cout << "one"; case 2: cout << "two"; default: cout << "Error"; } FTSM :: TK1914, 2011201228 First, evaluate the switch expression Execute the statements inside the switch structure starting from the case which matches the value of the expression If there is no match, start from the default case

29 CLASS ACTIVITY 3.5 Refer prog03.4.cpp. 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, 2011201229

30 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, 2011201230

31 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, 2011201231

32 THE break STATEMENT The break statement may be used to jump out of a switch statement. FTSM :: TK1914, 2011201232

33 FTSM :: TK1914, 2011201233

34 CLASS ACTIVITY 3.6 Refer prog03.5.cpp. 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, 2011201234

35 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, 2011201235

36 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, 2011201236

37 FTSM :: TK1914, 2011201237

38 FTSM :: TK1914, 2011201238

39 CLASS ACTIVITY 3.7 Refer prog03.6a.cpp 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, 2011201239

40 CLASS ACTIVITY 3.7 (CONT.) Refer prog03.6b.cpp 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, 2011201240

41 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, 2011201241

42 string COMPARISON EXAMPLE Suppose we have the following declarations: string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; FTSM :: TK1914, 2011201242

43 FTSM :: TK1914, 2011201243

44 FTSM :: TK1914, 2011201244

45 FTSM :: TK1914, 2011201245

46 CLASS ACTIVITY 3.8 Refer prog03.7.cpp 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, 2011201246

47 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, 2011201247

48 FTSM :: TK1914, 2011201248

49 FTSM :: TK1914, 2011201249

50 FTSM :: TK1914, 2011201250

51 FTSM :: TK1914, 2011201251

52 CLASS ACTIVITY 3.9 Problem: FTSM :: TK1914, 20112012 52 -10050 Substance A Substance B )( ] [ put in container E1 )( ] [ put in container E1 Substance C put in container E2 put in container E2 put in container E3 put in container E4 put in container E1

53 CLASS ACTIVITY 3.9 (CONT) Refer prog03.8a.cpp 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 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, 2011201253

54 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, 2011201254

55 FTSM :: TK1914, 2011201255

56 FTSM :: TK1914, 2011201256

57 FTSM :: TK1914, 2011201257

58 FTSM :: TK1914, 2011201258

59 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, 2011201259

60 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, 2011201260

61 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, 2011201261

62 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, 2011201262

63 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, 2011201263

64 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, 2011201264

65 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, 2011201265

66 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, 2011201266

67 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, 2011201267

68 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, 2011201268

69 Formulas Billing for residential customers: amountDue = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + numOfPremChannels * RES_COST_PREM_CHANNEL; FTSM :: TK1914, 2011201269

70 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, 2011201270

71 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.Prompt user to enter account number 3.Get customer account number 4.Prompt user to enter customer code 5.Get customer code FTSM :: TK1914, 2011201271

72 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, 2011201272

73 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, 2011201273

74 SUGGESTED READING (ROYO) Chapter 4: Control structures I (Selection) FTSM :: TK1914, 20112012

75 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, 2011201275

76 YOU SHOULD NOW KNOW… relational operators using relational operators to compare string values logical operators bool variables the conditional operator FTSM :: TK1914, 2011201276


Download ppt "TK 1914 : C++ Programming Control Structures I (Selection)"

Similar presentations


Ads by Google