EGR 2261 Unit 4 Control Structures I: Selection Read Malik, Chapter 4. Homework #4 and Lab #4 due next week. Quiz next week. Control Structures • A program’s execution can proceed: – – – – In sequence. Selectively (branch): making a choice. Repetitively (iteratively): looping. By calling a function. • We’ll look at selection (branching) in Chapter 4, at repetition (iteration) in Chapter 5, and at function calls in Chapter 6. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 2 Control Structures (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 3 Logical Expressions • Selection or repetition requires evaluation of a logical (Boolean) expression that evaluates to a logical (Boolean) value of true or false. – Example of a Boolean expression: “8 is greater than 3.” • Most logical expressions contain one or more relational operators: – Allow comparisons. – Require two operands (binary). – Next slide lists the relational operators. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 4 Relational Operators C++ Programming: From Problem Analysis to Program Design, Seventh Edition 5 Relational Operators and the Simple Data Types • Relational operators can be used with all three simple data types (int, double, and char) : • Comparing int values: Example: 8 < 15 evaluates to true Example: 6 != 6 evaluates to false • Comparing double values: Example: 2.5 == 5.8 evaluates to false Example: 5.9 <= 7.5 evaluates to true C++ Programming: From Problem Analysis to Program Design, Seventh Edition 6 Relational Operators and the Simple Data Types (cont’d.) • Comparing char values : – Example: 'R' > 'T’ – Result depends on the order of the characters in the ASCII code. – From the table in Appendix C (next slide) we see that the ASCII code for 'R' is 82 and the ASCII code for 'T’ is 84. Therefore 'R' > 'T’ evaluates to false. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 7 Relational Operators and the string Type • Relational operators can also 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 they're the same through the last character of the shorter string, the shorter string is less than the longer string. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 9 Relational Operators and the string Type (cont’d.) • Suppose we have the following declarations: string string string string string str1 str2 str3 str4 str5 = = = = = "Hello"; "Hi"; "Air"; "Bill"; "Big"; C++ Programming: From Problem Analysis to Program Design, Seventh Edition 10 Relational Operators and the string Type (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 11 Relational Operators and the string Type (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 12 Relational Operators and the string Type (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 13 One-Way Selection C++ Programming: From Problem Analysis to Program Design, Seventh Edition 14 One-Way Selection (cont’d.) • One-way selection syntax: • statement is executed if the value of the expression is true. • But statement is skipped if the value is false; program goes to whatever comes next. – statement is any C++ statement. It could be a cin statement, a cout statement, an assignment statement, …. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 15 One-Way Selection: Example •Note indenting, which is for readability. Compound Statements • A compound statement (or block) is a group of statements enclosed in braces: • Such a compound statement can be used anywhere a single statement can be used. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 17 One-Way Selection with a Compound Statement: Example Two-Way Selection C++ Programming: From Problem Analysis to Program Design, Seventh Edition 19 Two-Way Selection (cont’d.) • Two-way selection syntax: • If expression is true, statement1 is executed; otherwise, statement2 is executed. – statement1 and statement2 are any C++ statements. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 20 Two-Way Selection: Example Two-Way Selection with Compound Statements: Example Multiple Selections: Nested if • Nesting: one control statement is located within another. • An else is associated with the most recent if that has not been paired with an else. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 23 Multiple Selections: Nested if (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 24 Comparing if…else Statements with a Series of if Statements • The following slide shows another (less efficient) way to accomplish the same task. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 25 Comparing if…else Statements with a Series of if Statements (cont’d.) • This code accomplishes the same task as the code on the previous slide, but it’s not as efficient. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 26 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. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 27 The int Data Type and Logical (Boolean) Expressions • Early versions of C++ did not provide a built-in bool data type. • Instead, logical values were stored in variables of the data type int, with a value of 0 representing false and any non-zero value representing true. • Can still use the int data type to manipulate logical (Boolean) values, but it’s more convenient to use the bool data type. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 28 Logical (Boolean) Operators and Logical Expressions • Logical (Boolean) operators: let you combine logical expressions. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 29 The ! (Not) Operator C++ Programming: From Problem Analysis to Program Design, Seventh Edition 30 The && (And) Operator C++ Programming: From Problem Analysis to Program Design, Seventh Edition 31 The || (Or) Operator C++ Programming: From Problem Analysis to Program Design, Seventh Edition 32 Precedence of Some Operators C++ Programming: From Problem Analysis to Program Design, Seventh Edition 33 Associativity of Operators • Of the operators shown on the previous slide, operators with the same precedence are evaluated from left to right. (They have left-to-right associativity.) • As always, parentheses can override the normal order of evaluation. • Recall that the textbook’s Appendix B (next slide) shows precedence and associativity of all C++ operators. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 34 Precedence of Operators (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 36 Precedence of Operators (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 37 Precedence of Operators (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 38 Short-Circuit Evaluation • Short-circuit evaluation: evaluation of a logical expression stops as soon as the value of the expression is known. • Example: (age >= 21) || ( x == 5) (grade == 'A') && (x >= 7) C++ Programming: From Problem Analysis to Program Design, Seventh Edition //Line 1 //Line 2 39 Three Common Mistakes •The next three slides discuss three common mistakes: 1. Comparing floating-point numbers for equality. 2. Ignoring the associativity of relational operators. 3. Confusing equality (==) with assignment (=). Comparing Floating-Point Numbers for Equality: A Precaution • Comparison of floating-point numbers for equality may not behave as you would expect. – Example: • 1.0 == 3.0/7.0 + 2.0/7.0 + 2.0/7.0 evaluates to false. • Why? 3.0/7.0 + 2.0/7.0 + 2.0/7.0 = 0.99999999999999989 • Solution: either avoid doing this, or use a tolerance value instead: – Example: if fabs(x – y) < 0.000001 C++ Programming: From Problem Analysis to Program Design, Seventh Edition 41 Associativity of Relational Operators: A Precaution What we really want here is if (0 <= num && num <= 10) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 42 Associativity of Relational Operators: A Precaution (cont’d.) • Suppose num = 5: • Next, suppose num = 20: C++ Programming: From Problem Analysis to Program Design, Seventh Edition 43 Confusion Between the Equality (==) and Assignment (=) Operators • C++ allows you to use any expression that can be evaluated to either true or false as an expression in the if statement: if (x = 5) cout << "The value is five." << endl; • This statement is syntactically correct, but it’s almost certainly not what the programmer intended. • Using = in place of == is a silent killer: – It is not a syntax error. – It is a logical error. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 44 Program Style and Form (Revisited): Indentation • A properly indented program: – Shows the natural grouping of statements. – Helps you spot and fix errors quickly. • Insert a blank line between statements that are naturally separate. • Two commonly used styles for placing braces: – On a line by themselves. – Or left brace is placed after the expression, and the right brace is on a line by itself. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 45 Alternatives to if and if…else •Using if statements and if…else statements, you can handle any decisionmaking situations that your programs may require. •But C++ does offer two other ways to do the same sort of thing. You may wish to use these instead of if and if…else: •The conditional operator ?: •The switch structure Conditional Operator ?: • The conditional operator looks like this: ?: – It’s a ternary operator: takes 3 arguments. • Syntax: expression1 ? expression2 : expression3 • If expression1 is true, the result of the entire expression is expression2. – Otherwise, the result is expression3. • Concise and efficient, but hard to read. • See next slide for example. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 47 Conditional Operator ?: (cont.) • Example: max = (a >= b) ? a : b; • The preceding statement is equivalent to the following code: if (a >= b) max = a; else max = b; C++ Programming: From Problem Analysis to Program Design, Seventh Edition 48 switch Structures • Syntax is shown at right. • (expression) is evaluated first, and it must evaluate to an integer. • Value of expression determines which corresponding action is taken. • Expression is sometimes called the selector. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 49 switch Structures (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 50 switch Structures (cont’d.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 51 switch Structures (cont’d.) • One or more statements may follow a case label. • Braces are not needed to turn multiple statements into a single compound statement. • When a case value is matched, all statements after it execute until a break is encountered. • The break statement may or may not appear after each statement. • switch, case, break, and default are reserved words. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 52