Selection Structures: if and switch Statements Chapter 4.

Slides:



Advertisements
Similar presentations
CONTROL STRUCTURES: SEQUENTIAL, SELECTIVE, AND REPETITIVE
Advertisements

Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
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 4 Making Decisions
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
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.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Lecture 10: Control Flow. Selection (Decision) structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
7-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
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.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
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.
Selection Structures: if and switch Statements. 2 Selection Statements –In this chapter we study statements that allow alternatives to straight sequential.
Chapter 4 Control Structures: Selection We introduced the three fundamental control structures from which all programs are developed: 1. Sequence structures.
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 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
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.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
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.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Branching statements.
Chapter 3 Selection Statements
Chapter 4: Control Structures I (Selection)
Chapter 3 Control Statements
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.
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.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Chapter 4: Control Structures I (Selection)
Chapter 7 Selection Computing Fundamentals with C++ 3rd Edition
Chapter 7 Conditional Statements
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
Decision I (if Statement)
Chapter 4: Selection Structures: if and switch Statements
Branching statements Kingdom of Saudi Arabia
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

Selection Structures: if and switch Statements Chapter 4

2 Selection Statements –In this chapter we study statements that allow alternatives to straight sequential processing. In particular: if statements (do this only if a condition is true) if-else statements (do either this or that) Logical expressions (evaluate to true or false) Boolean operators (not: ! and: && or: ||)

3 4.1 Control Structures –Programs must often anticipate a variety of situations. –Consider an Automated Teller Machine: ATMs must serve valid bank customers. They must also reject invalid PINs. The code that controls an ATM must permit these different requests. Software developers must implement code that anticipates all possible transactions.

4 4.1 Control Structures t Type of control structures –Sequence (compound statements) { Statment1; Statement2; … } –Selection (this chapter) Choose among several alternatives Typically decisions are made dynamically –Repetition

5 4.2 Logical Expressions (Conditions)

6 Boolean Variables t bool variable t Declaration and execution statements bool leapYear; leapYear = true;// Non zero return value leapYear = false;// Zero return value

7 Boolean Expressions Examples (Write T for True, or F for False): int n1 = 55; int n2 = 75; n1 < n2 // _____ n1 > n2 // _____ (n1 + 35) > n2 // _____ (n1-n2) < 0.1// _____ n1 == n2 // _____

8 Logical Expressions –Logical expressions often use these relational operators: > Greater than < Less than >= Greater than or equal <= Less than pr equal == Equal (Note: it is not the assignment operator =) != Not equal

9 Logical Operators t Logical operator (&& means AND) used in an if...else statement: ( (tryIt >= 0) && (tryIt <= 100) ) t Logical operator (| | means OR) used in an if...else statement: ( (tryIt >= 0) | | (tryIt <= 100) )

10 Using && t Assume tryIt = 90, t Is tryIt within the range of 0 and 100 ? ( (tryIt >= 0) && (tryIt <= 100) ) ( ( 90 >= 0) && ( 90 <= 100) ) ( 1 && 1 ) 1

11 Using && t Assume tryIt = 99 t Is tryIt outside the range of 0 and 100 ? ( (tryIt 100) ) ( ( ) ) ( 0 ¦¦ 0 ) 0

12 Truth Tables for Boolean Operators t Truth tables Logical operators !, ¦¦, && –1 is a symbol for true –0 is a symbol for false

13 Precedence of Operators t Precedence: most operators are evaluated (grouped) in a left-to-right order: – a / b / c / d is equivalent to (((a/b)/c)/d) t Assignment operators group in a right-to- left order so the expression – x = y = z = 0.0 is equivalent to (x=(y=(z=0.0)))

14 Precedence of Operators

15 Precedence of Operators t Examples bool flag = false; int a = b = c = 0; !flag || (a+b < c – a) 0+0 < < 0 false !false || false true || false  true  Parentheses are sometimes restrictive

16 Comparing characters and strings t Characters –Based on their ASCII code (lexicographic) –Examples ‘a’ < ‘c’true ‘A’ < ‘a’true ‘7’ < ‘3’ false t Strings –Based on characters –Examples “XXX” ‘A’) “bed” != “beds”true “bed” < “beds”true (prefix)

17 Boolean Assignment bool same, isLetter; char c Form: variable = expression; Example: same = (x = = y); IsLetter = ((‘A’ <= c) && (c <=‘Z’)) || ((‘a’ <= c) && (c <=‘z’))

Introduction to the if Control Statement –The “if” is the first statement that alters strict sequential control. –General form: one alternative if ( logical-expression ) true-part ; logical-expression: any expression that evaluates to nonzero (true) or zero (false).

19 if Control Statements with Two Alternatives –The logical expression is evaluated. When true, the true-part is executed and the false-part is disregarded. When the logical expression is false, the false-part executes. –General Form: two alternatives if ( logical-expression ) true-part ; else false-part ;

20 What happens when an if statement executes? After the logical expression of the if statement evaluates, the true-part executes only if the logical expression was true. gross >100.0 False net=gross-tax net=gross True

21 if statement with Characters and Strings t Example for Character if(momOrDad == ‘m’) cout << “Hi mom” << endl; else cout << “Hi Dad” << endl; t Example for Strings pos = myString.find(“aaa”) if(( 0 <= pos ) && (pos < myString.length())) cout << “aaa found at position ” << pos << endl; else cout << “could not finf aaa!” << endl;

22 Programming Tip t Using = for == is a common mistake. For example the following statements are legal: t int x = 25; Because assignment statements evaluate to the expression on the right of =, x = 1 is always 1, which is nonzero, which is true: if (x = 1) // should be (x == 1)

if Statements with Compound Alternatives –General form (also known as a block): { statement-1 ; statement-2 ;... statement-N ; } –The compound statement groups together many statements that are treated as one.

24 Writing Compound Statements if (transactionType == 'c') { // process check cout << "Check for $" << transactionAmount << endl; balance = balance - transactionAmount; } else { // process deposit cout << "Deposit of $" << transactionAmount << endl; balance = balance + transactionAmount; }

Decision Steps in Algorithms t Algorithm steps that select from a choice of actions are called decision steps. The algorithm in the following case contains decisions steps to compute an employee’s gross and net pay after deductions. The decision steps are coded as if statements. t Payroll Case Study

26 Decision Steps in Algorithms t Statement: Your company pays its hourly workers once a week. An employee’s pay is based upon the number of hours worked (to the nearest half hour) and the employee’s hourly pay rate. Weekly hours exceeding 40 are paid at a rate of time and a half. Employees who earn over $100 a week must pay union dues of $15 per week. Write a payroll program that will determine the gross pay and net pay for an employee.

27 Decision Steps in Algorithms t Analysis: Input – Input data float hours // Number worked hours money rate // hourly pay –Output data money gross // gross pay money net // net pay –Constants DUES = // union dues MAX_NO_DUES = // maximum weekly earnings without dues MAX_NO_OVERTIME = 40.0 // maximum hours without overtime pay OVERTIME_RATE = 1.5 // rate for overhours –We model all data using the money and float data types.

28 Decision Steps in Algorithms  Program Design: The problem solution requires that the program read the hours worked and the hourly rate before performing any computations. After reading these data, we need to compute and then display the gross pay and net pay. The structure chart for this problem (Figure 4.6) shows the decomposition of the original problem into five subproblems. We will write three of the subproblems as functions. For these three subproblems, the corresponding function name appears under its box in the structure chart.

29 Decision Steps in Algorithms –1. Display user instructions Function: void instructUser() Displays the used constants and prompts for input –2. Enter hours worked and hourly rate. –3. Compute gross pay Function: float computeGross(float hours, money rate) If worked hours exceed 40 compute and return overtime pay + regular pay Else compute and return hours * rate –4. Compute net pay Function: money computeNet(money gross) If gross pay is larger than $100 deduct the dues $15 from gross pay Else no deduction –5. Display gross pay and net pay. Print instructions Enter data Compute gross pay Compute net pay Original Problem (stepwise refinement) Print results

30 PayrollFunctions.cpp // File: payrollFunctions.cpp // Computes and displays gross pay and net pay // given an hourly rate and number of hours // worked. Deducts union dues of $15 if gross // salary exceeds $100; otherwise, deducts no // dues. #include #include "myMoney.h"

31 PayrollFunctions.cpp using namespace std; // Functions used void instructUser(); money computeGross(float, money); money computeNet(money); //Constants const money MAX_NO_DUES = ; const money dues = 15.00; const float MAX_NO_OVERTIME = 40.0; const float OVERTIME_RATE = 1.5;

32 PayrollFunctions.cpp int main () { float hours; float rate; money gross; money net; // Display user instructions. instructUser();

33 PayrollFunctions.cpp // Enter hours and rate. cout << "Hours worked: "; cin >> hours; cout << "Hourly rate: "; cin >> rate; // Compute gross salary. gross = computeGross(hours, rate); // Compute net salary. net = computeNet(gross);

34 PayrollFunctions.cpp // Print gross and net. cout << "Gross salary is " << gross << endl; cout << "Net salary is " << net << endl; return 0; }

35 PayrollFunctions.cpp // Displays user instructions void instructUser() { cout << "This program computes gross and net salary." << endl; cout << "A dues amount of " << dues << " is deducted for" << endl; cout << "an employee who earns more than " << MAX_NO_DUES << endl << endl; cout << "Overtime is paid at the rate of " << OVERTIME_RATE << endl;

36 PayrollFunctions.cpp cout << "times the regular rate for hours worked over " << MAX_NO_OVERTIME << endl << endl; cout << "Enter hours worked and hourly rate" << endl; cout << "on separate lines after the prompts. " << endl; cout << "Press after typing each number." << endl << endl; } // end instructUser

37 PayrollFunctions.cpp // FIND THE GROSS PAY money computeGross (float hours, money rate) { // Local data... money gross; money regularPay; money overtimePay; // Compute gross pay. if (hours > MAX_NO_OVERTIME) { regularPay = MAX_NO_OVERTIME * rate;

38 PayrollFunctions.cpp overtimePay = (hours - MAX_NO_OVERTIME) * OVERTIME_RATE * rate; gross = regularPay + overtimePay; } else gross = hours * rate; return gross; } // end computeGross

39 PayrollFunctions.cpp // Find the net pay money computeNet (money gross) { money net; // Compute net pay. if (gross > MAX_NO_DUES) net = gross - DUES; else net = gross; return net; } // end computeNet

40 Payroll.cpp Program output This program computes gross and net salary. A dues amount of $15.00 is deducted for an employee who earns more than $ Overtime is paid at the rate of 1.5 times the regular rate on hours worked over 40 Enter hours worked and hourly rate on separate lines after the prompts. Press after typing each number.

41 Payroll.cpp Program output Hours worked: 50 Hourly rate: 6 Gross salary is $ Net salary is $315.00

Checking the Correctness of an Algorithm t Verifying the correctness of an algorithm is a critical step in algorithm design and often saves hours of coding and testing time.  We will now trace the execution of the refined algorithm for the payroll problem solved in the last section.

43 Checking the Correctness of an Algorithm 1. Display user instructions. 2. Enter hours worked and hourly rate. 3. Compute gross pay If the hours worked exceed 40.0 (max hours before overtime) Compute regularPay Compute overtimePay Add regularPay to overtimePay to get gross. else

44 Checking the Correctness of an Algorithm Compute gross as hours * rate. 4. Compute net pay If gross is larger than $ Deduct the dues of $15.00 from gross pay. else Deduct no dues. 5. Display gross and net pay.

45 Trace of the Payroll Algorithm 1. Display instructions ????Display 2. Enter data 3010Read 3. If hours > 40 False 1.Gross gets hours*rate 300False-Part 4. If gross > 100True 1.Deduct dues 285Net pay 5. Display results300 and 285 hoursrategrossnetEffect

Nested if Statements and Multiple Alternative Decisions –Nested logic is one control structure containing another similar control structure. –An if...else inside another if...else. e.g. (the 2nd if is placed on the same line as the 1st):

47 Example of nested logic if(x > 0) numPos = numPos + 1; else if(x < 0) numNeg = NumNeg + 1; else numZero = numZero + 1;  3 Alternatives  Second “if” is the false-part of the first one

48 Example of nested logic XnumPos numNegnumZero 3.0_____________________ -3.6_____________________ 0_____________________ Assume all variables initialized to 0

49 Nested if Statements versus Seequence of if Statements if(x > 0) numPos = numPos + 1; if(x < 0) numNeg = NumNeg + 1; if (x == 0) numZero = numZero + 1;  Less readable  Less efficient

50 Writing a Nested if as a Multiple-Alternative Decision  Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult to determine the logical structure of the if statement.

51 t Improve readability for complex nested if-statements t Form: if(condition 1) stat 1; else if(condition 2) stat 2; …. else if(condition N) stat N; else stat N+1; Multiple-Alternative Decision Our Example: if(x > 0) numPos = numPos + 1; else if(x < 0) numNeg = NumNeg + 1; else numZero = numZero + 1;

52 Function displayGrade void displayGrade ( int score) { if (score >= 90) cout << "Grade is A " << endl; else if (score >= 80) cout << "Grade is B " << endl; else if (score >= 70) cout << "Grade is C " << endl; else if (score >= 60) cout << "Grade is D " << endl; else cout << "Grade is F " << endl; }

53 Order of Conditions if (score >= 60) cout << " Grade is D " << endl; else if (score >= 70) cout << " Grade is C " << endl; else if (score >= 80) cout << " Grade is B " << endl; else if (score >= 90) cout << " Grade is A " << endl; else cout << " Grade is F " << endl;

54 Implementing Decision Tables Using Nested If Statements SalaryTax , % 15, to 29, % 30, to 49, % 50, to 79, % 80, to 150, % money computeTax(money salary) { if(salary < 0.00) tax = -1; else if(salary < ) tax = 0.15 * salary; else if(salary < ) tax = 0.16 * salary; else if(salary < ) tax = 0.18 * salary; else if(salary < ) tax = 0.20 * salary; else if(salary < ) tax = 0.25 * salary; elsetax = -1; return tax; }

55 Short Circuit Evaluation if (single == ‘y’ && gender == ‘m’ && age >= 18) –If single==‘y’ is false, gender and age are not evaluated if (single == ‘y’ || gender == ‘m’ || age >= 18) –If single==‘y’ is true, gender and age are not evaluated if (x != 0 && y/x> 18.0) –If x is 0, no division is performed –This avoids a potential run-time error (division by zero) if (y/x > 18.0 && x != 0) –Reversing the two subexpressions leads to a run-time error!  Short Circuit Evaluation has two main advantages: It can promote efficiency (not all parts have to be executed) It may be used to avoid run-time errors

The switch Control Statement t If the condition in a nested if statement is based on a single variable, the switch statement can be used instead t Example: if(momOrDad == ‘m’ || momOrDad == ‘M’) cout << “Hi Mom” << endl; else if(momOrDad == ‘d’ || momOrDad == ‘D’) cout << “Hi Dad” << endl;  This may transformed to a switch statement, since the condition includes only one variable ‘momOrDad’

57 General Form of a switch Control Statement switch ( switch-expression ) { case value-1 : statement(s)-1 break ;... // many cases are allowed case value-n : statement(s)-n break ; default : default-statement(s) }

58 Switch Control –When a switch statement is encountered, the switch-expression is evaluated. This value is compared to each case value until switch-expression == case value. All statements after the colon ‘:‘ (and before the ‘break’) are executed –It is important to include the break statement

59 Example switch Statement: switch(momOrDad) { case ‘m’: case ‘M’: cout << “Hi Mom” << endl; break; case ‘d’: case ‘D’: cout << “Hi Dad” << endl; break; }  No default is used  default: cout << “invalid input!” << endl;

60 Example switch Statement switch(watts) { case 25: cout << " Life expectancy is 2500 hours. " << endl; break; case 40: case 60: cout << " Life expectancy is 1000 hours. " << endl; break; case 75: case 100: cout << " Life expectancy is 750 hours. " << endl; break; de fault: cout << "Invalid bulb !!" << endl; } // end switch

61 Trace the previous switch –Show output when watts = '?'____________? watts = ’40’____________? watts = ’10'____________? watts = ’200'____________? watts = ’100'____________?

62 Remarks to switch Statements t The types float and string are not allowed as labels! t Use switch statements to make your program more readable and not vice versa t For example, if your program tends to include many statements for each case, then pack these statements in different functions in order to promote readability (although sacrificing some efficiency).

63 Return vs break t Example: void f(int someVariable) { switch(someVariable) { case value1: doSomething-1; return; case value2: doSomething-2; return; … } // end switch statement(s); // only executed when break is used return; } // end function f  return (within the switch) enforces an immediate return to the calling function (e.g. main()). The last statement(s) are NOT executed!  If break is used instead, the last statement(s) are executed!

Common Programming Errors t Failing to use { and } if(Grade >= 3.5) // The true-part is the first cout only cout <<"You receive an A !!!"; cout <<"You made it by " << (Grade-3.5) << " points"; else >>>

65 Common Programming Errors t There are no compile time errors next, but there is an intent error. else cout << "Sorry, you missed an A. "; cout << "You missed it by " << 3.5-Grade << " points"; t With the above false part, you could get this confusing output (when Grade = 3.9): You received an A !!!. You made it by 0.4 points.You missed it by -0.4 points

66 Corrected Version: if(Grade >= 3.5) { cout << "You received an A !!! " << endl; cout << "You made it by " << (Grade-3.5) << " points"; // Do other things if desired } else { cout << " You did NOT receive an A !!! "; cout << "You missed it by " << (3.5-Grade) <<" points"; }