Presentation is loading. Please wait.

Presentation is loading. Please wait.

Selection Chapter 6. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on introduction to structures Examine if statement in more detail Study.

Similar presentations


Presentation on theme: "Selection Chapter 6. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on introduction to structures Examine if statement in more detail Study."— Presentation transcript:

1 Selection Chapter 6

2 C++ An Introduction to Computing, 3rd ed. 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

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

4 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"... Description Software Objects TypeKindMovementName name of a univ. string varyingreceived university its mascot string varyingreturned

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

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

7 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 another if statement as the statement of the else if (boolean_exp) statement else if (boolean_exp) statement else if …

8 C++ An Introduction to Computing, 3rd ed. 8 The Multi-branch if The if ’s final form has a nested if as Statement 2 : if (Cond 1 ) Stmt 1 else if (Cond 2 ) Stmt 2... else if (Cond N ) Stmt N else Stmt N+1 Cond 1 Stmt 1 T F Stmt 2 Cond 2 TF Stmt N Cond N TF Stmt N+1...

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

10 C++ An Introduction to Computing, 3rd ed. 10 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? In a nested if statement, an else is matched with the nearest preceding unmatched if.

11 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 write if (x = 7) …

12 C++ An Introduction to Computing, 3rd ed. 12 Warning: Confusing = and == When you write if (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

13 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

14 C++ An Introduction to Computing, 3rd ed. 14 Objects, Operations Operations: i. Display prompts, MENU on the screen ii. Read temperature (a double ) from the keyboard iii. Read conversion (a char ) from the keyboard iv. Select conversion function corresponding to conversion, apply it to temperature Description Software Objects TypeKindName menu string constant MENU conversion char varying conversion temperature double varying temperature result double varying result

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

16 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.

17 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.3Figure 6.3 Sample run for Figure 6.3Sample run Note convenience of the switch statement

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

19 C++ An Introduction to Computing, 3rd ed. 19 Warning C++ switch statements exhibit drop-through behavior. 1. Expression is evaluated. 2. If Expression == ConstantValue i : Control jumps to the Statement after ConstantValue i. 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

20 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 Description Software Objects TypeKindMovementName a year code int varyingreceived yearCode name of the year string varyingreturned

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

22 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; }

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

24 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%

25 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

26 C++ An Introduction to Computing, 3rd ed. 26 Objects, Operations Description Software Objects TypeKindName homework average double varying homeworkAvarage test average double varying testAverage final-exam score double varying examScore homework weight double constant HOMEWORK_WEIGHT test weight double constant TEST_WEIGHT final-exam weight double constant EXAM_WEIGHT letter grade double constant grade Operations i. Display prompt on screen ii. Read three quantities from keyboard iii. Compute weighted average iv. Compute letter grade v. Display letter grade

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

28 C++ An Introduction to Computing, 3rd ed. 28 Function Objects, Operations Operation: Realize need for selective execution according to table: Description Software Objects TypeKindMovementName weighted average double varyingreceived (in) weightedAvarage corresponding letter grade char constantreturned (out) weightedAverage Return weightedAverage ≥ 90 A 80 ≤ weightedAverage < 90 B 70 ≤ weightedAverage < 80 C 60 ≤ weightedAverage < 70 D weightedAverage < 60 F

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

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

31 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

32 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 runFigure 6.8sample run

33 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

34 C++ An Introduction to Computing, 3rd ed. 34 Mutators and Input Methods For the class Name, Figure 6.9Figure 6.9 Note driver code, Figure 6.10Figure 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

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


Download ppt "Selection Chapter 6. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on introduction to structures Examine if statement in more detail Study."

Similar presentations


Ads by Google