Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.

Slides:



Advertisements
Similar presentations
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Advertisements

1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection)
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
C++ for Engineers and Scientists Third Edition
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Unit 3 Lesson 8 Selection Structures Mr. Dave Clausen La Cañada High School.
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Chapter 4 Selection Structures: Making Decisions.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Flow of Control Part 1: Selection
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.
CPS120: Introduction to Computer Science Decision Making in Programs.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 4: Control Structures I (Selection)
CHAPTER 4: Selection Control Structure. Objectives  Use the relational comparison operators  Learn about AND logic  Learn about OR logic  Make selections.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
1 09/15/04CS150 Introduction to Computer Science 1 Life is Full of Alternatives Part 2.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Decision Statements, Short- Circuit Evaluation, Errors.
Conditional Control Structures Chapter 5. Goals and Objectives Understand conditional control structures. Demonstrate the use of decision structures to.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CPS120: Introduction to Computer Science Decision Making in Programs.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
 2003 Prentice Hall, Inc. All rights reserved. 1 Basic C++ Programming.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
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.
A First Book of C++ Chapter 4 Selection.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Branching statements.
Chapter 4: Control Structures I (Selection)
Chapter 3 Control Statements
More on the Selection Structure
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Chapter 4: Control Structures I (Selection)
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Chapter 4 Selection.
Chapter 6: Repetition Statements
Chapter 4: Control Structures I (Selection)
Structured Program Development in C++
Chapter 5 Selection Statements
Presentation transcript:

Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School

Objectives v v Construct and evaluate Boolean expressions v v Understand how to use selection statements to make decisions v v Design and test if statements v v Design and test if-else statements v v Design and test switch statements Dave Clausen2

3 Boolean Expressions v Selection Statements –a control statement that help the computer make decisions –Certain code is executed when the condition is true, other code is executed or ignored when the condition is false. v Control Structure –controls the flow of instructions that are executed.

Dave Clausen4 New Data Type v Simple data types that we already know –int, double, char v New simple type –bool (Boolean data type: true or false) –bool is_prime = false; –if (is_prime = = true) //not necessary to test –if (is_prime) //preferred: is_prime contains true of false

Dave Clausen5 Boolean Data Type v In older systems –0 represents false –the number 1 represents true –assign values of true or false in lowercase letters BOOLTEST_Dev.cpp

Dave Clausen6 Relational Operators, and Boolean Expressions v Relational Operators –operations used on same data types for comparison u equality, inequality, less than, greater than v Simple Boolean Expression –two values being compared with a single relational operator –has a value of true or false

Dave Clausen7 Relational Operators ArithmeticOperation = < >    Relational Operator = < > <= >= != Meaning Is equal to Is less than Is greater than less than or equal to greater than or equal to Is not equal to

Dave Clausen8 Simple Boolean Expressions 7 = = = = > < < != a = = a true false true false true

Dave Clausen9 Order of Operations 1. ( ) 2. *, /, % 3. +, - 4. = =,, =, !=

Dave Clausen10 Comparing Strings v Compared according to ASCII values –upper case < lower case (i.e. ‘A’ < ‘a’ is true) v When comparing 2 strings where one is a subset of the other (one string is shorter & contains all the same letters) –shorter string < longer string –i.e. “Alex” < “Alexander”

Dave Clausen11 Confusing = and = = v = = means equality in a comparison v = means assigning a value to an identifier v side effects are caused if we confuse the two operators P209EX1Dev.cpp

Dave Clausen12 Compound Boolean Expressions v Logical Operators –And && (two ampersands) Conjunction –Or || (two pipe symbols) Disjunction –Not ! (one exclamation point) Negation v Use parentheses for each simple expression and the logical operator between the two parenthetical expressions. –i.e. ((grade >= 80) && (grade = 80) && (grade < 90))

Dave Clausen13 Truth Tables for AND / OR Expression1Expression2E1&&E2E1||E2 (E1)(E2) truetruetruetrue truefalsefalsetrue falsetruefalsetrue falsefalsefalsefalse

Dave Clausen14 Truth Table for NOT Order of Priority for Booleans ExpressionNot E (E)!E truefalse falsetrue v Order Of Priority in Boolean Expressions –1. ! –2. && –3. ||

Dave Clausen15 Order of Operations including Booleans v 1. ( ) v 2. ! v 3. *, /, % v 4. +, - v 5., >=, = =, != v 6. && v 7. ||

Dave Clausen16 Complements v Operation v ! < v ! <= v ! > v ! >= v Complement (equivalent) v >= v>v> v <= v<v<

Dave Clausen17 DeMorgan’s Laws ! ( A && B) is the same as: !A || !B Not (true AND true) Not(true) OR Not(true) Not (true) false OR false false false false false !( A || B) is the same as: !A && !B Not( true OR true) Not(true) AND Not(true) Not( true OR true) Not(true) AND Not(true) Not (true) false AND false Not (true) false AND false false false false false

Dave Clausen18 If Statements v Format for if statements: if ( ) –Parentheses are required around the Boolean Expression. um = 0.0; sum = 0.0;cin>>number; if (number > 0.0) sum = sum + number; sum = sum + number; cout<<“the sum is: “<<sum<<endl;

Dave Clausen19 Compound Statements –Use the symbols { and } to group several statements as a single unit. –Simple statements within the compound statements end with semicolons. –Compound Statements are sometimes called a statement block. –Use compound statements in an if statement if you want several actions executed when the Boolean expression is true. MINMAXDev.cpp

Dave Clausen20 if …else Statements v Format for if…else statements if ( ) { //end of if option //end of if option}else{ //end of else option //end of else option}

Dave Clausen21 if …else Example cout. “; cin>>number; if (number < 0) { neg_count = neg_count + 1; neg_count = neg_count + 1; cout<<setw(15) << number<<endl; cout<<setw(15) << number<<endl; //end if option //end if option}else{ non_neg_count = non_neg_count + 1; non_neg_count = non_neg_count + 1; cout << setw(30) << number << endl; cout << setw(30) << number << endl; //end of else option //end of else option}

Dave Clausen22 Behavior of Selection Statements ? statement true ? statement false true false statement if ( ) {. } if ( ) else {. }

Dave Clausen23 Robust Programs v Robust Programs are protected from: –most possible crashes –bad data –unexpected values v For student programs –balance “error trapping” and code efficiency –our text assumes valid data is entered when requested.

Dave Clausen24 Nested if statements v Nested if statement (avoid this for this class) –an if statement used within another if statement where the “true” statement or action is. if (score >=50) if (score>=69.9) cout =69.9 and score>=50 cout =69.9 and score>=50else cout =69.9 true score >=50 cout =69.9 true score >=50else cout =50 cout =50

Dave Clausen25 Extended if statements –Extended if statements are Nested if statements where another if statement is used with the else clause of the original if statement. (use this for this class) if (condition 1) action1 action1 else if (condition2) action2 action2 else else action3 action3

Dave Clausen26 Avoid Sequential Selection v This is not a good programming practice. –Less efficient –only one of the conditions can be true u this is called mutually exclusive conditions if (condition1)//avoid this structure action1//use nested selection action1//use nested selection if (condition2) action2 action2 if (condition3) action3 action3 SALESDev.cpp

Dave Clausen27 Program Testing v Use test data that tests every branch or selection in the program. v Test the if statement(s) v Test the else statement(s) v Test the border, edge, extreme cases. v Test carefully nested and extended selection statements and their paths.

Dave Clausen28 Switch Statements u Allows for multiple selection that is easier to follow than nested or extended if statements. switch (age)//age is of type int { case 18: case 18: break; case 19: case 19: break; case 20: case 20: break; default: default: }

Dave Clausen29 Switch: Flow of Execution –The selector (argument) for switch must be of an ordinal type (not double) u switch (age) u The variable “age” is called the selector in our example. u If the first instance of the variable is found among the labels, the statement(s) following this value is executed until reaching the next break statement. u Program control is then transferred to the next statement following the entire switch statement. u If no value is found, the default statement is executed.

Dave Clausen30 Switch Statement Example 2 switch (grade)//grade is of type char { case ‘A’ : case ‘B’ :cout<<“Good work!”<<endl; break; case ‘C’ :cout<<“Average work”<<endl; break; case ‘D’ : case ‘F’ :cout<<“Poor work”<<endl; break; default :cout<<grade<<“ is not a valid letter grade.”; break;}

Dave Clausen31 Assertions –Assertions u A statement about what we expect to be true at a certain point in the program where the assertion is placed. u Could be used with selection, functions, and repetition to state what you expect to happen when certain conditions are true. u Could be comments, should be Boolean expressions that could be evaluated by the compiler. u Are used as preconditions and post conditions u Can be used as a proof of your program’s correctness u Can help you “debug” your program. If there is an error, the program halts with an error message and the line number where the error is located.

Dave Clausen32 Implementing Assertions v Use #include v Use #include –Example 1: assert (number_of_students != 0); class_average = sum_of_scores / number_of_students; –The parameter of assert is a Boolean Expression. –The compiler verifies if the assertion is true or false u if false, the program halts with an error message: Assertion Failed: number_of_students !=0, file “filename”, line 48 u this tells you that your assertion is false

Dave Clausen33 Assertion Example #2 v Assertions used as pre & post conditions: assert((num1>=0) && (num2>=0)); //precondition if (num1 < num2) { temp = num1; temp = num1; num1 = num2; num1 = num2; num2 = temp; num2 = temp;} assert((num1>=num2) && (num2>=0)); //postcondition

Dave Clausen34 Assert as a Debugging Tool u Executable assertions when false, terminate your program and tell you the line number where the error is located. u This is valuable during the software debugging and testing phases. u When your program is working correctly, you do not need to remove all the assertions manually. u Add the preprocessor directive: #define NDEBUG BEFORE #include to ignore all assert functions. //NDEBUG means No debug. assertDev.cpp assertDev.cpp