EGR 2261 Unit 4 Control Structures I: Selection

EGR 2261 Unit 4 Control Structures I: Selection

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 The programs youve written up to now have proceeded sequentially, executing each statement in order from the first statement to the last statement. A programs execution can also proceed: Selectively: making a choice (Chapter 4) Repetitively: looping (Chapter 5) By calling a function (Chapter 6)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 2 Control Structures (contd.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 3 Logical Expressions

Selection or repetition relies on a logical expression (also called Boolean expression) that evaluates to a value of true or false. Examples: 8 is greater than 3. Boring, because its always true. num is greater than 3. Sometimes true, sometimes false. Most logical expressions contain one or more relational operators, which are binary operators that let us compare two values. 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 The relational operators can be used with all three of our familiar 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 (contd.) Comparing char values : Example: 'R' > 'T The result of this comparison 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 (contd.) Suppose we have the following declarations: C++ Programming: From Problem Analysis to Program Design, Seventh Edition 10

One-Way Selection C++ Programming: From Problem Analysis to Program Design, Seventh Edition 11 One-Way Selection (contd.) 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 12 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 14

One-Way Selection with a Compound Statement: Example Two-Way Selection C++ Programming: From Problem Analysis to Program Design, Seventh Edition 16 Two-Way Selection (contd.) Two-way selection syntax:

If expression is true, statement1 is executed; otherwise, statement2 is executed. statement1 and statement2 can be any C++ statements. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 17 Two-Way Selection: Example

Two-Way Selection with Compound Statements: Example Multiple Selections: Nested if Recall that, in the pictures above, statement1 and statement2 can be any C++ statements. They can even be other if statements, in which case we say that were nesting if statements inside each other. See next two slides for examples. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

20 Multiple Selections: Nested if (contd.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 21 Nested ifelse Statements Versus a

Series of if Statements Heres another example: The next slide shows another (less efficient) way to accomplish the same task. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 22 Nested ifelse Statements Versus a Series of if Statements (contd.)

This code accomplishes the same task as the code on the previous slide, but its not as efficient. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 23 bool Data Type Recall that the bool data type has only two possible values: true and false. Internally, true is represented as the value 1, and

false is represented as the value 0. In fact, if you use cout to display a Boolean variable or expression, what youll see on the screen is 0 or 1 rather than true or false. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 24 Using the int Data Type Instead of bool

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. You can still use the int data type to manipulate logical (Boolean) values, but its more convenient to use the bool data type, since it lets you use the words true and false as values. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

25 Logical Operators C++s logical operators (also called Boolean operators) let you combine logical expressions. For example, you might want to check whether a variable is greater than 100 and less than 150: if (myNum > 100 && myNum < 150) C++ Programming: From Problem Analysis to Program Design, Seventh Edition

26 The ! (Not) Operator C++ Programming: From Problem Analysis to Program Design, Seventh Edition 27 The && (And) Operator C++ Programming: From Problem Analysis to Program Design, Seventh Edition

28 The || (Or) Operator C++ Programming: From Problem Analysis to Program Design, Seventh Edition 29 Precedence of Some Operators

As always, parentheses can override the normal order of evaluation. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 30 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.)

Note: The previous slide shows only some of the operators available in C++. Recall that the textbooks Appendix B (next slide) shows precedence and associativity of all C++ operators. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 31 Short-Circuit Evaluation Short-circuit evaluation: evaluation of a logical

expression stops as soon as the value of the expression is known. In certain (unusual) cases this may give surprising results. Example: Compare the following code snippets: int x = 5; if ((x >= 2) || (++x < 10)) cout << x; int x = 5; if ((++x < 10) || (x >= 2)) cout << x; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

33 Three Common Mistakes The next three slides discuss three common mistakes: 1. Confusing equality (==) with assignment (=). 2. Comparing floating-point numbers for equality. 3. Ignoring the associativity of relational

operators. Common Mistake #1: Confusing the Equality (==) and Assignment (=) Operators C++ lets you use any expression that can be evaluated to either true or false as an expression in an if statement: if (x = 5) cout << "The value is five." << endl; This statement is syntactically correct, but its 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 that usually gives surprising results. C++ Programming: From Problem Analysis to Program Design, Seventh Edition 35 Common Mistake #2: Comparing Floating-Point Numbers for Equality Comparison of floating-point numbers for equality may

not behave as you would expect, because of rounding errors. 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 36 Common Mistake #3: Ignoring Associativity of Relational Operators What we really want here is if (0 <= num && num <= 10) C++ Programming: From Problem Analysis to Program Design, Seventh Edition

37 Common Mistake #3: Ignoring Associativity of Relational Operators (contd.) Suppose num = 5: Next, suppose num = 20: C++ Programming: From Problem Analysis to Program Design, Seventh Edition

38 Program Style and Form (Revisited): Indentation A properly indented program: Shows the natural grouping of statements. Helps you spot and fix errors quickly. Two commonly used styles for braces: Each brace on a line by itself. 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 if (x > 10) { cout << x; cout << y; } if (x > 10) {

cout << x; cout << y; } 39 Alternatives to if and ifelse With if statements and ifelse 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 ifelse: The conditional operator ?: The switch structure Conditional Operator ?: The conditional operator looks like this: ?: Its the only 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 41 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 42 switch Structures Syntax is shown at right. (expression) is evaluated first, and it must evaluate to an integer (this includes char expressions). 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 43 switch Structures (contd.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition

44 switch Structures (contd.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition 45 switch Structures (contd.) 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 46

Recently Viewed Presentations

  • Measurement of phi3 with B-&gt;D0K Dalitz analysis

    Measurement of phi3 with B->D0K Dalitz analysis

    The relative phase γ (φ3) Interference between tree-level decays; theoretically clean Dalitz analysis method Measure B+/B- asymmetry across Dalitz plot Includes GLW (D0 Ks ρ0, CP eigenstate) and ADS (D0 K*+π-, DCS 2-body decay) regions D0 Ksπ+π- decay model Belle/Babar...
  • Operant Conditioning - Administration

    Operant Conditioning - Administration

    Operant Conditioning A type of learning in which behavior is strengthened if followed by reinforcement or diminished if followed by punishment. Edward Thorndike Law of Effect: rewarded behavior is likely to recur. B.F. Skinner Shaping A procedure in Operant Conditioning...
  • Galley Warfare &amp; The Rise of European Sea Power

    Galley Warfare & The Rise of European Sea Power

    Sea Power and Maritime Affairs ... Thermistocles knew why this <expletive deleted> course is important! He knew that the Persians could not fight without a seaborne supply system Mahanian Principle: "Communications dominate war" Battle of Salamis - 480 BC: The...
  • Lipids: Fats & Oils AP Biology Lipids long

    Lipids: Fats & Oils AP Biology Lipids long

    Unsaturated fats. C=C double bonds in the fatty acids. plant & fish fats . vegetable oils. liquid at room temperature. the kinks made by doublebonded C prevent the molecules from packing tightly together
  • The Biology of Behavior PowerPoint Presentation by Jim

    The Biology of Behavior PowerPoint Presentation by Jim

    Many of these areas rely on dopamine, which may be why people with low dopamine (ADHD) don't learn well from rewards, and why people who crave dopamine (ADHD, addicts, young teens, and those with . reward deficiency syndrome) are reckless...
  • Preliminary Hsc Pdhpe

    Preliminary Hsc Pdhpe

    Resting heart rate and heart rate during sub-maximal work both fall as a result of aerobic training. However, heart rate during maximal exercise will be the same for both trained and untrained individuals. The difference is that the trained person...
  • Global Business Today 9e

    Global Business Today 9e

    Learning Objectives. LO 5-1Understand the ethical issues faced by international businesses.. LO 5-2. Recognize an ethical dilemma. LO 5-3. Identify the causes of unethical behavior by managers. LO 5-4. Describe the different philosophical approaches to ethics.
  • Sample Title Slide Standard Template

    Sample Title Slide Standard Template

    Of course, it can also protect servers in the data center that have bandwidth constraints. [BUILD 7] PureDisk data for any client can be recovered in the data center. [BUILD 8] To protect the PureDisk environment in the data center,...