COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.

Slides:



Advertisements
Similar presentations
Decisions If statements in C.
Advertisements

Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering.
Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
CONTROL STRUCTURES: SEQUENTIAL, SELECTIVE, AND REPETITIVE
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
C++ for Engineers and Scientists Third Edition
COS120 Software Development Using C++ AUBG Fall semester 2010
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Computer Science Selection Structures.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CPS120: Introduction to Computer Science Decision Making in Programs.
Selection Structures: if and switch Statements Chapter 4.
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 Conditions Logical Expressions Selection Control Structures Chapter 5.
A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.
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.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: 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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Introduction to branching.
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 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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Controlling Program Flow with Decision Structures.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
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.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
The if…else Selection Statement
Chapter 3 Control Statements
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
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Structured Program
Chapter 7 Conditional Statements
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Decision I (if Statement)
Boolean Expressions to Make Comparisons
Chapter 4: Selection Structures: if and switch Statements
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot Koffman, Course lecturer: Assoc. Prof. Stoyan Bonev, PhD

Lecture 10: Control Flow. Selection (decision) structures

3 Lecture Contents: t Quiz #2 on Skills in C++ Functions t The if statement (then version) t The if statement (then – else version) t Nested if...else statements versus sequence of if statements t Demo programs t Exercises

4 Quiz #2 on Skills in C++ Functions

5 The if statement (then version) Syntax and flowchart fragment: if ( ) ;

6 The if statement (then – else version) Syntax and flowchart fragment: if ( ) ; else ;

7 Nested if…else statements vs. sequence of if statements t Nested if … else … statements. t Example: ambiguity with two ifs and one else clause // increment n_pos, n_zero, n_neg // depending on the value of x if (x > 0)n_pos = n_pos + 1; if (x < 0)n_neg = n_neg + 1; else n_zero = n_zero + 1; t The rule: An else is matched with the last if that doesn’t have its own else.

8 Nested if…else statements vs. sequence of if statements t Nested if … else … statements. The rule: An else is matched with the last if that doesn’t have its own else. Example: // increment n_pos, n_zero, n_neg // depending on the value of x if (x > 0)n_pos = n_pos + 1; else if (x < 0)n_neg = n_neg + 1; else n_zero = n_zero + 1;

9 Nested if…else statements vs. sequence of if statements t Sequence of if statements Example: // increment n_pos, n_zero, n_neg // depending on the value of x if ( x > 0 )n_pos = n_pos + 1; if ( x < 0 )n_neg = n_neg + 1; if ( x == 0 )n_zero = n_zero + 1; // less efficient version because all // three conditions are always tested

10 Else If clause A variation of the IF…THEN…ELSE statement uses several conditions with ELSE and IF keywords: if (condition1) action1 else if (condition2) action2 else if (condition3) action3 else action4 Any number of ELSE IF clauses is permitted. The conditions are evaluated from the top, and if one of them is True, the corresponding block of statements (action I ) is executed. The ELSE clause will be executed if none of the previous expressions is True. Example comes on next slide.

11 Else If clause Score = InputBox(“Enter score:”) if (score < 60) Result = “Fail”; else if (score < 75) Result = “Pass”; else if (score < 90) Result = “Very good”; else Result = “Excellent”;

12 Else If clause The order of comparisons is vital in an IF…THEN…ELSE IF… statements. Try to switch the first two conditions of the last page code and you may get quite unexpected results if (score < 75) Result = “Pass”; else if (score < 60) Result = “Fail”; else if (score < 90) Result = “Very good”; else Result = “Excellent”; Let’s assume score is 48. The first condition checked (48<75) will return True and it will assign “Pass” to Result, and then it will skip the other remaining clauses. ERROR in the algorithm implemented! A student can’t pass a test with grade < 60. MORAL: Be careful and test your code if it uses ELSE IF clauses.

13 Muiltiple IF…THEN… structures versus Else If clause After True condition is found, C++ executes the associated stmts and skips the remaining clauses. It continues program execution with stmt immediately after last ELSE clause. All following ELSE IF clauses are skipped, and the code runs a bit faster. That’s why the complicated ELSE IF structure should be preferred to the equivalent series of simple IF… statements shown below: if (score < 60) Result = “Fail”; if (score < 75) Result = “Pass”; if (score < 90) Result = “Very good”; if (score >=90) Result = “Excellent”; C++ will evaluate the conditions of all the IF stmts, even if the score is less than 50.

14 More on if statement(s) Extract from Friedman/Koffman, chapter 4

Selection Structures: if and switch Statements Chapter 4

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

Logical Expressions

18 Boolean Variables t bool variable t Included with C++ compiler bool leapYear; leapYear = true;// Non zero return value leapYear = false;// Zero return value

19 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 // _____

20 Logical Expressions –Logical expressions often use these relational operators:

21 Logical Operators t Logical operator (&& means AND) used in an if...else statement: ( (tryIt >= 50) && (tryIt <= 1500) ) t Logical operator (| | means OR) used in an if...else statement: ( (tryIt 1500) )

22 Using && t Assume tryIt = 90, t Is tryIt within the range of 50 and 1500 ? ( (tryIt >= 50) && (tryIt <= 1500) ) ( ( 90 >= 50) && ( 90 <= 1500) ) ( 1 && 1 ) 1

23 Using || t Assume tryIt = 99 t Is tryIt outside the range of 50 and 1500 ? ( (tryIt 1500) ) ( ( ) ) ( 0 || 0 ) 0

24 Truth Tables for Boolean Operators t Truth tables for Logical operators !, ¦¦, && – ! means unary NOT /negation/ operator – && means binary AND /conjunction/ operator – ¦¦ means binary OR /disjunction/operator –1 is a symbol for true, 0 is a symbol for false

25 Bit-wise logical operators t &- bit wise AND operator t |- bit wise OR operator

26 De Morgan laws t In logic, De Morgan's laws (or De Morgan's theorem) are rules in formal logic relating pairs of dual logical operators in a systematic manner expressed in terms of negation. The relationship so induced is called De Morgan duality.logicformal logiclogical operatorsnegation t Augustus De Morgan originally observed that in classical propositional logic the following relationships hold: Augustus De Morganpropositional logic t not (P and Q) = (not P) or (not Q) t not (P or Q) = (not P) and (not Q)

27 Boolean Algebra t Full set of boolean binary functions ArgsFunctions a e a b n o o d r r

28 Boolean Algebra t Minimal /basic/ set of boolean functions –Negation or logical not not a!a –Conjunction or logical multiplication a and ba && b –Disjunction or logical addition a or ba || b

29 Boolean Algebra t Exclusive OR formulated through basic functions t a  b = (not a and b) or (a and not b) t a  b = (!a && b) || (a && !b)

30 Precedence of Operators

31 Boolean Assignment bool same; same = true; Form:variable = expression; Example:same = (x = = y);

Introduction to the if Dependent Control Statement –The if is the first statement that alters strict sequential control. –General form if ( logical-expression ) true-part ; logical-expression: any expression that evaluates to nonzero (true) or zero (false). In C++, almost everything is true or false.

33 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 if ( logical-expression ) true-part ; else false-part ;

34 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

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

37 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; }

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.

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

40 Example of nested logic if(x > 0) numPos = numPos + 1; else if(x < 0) numNeg = NumNeg + 1; else numZero = numZero + 1;

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

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

43 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; }

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

45 Short Circuit Evaluation (single == ‘y’ && gender == ‘m’ && age >= 18) –If single is false, gender and age aren’t evaluated (single == ‘y’ || gender == ‘m’ || age >= 18) –If single is true, gender and age are not evaluated

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

47 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

48 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"; }

49 Exercise 10.1 Build programs based on branch algorithms: t To add, subtract, multiply, and divide two integer values checking the valid divisor (!=0) condition

50 Exercise 10.2 Build programs based on branch algorithms: t To associate noise loudness with the effect of noise using a table data: Loudness in decibels(db)Perception 50 or lowerquiet 51-90annoying very annoying Above 110uncomfortable

51 Exercise 10.3 Build programs based on branch algorithms:  To implement nested if statements using sample flow chart algorithms

52 Exercise 10.4 Build programs based on branch algorithms:  To compute area of a triangle by Heron’s formulae

53 Exercise 10.5 Build programs based on branch algorithms:  To test an integer value as a valid leap year (divisible by 4 but not by 100, except that years divisible by 400)

54 Exercise 10.6 Build programs based on branch algorithms:  To find roots (solutions) of a linear equation bx + c = 0

55 Exercise 10.7 Build programs based on branch algorithms: t To find roots (solutions) of a quadratic equation ax 2 + bx + c = 0

56 Before lecture end Lecture: Control Flow. Selection (decision) structures More to read: Friedman/Koffman, Chapter 04

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman

58 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Objectives Become familiar with selection statements Compare numbers, characters, and strings Use relational, equality, and logical operators Write selection statements with one or two alternatives Select among multiple choices

59 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.1 Control Structures Regulate the flow of execution Combine individual instructions into a single logical unit with one entry point and one exit point. Three types: sequential, selection, repetition

60 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sequential Execution Each statement is executed in sequence. A compound statement is used to specify sequential control: { statement 1 ; statement 2 ;. statement n ; }

61 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.2 Logical Expressions C++ control structure for selection is the if statement. E.g.: if (weight > ) shipCost = 10.00; else shipCost = 5.00;

62 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relational and Equality Operators Logical expressions (conditions) are used to perform tests for selecting among alternative statements to execute. Typical forms: variable relational-operator variable variable relational-operator constant variable equality-operator variable variable equality-operator constant Evaluate to Boolean (bool) value of true or false

63 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.1 Rational and Equality Operators

64 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example x x <= 0 -5 true

65 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example xy x >= y -5 false 7 7

66 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operators && (and) || (or) ! (not) Used to form more complex conditions, e.g. (salary 5) (temperature > 90.0) && (humidity > 0.90) winningRecord && (!probation)

67 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.3 && Operator

68 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.4 || Operator

69 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.5 ! Operator

70 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.6 Operator Precedence

71 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example flagxyz false x + y / z <= false

72 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example flagxyz false ! flag || (y + z >= x - z) true

73 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.7 English Conditions as C++ Expressions

74 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing Characters and Strings Letters are in typical alphabetical order Upper and lower case significant Digit characters are also ordered as expected String objects require string library –Compares corresponding pairs of characters

75 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.8 Examples of Comparisons

76 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Boolean Assignment Assignment statements have general form variable = expression; E.g.: (for variable called same of type bool) same = true; same = (x == y);

77 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Additional Examples inRange = (n > -10) && (n < 10); isLetter = ((‘A’ <= ch) && (ch <= ‘Z’)) || ((‘a’ <= ch) && (ch <= ‘z’)); even = (n % 2 == 0);

78 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Writing bool Values Boolean values are represented by integer values in C++ –0 for false –non-zero (typically 1) for true Outputting (or inputting) bool type values is done with integers

79 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.3 The if Control Structure Allows a question to be asked, e.g. “is x an even number.” Two basic forms –a choice between two alternatives –a dependent (conditional) statement

80 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if Statement with Two Alternatives Form: if (condition) statement T else statement F E.g.: if (gross > ) net = gross - tax; else net = gross;

81 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.4 Flowchart of if statement with two alternatives

82 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if Statement with Dependent Statement When condition evaluates to true, the statement is executed; when false, it is skipped Form:if (condition) statement T E.g.:if (x != 0) product = product * x;

83 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.5 Flowchart of if statement with a dependent

84 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.4 if Statements with Compound Alternatives Uses { } to group multiple statements Any statement type (e.g. assignment, function call, if) can be placed within { } Entire group of statements within { } are either all executed or all skipped when part of an if statement

85 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example 4.11 if (popToday > popYesterday) { growth = popToday - popYesterday; growthPct = * growth / popYesterday; cout << “The growth percentage is “ << growthPct; }

86 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example 4.11 (continued) if (transactionType == ‘c’) {// process check cout << “Check for $” << transactionAmount << endl; balance = balance - transactionAmount; } else {// process deposit cout << “Deposit of $” << transactionAmount << endl; balance = balance + transactionAmount; }

87 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Program Style Placement of { } is a stylistic preference Note placement of braces in previous examples, and the use of spaces to indent the statements grouped by each pair of braces.

88 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Tracing an if Statement Hand tracing (desk checking) is a careful step-by-step simulation on paper of how the computer would execute a program’s code. Critical step in program design process Attempts to verify that the algorithm is correct Effect shows results of executing code using data that are relatively easy to process by hand

89 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.9 Step-by-Step Hand Trace of if statement

90 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Decision Steps in Algorithms Algorithm steps that select from a choice of actions are called decision steps Typically coded as if statements

91 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: 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.

92 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Analysis The problem data include the input data for hours worked and hourly pay and two required outputs, gross pay and net pay. There are also several constants: the union dues ($15), the minimum weekly earnings before dues must be paid ($100), the maximum hours before overtime must be paid (40), and the overtime rate (1.5 times the usual hourly rate). With this information, we can begin to write the data requirements for this problem. We can model all data using the money (see Section 3.7) and float data types.

93 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Data Requirements Problem Constants MAX_NO_DUES = DUES = MAX_NO_OVERTIME = 40.0 OVERTIME_RATE = 1.5

94 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Data Requirements Problem Input float hours float rate Problem Output float gross float net

95 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: 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.

96 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.6 Structure chart for payroll problem

97 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Initial Algorithm 1.Display user instructions (function instructUser). 2.Enter hours worked and hourly rate. 3.Compute gross pay (function computeGross). 4.Compute net pay (function computeNet). 5.Display gross pay and net pay.

98 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: instructUser Function Global constants - declared before function main MAX_NO_DUES DUES MAX_NO_OVERTIME OVERTIME_RATE

99 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: instructUser Function Interface –Input Arguments none –Function Return Value none –Description Displays a short list of instructions and information about the program for the user.

100 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeGross Function Interface –Input Arguments float hours float rate –Function Return Value float gross

101 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeGross Function Formula Gross pay = Hours worked  Hourly pay Local Data float gross float regularPay float overtimePay

102 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeGross Function - Algorithm 3.1 If the hours worked exceeds 40.0 (max hours before overtime) Compute regularPay Compute overtimePay Add regularPay to overtimePay to get gross Else Compute gross as house * rate

103 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeNet Function Interface –Input Arguments float gross –Function Return Value float net Formula net pay = gross pay - deductions Local Data float net

104 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeNet Function - Algorithm 4.1 If the gross pay is larger than $ Deduct the dues of $15 from gross pay Else Deduct no dues

105 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions

106 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

107 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

108 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

109 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

110 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.2 Sample run of payroll program with functions

111 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Global Constants Enhance readability and maintenance –code is easier to read –constant values are easier to change Global scope means that all functions can reference

112 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Identifier Scope Variable gross in main function Local variable gross in function computeGross. No direct connection between these variables.

113 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Flow Information and Structure Charts Shows which identifiers (variables or constants) are used by each step If a step gives a new value to a variable, it is consider an output of the step. If a step uses the value of an variable without changing it, the variable is an input of the step. Constants are always inputs to a step.

114 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Software Development Method 1. Analyze the problem statement 2. Identify relevant problem data 3. Use top-down design to develop the solution 4. Refine subproblems starting with an analysis similar to step 1

115 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.6 Checking Algorithm Correctness Verifying the correctness of an algorithm is a critical step in algorithm design and often saves hours of coding and testing time

116 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example - Trace of Payroll Problem 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 Compute gross as hours * rate.

117 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example - Trace of Payroll Problem 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.

118 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.7 Nested if Statements and Multiple-Alternative Decisions Nested logic is one control structure containing another similar control structure E.g. one if statement inside another Makes it possible to code decisions with several alternatives

119 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example of Nested Logic if (x > 0) numPos = numPos + 1; else if (x < 0) numNeg = numNeg + 1; else// x must equal 0 numZero = numZero + 1;

120 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example of Nested Logic XnumPosnumNegnumZero 3.0_____________________ -3.6_____________________ 0_____________________ Assume all variables initialized to 0

121 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparison of Nested if to Sequence of if Statements if (x > 0) numPos = numPos + 1; if (x < 0) numNeg = numNeg + 1; if (x == 0) numZero = numZero + 1;

122 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.

123 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Multiple-Alternative Decision Form if (condition 1 ) statement 1 ; else if (condition 2 ) statement 2 ;. else if (condition n ) statement n ; else statement e ;

124 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Multiple-Alternative Example if (x > 0) numPos = numPos + 1; else if (x < 0) numNeg = numNeg + 1; else numZero = numZero + 1;

125 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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; }

126 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Order of Conditions Matters 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;

127 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.12 Decision Table for Example 4.16

128 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.4 Function computeTax

129 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Short Circuit Evaluation (single == ‘y’ && gender == ‘m’ && age >= 18) –If single is false, gender and age are not evaluated (single == ‘y’ || gender == ‘m’ || age >= 18) –If single is true, gender and age are not evaluated

130 Thank You For Your Attention!