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

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

Types and Variables. Computer Programming 2 C++ in one page!
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Computer Programming 1 Problem Solving and Software Engineering.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
Chapter 4 Making Decisions
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Controlling Function Behavior Sequence, Selection and Repetition.
Flow of Control Part 1: Selection
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
Previously Repetition Structures While, Do-While, For.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Chapter 05 (Part III) Control Statements: Part II.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
TK 1914 : C++ Programming Control Structures I (Selection)
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Chapter Making Decisions 4. Relational Operators 4.1.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
Calvin College Controlling Behavior The if, switch and for Statements.
Selection Executing Statements Selectively. Review We’ve seen that the C++ if statement permits a Statement to be executed selectively: if (Expression)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Control Structures 1 The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4)
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Controlling Behavior The if and for Statements. Function Behavior The behavior of a function is determined by the statements within the function. Statements.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Chapter 3 Selection Statements
Controlling Behavior The if and for Statements.
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
Chapter 1.2 Introduction to C++ Programming
Chapter 4: Making Decisions.
The Selection Structure
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Control Structures – Selection
Control Statement Examples
Introduction to C++ Programming
Chapter 2 - Introduction to C Programming
Chapter 7 Conditional Statements
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Controlling Behavior The if and for Statements.
Introduction to C Programming
Presentation transcript:

Selection Chapter 6

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

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

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

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

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 …

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 …

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

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

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) …

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

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: 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

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

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

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.

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

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

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

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: 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

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

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

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

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

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") ;

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 runFigure 6.8sample 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.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

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