Unit 3 Lesson 8 Selection Structures Mr. Dave Clausen La Cañada High School.

Slides:



Advertisements
Similar presentations
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Advertisements

Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
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)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CHAPTER#3 STRUCTURED PROGRAM DEVELOPMENT IN C++ 1 st semester King Saud University College of Applied studies and Community Service Csc 1101.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Object-Oriented Programming Using C++ Third Edition Chapter 3 Making Decisions.
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.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
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.
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.
CONDITIONAL STATEMENTS OVERVIEW.  Many times we want programs to make decisions  What drink should we dispense from the vending machine?  Should we.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
CPS120: Introduction to Computer Science Decision Making in Programs.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Copyright 2003 Scott/Jones Publishing Making Decisions.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.
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#3 Part1 Structured Program Development in C++
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Week 4 Program Control Structure
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.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
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.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Program Flow Control Addis Ababa Institute of Technology Yared Semu April 2012.
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.
Branching statements.
More on the Selection Structure
Chapter 4 C Program Control Part I
Selection (also known as Branching) Jumail Bin Taliba by
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.
Chapter 4 (Conditional Statements)
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 4: Making Decisions.
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Chapter 4: Control Structures I (Selection)
Structured Program Development in C++
Chapter 5 Selection Statements
Presentation transcript:

Unit 3 Lesson 8 Selection Structures Mr. Dave Clausen La Cañada High School

Dave Clausen2 Confusing = and = = v Don’t confuse the meaning of = in Math with its meaning in C++. v The symbol = means assigning a value to an identifier, and not that two objects or expressions are “equal” in C++. v The symbol = = means equality in a comparison in C++. v Side effects are caused if we confuse the two operators. P209Ex1.cpp P209Ex1.txt

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

Dave Clausen5 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 Clausen6 Boolean Expressions v Selection Statements –a control statement that helps 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 Clausen7 Introduction to Selection Structures v Programs consist of statements that solve a problem or perform a task. v Up to this point, you have been creating programs with sequence structures. v Sequence structures execute statements one after another without changing the flow of the program. v Other structures, such as the ones that make decisions, do change the flow of the program. v The structures that make decisions in C++ programs are called selection structures. v When a decision is made in a program, a selection controls the flow of the program based on the decisions in your program.

Dave Clausen8 Use Selection Structures to Make Decisions v Selection structures are how C++ programs make decisions. v The if structure is a one-way selection structure. When a control expression in an if statement is evaluated to be true, the statements associated with the structure are executed. v The if/else structure is a two-way selection structure. If the control expression in the if statement evaluates to true, one block of statements is executed; otherwise (else), another block is executed. v The switch structure is a multi-way selection structure that executes one of many sets of statements, depending on the value of the control expression. The control expression must evaluate to an integer or character value.

Dave Clausen9 Flowcharts can illustrate program flow when using selection structures

Dave Clausen10 Using if v Many programming languages include an if structure. v Although the syntax varies among the programming languages, the if keyword is usually part of every language. v If you have used if in the other programming languages, you should have little difficulty using if in C++. v The if structure is one of the easiest and most useful parts of C++.

Dave Clausen11 If Statements v Format for if statements: if ( ) –Parentheses are required around the Boolean Expression. –The Boolean expression that makes the decision is called the control 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 Clausen12 Code List 8-1 if ( i = = 3 ) { cout << “The value of i is 3”<<endl; } v The curly brackets are not required if you only want one statement to be executed when the control expression is true.

Dave Clausen13 Figure 8-1

Dave Clausen14 Style for If Statements v For our class don’t use the books programming style of putting the brackets at the beginning and ending of the line, for example: if (i = = 3) {cout << “The value of i is 3”<<endl; } v Instead use the following format: if (i = = 3) { cout << “The value of i is 3”<<endl; }

Dave Clausen15 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. Minmax.cpp Minmax.txt

Dave Clausen16 Code List 8-2 if ( yes_no = = ‘Y’ ) { cout << “Enter the title: “; getline(cin, title); } v If you wish to have more than one line of code executed when the control expression is true, use { and } to treat the lines of code as a compound statement.

Dave Clausen17 Code List 8-3 // city.cpp city.txt city.cppcity.txtcity.cppcity.txt #include #include #include “oostring.cpp” int main () { oostring city_name; unsigned long population; cout << “What is the name of you city or town? “; getline(cin, city_name); cout << “what is the population of the city or town? ‘; cin >> population; cin.ignore(80, ‘\n’); if (population >= ) { cout << “According to estimates population figures, “; cout << city_name << “ is one of the 100 largest u.s. cities.\n”; cout << city_name << “ is one of the 100 largest u.s. cities.\n”;} return 0; }

Dave Clausen18 Errors with if Statements v Do NOT place a ; (semicolon) directly after the Boolean expression in an if statement: v Don’t do this for example: if ( i = = 3); //Don’t do this! cout<<“The value of i is 3” << endl; cout<<“The value of i is 3” << endl; v This will cause syntax and / or logic errors in your program.

Dave Clausen19 Using if/else v The if/else structure is sometimes called a two-way selection structure. v Using if/else, one block of code is executed if the control expression is true. v The else portion of the structure is executed if the control expression is false.

Dave Clausen20 Two Way Selection Structure v Figure 8-2 shows a flowchart for a two-way selection structure.

Dave Clausen21 Code List 8-4 v Consider the code fragment in Code List 8-4 if ( i < 0) { cout << “The number is negative.\n”; }else{ cout << “The number is zero or positive.\n”; }

Dave Clausen22 Code List 8-5 if (population >= ) { cout << “According to estimated population figures, ”; cout << city_name << endl; cout << “ is one of the 100 largest U.S. cities.\n”; }else{ cout << “According to estimated population figures, ”; cout << city_name << endl; cout << “ is not one of the 100 largest U.S. cities.\n”; }

Dave Clausen23 if …else Statements v Format for if…else statements if ( ) //indent 3 spaces //indent 3 spaces //end of if option //end of if optionelse //indent 3 spaces //indent 3 spaces //end of else option //end of else option

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

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

Dave Clausen26 Errors with if else Statements v Do NOT place a ; (semicolon) directly after the command else in an if else statement: v Don’t do this for example: if ( i < 0) cout << “The number is negative.\n”; else; //Don’t do this! cout << “The number is zero or positive.\n”; v This will cause syntax errors in your program.

Dave Clausen27 Nested if statements v Nested if statement –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 Clausen28 Nested if Structures v You can place if structures within other if structures. v When an if or if/else structure is placed within another if or if/else structure, the structures are said to be nested. v The flowchart in Figure 8-3 decides whether a student is exempt from a final exam based on grade average and days absent. v Don’t get your hopes up, this doesn’t work at our school!

Dave Clausen29 Figure 8-3

Dave Clausen30 Code List 8-6 v The code in Code List 8-6 is written to initially assume that the student is not exempt from the final exam. exempt_from_final = false; if (my_average >= 90) {// If your average is 90 or better if (my_days_absent <= 3)// and you have missed three days or less { exempt_from_final = true; // you are exempt (not at LCHS). }}

Dave Clausen31 Preferred Code List 8-6 v Nested if statements can be confusing, rewriting Code List 8-7 using Compound Boolean Expressions is much more clear. v I prefer that you avoid Nested if statements and use compound Boolean Expressions whenever possible. v If not, use extended if statements. if (my_average >= 90) && (my_days_absent = 90) && (my_days_absent <= 3){ exempt_from_final = true; exempt_from_final = true;}

Dave Clausen32 Figure 8-4 v Figure 8-4 shows the flowchart from Figure 8-3 expanded to include another way to be exempted from the final exam. v The new algorithm allows a student to be exempt from the exam if the student’s grade is greater than or equal to 80 AND they have only been absent from school one day or less. v This still doesn’t work at our school!

Dave Clausen33 Flowchart 8-4

Dave Clausen34 Code List 8-7 exempt_from_final = false; if (my_average >= 90) {// If you average is 90 or better if (my_days_absent <= 3)// and you have missed three days if (my_days_absent <= 3)// and you have missed three days exempt_from_final = true; // or less, you are exempt. exempt_from_final = true; // or less, you are exempt.}else{ if (my_average >= 80) if (my_average >= 80) {// If your average is 80 or better {// If your average is 80 or better if (my_days_absent <= 1)// and you have missed one day or if (my_days_absent <= 1)// and you have missed one day or exempt_from_final = true;// less, you are exempt. exempt_from_final = true;// less, you are exempt. }}

Dave Clausen35 Preferred Code List 8-7 v Nested if statements can be confusing, rewriting Code List 8-7 using Compound Boolean Expressions is much more clear. v I prefer that you avoid Nested if statements and use compound Boolean Expressions whenever possible. v If not, use extended if statements. exempt_from_final = false; if (my_average >= 90) && (my_days_absent = 90) && (my_days_absent <= 3){ exempt_from_final = true; exempt_from_final = true;} else if (my_average >= 80)&& (my_days_absent = 80)&& (my_days_absent <= 1){ exempt_from_final = true; exempt_from_final = true;}

Dave Clausen36 Code List 8-8 // deposit.cpp deposit.txt deposit.cppdeposit.txtdeposit.cppdeposit.txt #include #include int main ( ) { float amount_to_deposit; cout << “How much do you want to deposit to open the account?”; cin >> amount_to_deposit; if (amount_to_deposit < ) { if (amount_to_deposit < ) if (amount_to_deposit < ) cout << “You should consider the EconoCheck account.\n”; cout << “You should consider the EconoCheck account.\n”; else else cout << “You should consider the FreeCheck account.\n”; cout << “You should consider the FreeCheck account.\n”; }else cout << “You should consider an interest-bearing account.\n”; cout << “You should consider an interest-bearing account.\n”; return 0; }

Dave Clausen37 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. if (condition 1) action1 action1 else if (condition2) action2 action2 else else action3 action3

Dave Clausen38 Preferred Code List 8-8 // deposit2.cpp deposit2.txt deposit2.cppdeposit2.txtdeposit2.cppdeposit2.txt #include #include int main ( ) { float amount_to_deposit; cout << “How much do you want to deposit to open the account?”; cin >> amount_to_deposit; if (amount_to_deposit < ) cout << “You should consider the EconoCheck account.\n”; cout << “You should consider the EconoCheck account.\n”; else if (amount_to_deposit < ) cout << “You should consider the FreeCheck account.\n”; cout << “You should consider the FreeCheck account.\n”; else else cout << “You should consider an interest-bearing account.\n”; cout << “You should consider an interest-bearing account.\n”; return 0; }

Dave Clausen39 Revised Code List 8-4 v Let’s refine Code List 8-4 to check if the number is zero using extended if statements. if ( i < 0) cout << “The number is negative.\n”; else if (i > 0) cout << “The number is positive.\n”; cout << “The number is positive.\n”; else else cout<< “The number is zero.\n”; cout<< “The number is zero.\n”;

Dave Clausen40 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 extended selection statements action1//use extended selection statements if (condition2) action2 action2 if (condition3) action3 action3 Sales.cpp Sales.txt

Dave Clausen41 The switch Structure v So far, we have studied one-way (if) and two-way (if/else) selection structures. v C++ has another method of handling multiple options known as the switch structure. v The switch structure has many uses but is most often used with menus. –A menu is a set of options presented to the user of a program. –Code List 8-9 displays a menu of choices and asks the user to enter a number that corresponds to one of the choices. –Then a case statement is used to handle each of the options. v Nested if/else structures could be used in place of the switch structure.

Dave Clausen42 Code List 8-9 cout << “How do you want the order shipped?\n”; cout << “1 - Ground\n”; cout << “2 - 2-day air\n”; cout << “3 – Overnight air\n”; cout << “Enter the number of the shipping method you want: ”; cin >> shipping_method; switch (shipping_method) { case 1:shipping_cost = 5.00; break; break; case 2: shipping_cost = 7.50; break; break; case 3: shipping_cost = 10.00; break; break; default: shipping_cost = 0.00; default: shipping_cost = 0.00;break;}

Dave Clausen43 The switch Structure 2 v The switch structure is easier to use and a programmer is less prone to making errors that are related to braces and indentations. v Remember, however, that an integer or character data type is required in the control expression of a switch structure. v When using character types in a switch structure, enclose the characters in single quotation marks as in any other character literal. v Use a : (colon) after each case statement, not a ; (semi-colon). v The code segment in Code List 8-10 is an example of using character literals in a switch structure.

Dave Clausen44 Code List 8-10 switch (character_entered) { case ‘A’: cout << “The character entered was A, as in albatross.\n”; case ‘A’: cout << “The character entered was A, as in albatross.\n”;break; case ‘B’: cout << “the character entered was B, as in butterfly.\n”; case ‘B’: cout << “the character entered was B, as in butterfly.\n”;break; default: cout << “Invalid choice. Please enter an A or B” <<endl; default: cout << “Invalid choice. Please enter an A or B” <<endl;break;}

Dave Clausen45 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: break;}

Dave Clausen46 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 Clausen47 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 Clausen48 Errors with Switch Statements v Do NOT place a ; (semicolon) directly after the command switch in a switch structure: v Don’t do this for example: switch (character); //Don’t do this! { case ‘A’: cout << “The character entered was A.” <<endl; case ‘A’: cout << “The character entered was A.” <<endl;break; case ‘B’: cout << “the character entered was B.” <<endl; case ‘B’: cout << “the character entered was B.” <<endl;break; default: cout << “Please enter an A or B” <<endl; default: cout << “Please enter an A or B” <<endl;break;}

Dave Clausen49 Program Testing v Use test data that tests every branch or selection in the program. v Test the true 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. v Test every case in a switch statement.