1 / 35

Selection

Selection. Chapter 6. Objectives. Expand on introduction to structures Examine if statement in more detail Study use of switch statement to implement multialternative selections Observe use of boolean expressions for modeling logical circuits

hyland
Télécharger la présentation

Selection

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Selection Chapter 6

  2. Objectives • Expand on introduction to structures • Examine if statement in more detail • Study use of switch statement to implement multialternative selections • Observe use of boolean expressions for modeling logical circuits • Study architecture of typical computer systems • First look at class mutator methods C++ An Introduction to Computing, 3rd ed.

  3. Introductory Example • Consider Big 10 Conference mascots • Univ. of Illinois Fighting Illini • Ohio State Univ. Buckeyes . . . • We seek a mascot() function • Given name of a university • Returns name of mascot C++ An Introduction to Computing, 3rd ed.

  4. Objects, Operations Operations • Compare university to "Michigan State";if true, return "Spartans" • Compare university to "Ohio State";if true, return "Buckeyes" . . . C++ An Introduction to Computing, 3rd ed.

  5. Algorithm • if university is "Illinois" return "Fighting Illini", • Otherwise if university is "Ohio State" return "Buckeyes", • Otherwise if … • Note function source code, Figure 6.1 • Driver program, Figure 6.2 • Sample run C++ An Introduction to Computing, 3rd ed.

  6. Single branchif (boolean_exp) statement Dual branchif (boolean_exp) statement1 else statement2 Multibranchif (boolean_exp) statementelse if (boolean_exp) statementelse if … Selection: the if Statement C++ An Introduction to Computing, 3rd ed.

  7. Selection: the if Statement • Note multibranch if • Appears to be a different version • Actually is an if statement with anotherif statement as the statement of the elseif (boolean_exp) statementelse if (boolean_exp) statementelse if … C++ An Introduction to Computing, 3rd ed.

  8. Cond1 F T Cond2 Stmt1 T F . . . Stmt2 CondN T F StmtN StmtN+1 The Multi-branch if • The if’s final form has a nested if as Statement2: if (Cond1) Stmt1 else if (Cond2) Stmt2 ... else if (CondN) StmtN else StmtN+1 C++ An Introduction to Computing, 3rd ed.

  9. Multibranch if • Note which else goes with which if C++ An Introduction to Computing, 3rd ed.

  10. In a nested if statement, an else is matched with the nearest preceding unmatched if. The Dangling else Problem • Consider:if (x > 0) if (y > 0) z = sqrt (x) + sqrt(y); else cerr << " * * Unable to Compute * *"; • Which if does the else go with? C++ An Introduction to Computing, 3rd ed.

  11. Warning: Confusing = and == • True and false in C++ • An integer value of 0 interprets as false • A non zero value interprets as true • Assignments are expressions x = 7; • The value is assigned to the variable … and • The expression has a value (the value assigned) • What happens when you writeif (x = 7) … C++ An Introduction to Computing, 3rd ed.

  12. Warning: Confusing = and == • When you writeif (x = 7) … • The value is assigned to the variable • The expression has that value (in this case non zero) • The value of the expression is used to select the true or false branch of the if statement • The program will • Compile and run without crashing • But will probably not execute as expected C++ An Introduction to Computing, 3rd ed.

  13. Selection: The switch Statement • Consider an extension to the problem of Chapter 4 • Temperature Conversions • Generalize the problem • User chooses which conversion is to be performed C++ An Introduction to Computing, 3rd ed.

  14. Objects, Operations Operations: • Display prompts, MENU on the screen • Read temperature (a double) from the keyboard • Read conversion (a char) from the keyboard • Select conversion function corresponding to conversion, apply it to temperature C++ An Introduction to Computing, 3rd ed.

  15. Algorithm • Display menu via cout • Read conversion from cin • Display prompt for temperature via cout • Read temperature from cin • If conversion is 'A' or 'a' Convert from F to C, store in resultOtherwise if conversion is 'B' Convert from C to F, store in result. . .Otherwise display an error message C++ An Introduction to Computing, 3rd ed.

  16. Drawback The multi-branch if has non-uniform execution time: Menu option 'A' requires 1 comparison Menu option 'B' requires 2 comparisons ... Menu option 'F' requires 6 comparisons • Computations that are “later” in the if take longer. • There are situations where the time to select one of many statements must be uniform. C++ An Introduction to Computing, 3rd ed.

  17. Coding and Testing • C++ switch statement provides more convenient way to do this • Note source code, Figure 6.3 • Sample run for Figure 6.3 • Note convenience of the switch statement C++ An Introduction to Computing, 3rd ed.

  18. Keywords Int or char expression Each StatementList usually ends with a break or return statement. Each caseList is one or more cases of this form: case ConstantValue : The switch Statement • Form:switch (expression) { case_list1: statement_list1; case_list2: statement_list2; … default: statement_listn+1;} C++ An Introduction to Computing, 3rd ed.

  19. Warning C++ switch statements exhibit drop-through behavior. 1. Expression is evaluated. 2. If Expression == ConstantValuei: Control jumps to the Statement after ConstantValuei. 3. Control continues within the switch statement until: a. The end of the switch is reached; b. A break is executed, terminating the switch; c. A return is executed, terminating the function; or d. An exit() is executed, terminating the program. Note the use of the break statement in Figure 6.3 Note the use of the return statement in Figure 6.4 C++ An Introduction to Computing, 3rd ed.

  20. Using switch in a Function • Convert numeric codes to names • University code of 1, 2, … for "freshman", "sophomore", … • Objects • Operations • Return the name of the year corresponding to yearCode C++ An Introduction to Computing, 3rd ed.

  21. Using switch in a Function • AlgorithmIf yearCode is 1 return "Freshman"Otherwise, if yearCode is 2 return "Sophomore" . . . • View source code, Figure 6.4 • Driver program, Figure 6.5 • Sample run for Figure 6.5 C++ An Introduction to Computing, 3rd ed.

  22. Cases with No Action • In some situations the expression of a switch statement may be a legal value but: • No action takes place for that value • Solution: • Include that value in the case list • But include no statement, only the break;switch (option) {case 1 : doWhatever(); break;case 2 : doSomethingElse(); break; . . .case 9: case 10: break;} C++ An Introduction to Computing, 3rd ed.

  23. When to Use switch • Choose switch over if-else-if when: • The equality == comparison is being performed • The same expression is being compared in each condition … and … • The value to which the expression is being compared is int compatible C++ An Introduction to Computing, 3rd ed.

  24. Problem • Consider the weighting of different grades. • Tests, quizzes, etc. • Average scores calculated, multiplied by weighting factor, then added to give final weighted average • Program needed to receive averages for different types of grades will compute letter grade • HW = 20%, tests = 50%, final exam = 30% C++ An Introduction to Computing, 3rd ed.

  25. Behavior For grade calculation : Enter homework average : 80 Enter test average : 80 Enter final exam : 80 Letter grade given : B C++ An Introduction to Computing, 3rd ed.

  26. Objects, Operations Operations • Display prompt on screen • Read three quantities from keyboard • Compute weighted average • Compute letter grade • Display letter grade C++ An Introduction to Computing, 3rd ed.

  27. Grade Computation Algorithm • Prompt for homework average, test average, exam score • Enter homeworkAverage, testAverage, examScore • CalculatefinalAverage = HOMEWORK_WEIGHT * homeworkAvarage + TEST_WEIGHT * testAverage + EXAM_WEIGHT * examScore • Calculate and display letter grade corresponding to finalAverage • We will use a function to accomplish steps 3 and 4 above C++ An Introduction to Computing, 3rd ed.

  28. Function Objects, Operations Operation: Realize need for selective execution according to table: C++ An Introduction to Computing, 3rd ed.

  29. Coding, Testing • Note adjustments for use of switch • Convert weightedAverage to an int • Reduce number of casesswitch int(weightedAverage) / 10 { … • Note function source code, Figure 6.6 • Full program source code Figure 6.7 • Sample run of Figure 6.7 C++ An Introduction to Computing, 3rd ed.

  30. Conditional Expression • Form:condition ? expression1 : expression2 • Behavior • condition evaluated • If it is true, expression1 returned as result • If it false, expression2 returned as result • Try it out … what gets printed?double a = 5, b = 10, c = -3;cout << (b * b – 4 * a * c > 0 ? "real root" : "imaginary root") ; C++ An Introduction to Computing, 3rd ed.

  31. Boolean Logic and Digital Design • Based on work by George Boole • Note basic rules, pg 316 • Use of these rules became important with invention of digital computer • Circuits C++ An Introduction to Computing, 3rd ed.

  32. Boolean Logic and Digital Design • Combine to create half adder circuit • digit1, digit2, sum, and carry are all binary digits (either 0 or 1) • Note source code Figure 6.8, sample run C++ An Introduction to Computing, 3rd ed.

  33. OBJECTive Thinking:Mutator Methods • Methods which allow the programmer to change the value of an instance variable • Includes input methods • User can define an object using values read from an istream • In both types of methods we write special validation code • Ensures valid values for instance variables C++ An Introduction to Computing, 3rd ed.

  34. Mutators and Input Methods • For the class Name, Figure 6.9 • Note driver code, Figure 6.10 • Contrast accessor and output methods with mutators and input methods • Accessors retrieve attribute values • Mutators change attribute values • Accessors, output methods declared as const since they do not change attribute values • Mutators, input methods NOT declared const C++ An Introduction to Computing, 3rd ed.

  35. Mutators and Input Methods • For Sphere classvoid setRadiusAndDensity (double radius, double density); …void readRadiusAndDensity(istream& in); • See source code of Sphere.h, Figure 6.11 • Sphere.cpp, Figure 6.12 • Driver to test class sphere, Figure 6.13 C++ An Introduction to Computing, 3rd ed.

More Related