1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
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)
Thursday, December 14, 2006 “Would you tell me, please, which way I ought to go from here?” “That depends a good deal on where you want to get to,” said.
Chapter 4: Control Structures: Selection
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Selection Structures (if & switch statements) (CS1123)
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.
CONTROLLING PROGRAM FLOW
CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
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.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
1 Three C++ Looping Statements Chapter 7 CSIS 10A.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Chapter 5: Structured Programming
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
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.
CHAPTER#3 PART1 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc.
CHAPTER 1.3 THE OPERATORS Dr. Shady Yehia Elmashad.
Chapter 4 Selection: the if-else and switch-case instructions.
Overview Go over parts of quiz? Another iteration structure for loop.
Chapter#3 Part1 Structured Program Development in C++
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Week 4 Program Control Structure
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.
COMP Loop Statements Yi Hong May 21, 2015.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
A First Book of C++ Chapter 4 Selection.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Branching statements.
Chapter 3 Selection Statements
The if…else Selection Statement
Selection (also known as Branching) Jumail Bin Taliba by
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Relational Operators A relational operator compares two values. The values can be any built-in C++ data type, such as Character Integer Floating point.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 7 Conditional Statements
Chapter 4: Control Structures I (Selection)
Structured Program Development in C++
CSC215 Lecture Control Flow.
Presentation transcript:

1 SELECTION using IF and IF-ELSE Chapter 4

2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls

3 Review: Standard Program Structure To solve most problems, your main() program will generally look like this (conceptually) 1.Declare variables for input, result and intermediate data 2.Ask for data (cout) 3.Input data (cin) 4.Calculate result 5.Output result (cout)

4 Simple Flow of Control Flow of control The order in which statements are executed Sequential The normal default flow…one line after the other Conditional (or Branch, or Selection) Lets program choose between one or more alternatives Loop (or Iteration) Lets program repeat a block of statements many times

5 Which way to go? Conditional statements allow execution of certain statements only if a particular condition is satisfied Consider these statements as some kind of a gate keeper that allows entry only if a condition is satisfied

6 Who are these gatekeepers ? There are two types of conditional statements : The if Statement The if…else Statement

7 Agenda Background One Way selection (if)  Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls

8 The plain old if… The if statement allows conditional execution What does this mean ? Consider this …. You get an award only if you get a perfect score on a test if (score == 100) cout<< “Congratulations!”;

9 if statement syntax if (condition) statement ; Condition – is a logical expression like score == 100 x+y>10 ans!=‘y’ Statement – is any executable statement like cout<<“Congrats!”; OR x = x + 50;

10 How it works The if statement first evaluates the condition… for example… if (score == 100) cout<< “Congratulations!”; if score is 100 then the condition evaluates to true so it displays a Congratulations! message if score is not 100, it skips to the next line…no output

11 One-Way Selection Flowchart (if) score==100 true false CONGRATS! Next statement

12 Logical Expressions Logical expressions are expressions that are either true or false (4<3) (hours>40) (Length>=Width) relational operators such as ‘>’ (greater than) are used to compare variables and/or numbers

13 Relational Operators The Six Relational operators (No spaces allowed between the symbols!) < less than >greater than <= greater than or equal to >= less than or equal to == equal or equivalent (Only use on int or char) !=is not equal to(Only use on int or char) (not suitable with floats due to roundoff error) Common source of errors, don’t use one =!

14 Q1) One-Way Selection What is output from following: if (score > 65) cout<<“Pass! ”; cout<<“Congrats!”; Given a) score = 80 ____________ b) score = 40 ____________ c) score = 65 ____________

15 Agenda Background One Way selection (if) Two Way selection (if-else)  Compound Statements Nested if-else Logical operators Common pitfalls

16 The if…else statement The if…else statement selects between one of two statements. Here is the syntax of if-else: if (condition) statement1; else statement2; So how does this work ….. ? Notice: no condition here

17 How it works Again, condition is a logical expression like score > 65 statement1 and statement2 are executable, like cout<<“Congrats!”; OR x = x + 50; If condition is true then statement1 will execute Otherwise (i.e. condition is false) statement2 will execute

18 if…else Example To calculate hourly wages there are two choices Regular time ( up to 40 hours) gross_pay = rate * hours; Overtime ( over 40 hours) gets $50 bonus gross_pay = rate * ; The program must choose which of these expressions to use

19 Conditional Flowchart (if-else) hours>40 truefalse calc pay with overtime calc pay regular display pay to screen

20 Designing the Conditional Determine if (hours >40) is true If it is true, then use gross_pay = rate * ; If it is not true, then use gross_pay = rate * hours;

21 Implementing the Branch The actual C++ to do this: if (hours > 40) gross_pay = rate * ; else gross_pay = rate * hours; Notice, one condition, for two statements Notice: no condition here! “else” means “condition was false”

22 Full Application: Calculating Pay // pay.cpp int main() {float hours, pay, rate; cout << "enter hours and rate: "; cin >> hours >> rate; if (hours > 40) pay = rate * ; else pay = rate * hours; cout << "pay is " << pay; } This is Step4. Calc Result

23 Q2) Two-Way Selection What is output from the following: if (score > 60) cout<<“Pass--”; else cout<<“Fail--”; cout<<“Have a nice day!”; Given a) score = 80 ____________ b) score = 40 ____________ c) score = 60 ____________

24 Q3) Two-Way Selection What is output from the following: if (score = 100) cout<<“Congrats!”; else cout<<“Nice try”; Given a) score = 100 ____________ b) score = 80 ____________

25 Application of 2-Way Selection //cost.cpp see p67-68 Use for Problem 10 int number, cost; cout << "Number purchased: "; cin >> number; if (number < 5) cost = 12 * number; else cost = 10 * number; cout << number << " baseballs cost $" << cost;

26 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements  Nested if-else Logical operators Common pitfalls

27 Compound Statements A compound statement is more than one statement enclosed in { } Branches of if or if-else statements often need to execute more that one statement Example: if (condition) { statements for true } else { statements for false }

28 Example with two if-else statements if (hours > 40.0) pay = 40.0 * rate + 50; else pay = hours * rate; cout << "pay is " << pay; if (hours > 40.0) cout << " overtime worked"; else cout << " no overtime worked";

29 Above redone (simplified) with compound statements if (hours > 40.0) { pay = 40.0 * rate + 50; cout << " pay is " << pay << " overtime worked"; } else { pay = hours * rate; cout << " pay is " << pay << " no overtime"; }

30 Q4) What’s wrong with this code? if (hours > 40.0) pay = 40.0 * rate + 50; cout << " pay is " << pay << " overtime worked"; else { pay = hours * rate; cout << " pay is " << pay << " no overtime"; }

31 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else  Logical operators Common pitfalls

32 Nesting and Multi-Way Branches How to select from more than two possibilities? How to check a variable is inside a range of values? Answer: put an if-else inside if or else block …nesting if (expr1) statement1; // do if expr1 is true else // do if expr1 is false if (expr2) statement2; // expr1 false, expr2 true else statement3;// both expr1 and expr2 false

33 Nested if-else (multi-way branch) if (expr1) { block1 } else if (expr2) { block2 } else if (expr3) {block 3} else {block4} Syntax: if( grade>=90) cout<<"Your GPA is A."<<endl; else if (grade>=80) cout<<"Your GPA is B."<<endl; else if (grade>=70) cout<<"Your GPA is C."<<endl; else if (grade>=60) cout<<"Your GPA is D."<<endl; else {cout<<"Your GPA is F."<<endl; cout<<"You will cry!"<<endl;} Example:

34 Q5) What does this code produce: if( grade>=90) cout<<"GPA is A."<<endl; else if (grade>=70) cout<<"GPA is C."<<endl; else if (grade>=80) cout<<"GPA is B."<<endl; Given a) grade = 93 ____________ b) grade = 85 ____________ c) grade = 75 ____________ d) grade = 45 ____________

35 Application – Multiway Branch // suit.cpp See p75 Use for Problem 11 char suit; // 'C', 'D', 'H', or 'S' cout << "First letter of suit (C,D,H, or S): "; cin >> suit; if (suit == 'C') cout << "clubs"; else if (suit == 'D') cout << "diamonds"; else if (suit == 'H') cout << "hearts"; else if (suit == 'S') cout << "spades"; else cout << "Invalid suit";

36 Time for Break! Download Lab3If.cpp Work on 1-6, 11 You need to do 1 thru 10 for 10 points Call me over if you need help

37 Application: How to tell if n is in the correct range cout<<“Enter a number between 1 and 10”; cin>>n; if (n>=1) if (n<=10) cout<<“OK, n is between 1 and 10!”; else cout<<“n is too big”; else cout<<“n is too small”;

38 A better way using && cout<<“Enter a number between 1 and 10”; cin>>n; if (n>=1 && n <=10) cout<<“OK, n is between 1 and 10!”; else cout<<“illegal value of n”;

39 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators  Common pitfalls

40 Logical Operators AND operator: p && q OR operator: p || q NOT operator: !p Both p and q are relational expressions (like a<5) or boolean (true/false) expressions

41 Compound Conditions Logical AND means true only if both true AND operator: && p && q pq TTT TFF FTF FFF

42 Compound Conditions Logical OR means true if at least 1 is true OR operator: || p || q pq TTT TFT FTT FFF

43 Compound Conditions NOT operator: ! !p p TF FT

44 Compound Condition Example int main() { int n1, n2, n3; cout << “Enter three integers: “; cin >> n1 >> n2 >> n3; if (n1 <= n2 && n1 <= n3) cout << “Minimum is “ << n1 << endl; if (n2 <= n1 && n2 <= n3) cout << “Minimum is “ << n2 << endl; if (n3 <= n1 && n3 <= n2) cout << “Minimum is “ << n3 << endl; }

45 OR Example int main() { char ans; cout << “Are you enrolled (y/n): ”; cin >> ans; if ( ans == ' Y ' || ans == ' y ' ) cout <<“You are enrolled.\n”; else cout << “You are not enrolled.\n”; } This will accept both ‘Y’ and ‘y’ as an answer

46 YOUR TURN 6. T/F ( 3 7) 7. T/F ! ( 2 > 3 ) 8. T/F (25 = = 25 ) || ( 2 > 3 ) 9. the expression: ( number > 10 && number < 40 ) is TRUE, when a) number is larger than 40 b) number is smaller than 10 c) number is between 10 and 40 d) Never

47 Agenda Background One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else Logical operators Common pitfalls 

48 Common Pitfalls in Selection/Logic Dangling else Using = instead of == Forgetting { } around multiple statement blocks Not testing your proposed solution using simple test data values Trying to solve all at once…a mess! Better: build up solution step by step: see p79-82 Read/steal code examples from text noted on handout If stuck, start small, do drill exercises, then tackle programs

49 Dangling Else A subtle bug possibility When you nest a single-choice if in a 2-choice if: if (cond1) if (cond2) statement1; else statement2; Q: Which if does the else belong to? A: the closest one above it

50 Dangling else…continued Compiler really interprets above like this: if (cond1) if (cond2) statement1; else statement2; Single choice if Two choice if No matter how you type it!

51 Dangling else…end A good idea to avoid confusion, put { } around both choices of two-choice if if (cond1) { if (cond2) statement1; } else {statement2; } Now it’s clear how to interpret it!

52 Go back home proud ! You’re a C++ programmer !

53 A1) One-Way Selection What is output from following: if (score > 65) cout<<“Pass! ”; cout<<“Congrats!”; Given a) score = 80 Pass! Congrats! b) score = 40 Congrats! c) score = 65 Congrats!

54 A2) Two-Way Selection What is output from the following: if (score > 60) cout<<“Pass--”; else cout<<“Fail--”; cout<<“Have a nice day!”; Given a) score = 80 Pass--Have a nice day! b) score = 40 Fail--Have a nice day! c) score = 60 Fail--Have a nice day!

55 A3) Two-Way Selection What is output from the following: if (score = 100) cout<<“Congrats!”; else cout<<“Nice try”; Given a) score = 100 Congrats! b) score = 80 Congrats! (due to bug) Bug! Use ==

56 A4) What’s wrong with this code? if (hours > 40.0) pay = 40.0 * rate + 50; cout << " pay is " << pay << " overtime worked"; else { pay = hours * rate; cout << " pay is " << pay << " no overtime"; } Need { }

57 A5) What does this code produce: if( grade>=90) cout<<"GPA is A."<<endl; else if (grade>=70) cout<<"GPA is C."<<endl; else if (grade>=80) cout<<"GPA is B."<<endl; Given a) grade = 93 A b) grade = 85 C c) grade = 75 C d) grade = 45 nothing

58 YOUR TURN 6. F ( 3 7) 7. T ! ( 2 > 3 ) 8. T (25 = = 25 ) || ( 2 > 3 ) 9. the expression: ( number > 10 && number < 40 ) is TRUE, when a) number is larger than 40 b) number is smaller than 10 c) number is between 10 and 40  d) Never