Chapter 4: Selection Structures: if and switch Statements

Slides:



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

CONTROL STRUCTURES: SEQUENTIAL, SELECTIVE, AND REPETITIVE
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
C++ for Engineers and Scientists Third Edition
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 and logical operators.
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 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
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.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Week 4 Program Control Structure
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
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.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Introduction to Control Statements IT108 George Mason University.
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)
CNG 140 C Programming (Lecture set 3)
The if…else Selection Statement
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
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
Relational Operators A relational operator compares two values. The values can be any built-in C++ data type, such as Character Integer Floating point.
The Selection Structure
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Logical Statements and Selection Structures
Control Structures – Selection
Chapter 4: Control Structures I (Selection)
Chapter 7 Additional Control Structures
Chapter 7 Conditional Statements
Chapter 6 Control Statements: Part 2
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Decision I (if Statement)
Week 3 – Program Control Structure
Life is Full of Alternatives
Control Statements Paritosh Srivastava.
Controlling Program Flow
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

Chapter 4: Selection Structures: if and switch Statements Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman

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

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

Sequential Execution Each statement is executed in sequence. A compound statement is used to specify sequential control: { statement1; statement2; . statementn; }

4.2 Logical Expressions C++ control structure for selection is the if statement. E.g.: if (weight > 100.00) shipCost = 10.00; else shipCost = 5.00;

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

Table 4.1 Rational and Equality Operators

Example x x <= 0 -5 -5 true

Example x y x >= y -5 7 -5 7 false

Logical Operators && (and) || (or) ! (not) Used to form more complex conditions, e.g. (salary < minSalary) || (dependents > 5) (temperature > 90.0) && (humidity > 0.90) winningRecord && (!probation)

Table 4.3 && Operator

Table 4.4 || Operator

Table 4.5 ! Operator

Table 4.6 Operator Precedence

Example x y z flag 3.0 4.0 2.0 false x + y / z <= 3.5 2.0 5.0 false

Example x y z flag 3.0 4.0 2.0 false ! flag || (y + z >= x - z) true 6.0 1.0 true true

Table 4.7 English Conditions as C++ Expressions

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

Table 4.8 Examples of Comparisons

Boolean Assignment Assignment statements have general form variable = expression; E.g.: (for variable called same of type bool) same = true; same = (x == y);

Additional Examples inRange = (n > -10) && (n < 10); isLetter = ((‘A’ <= ch) && (ch <= ‘Z’)) || ((‘a’ <= ch) && (ch <= ‘z’)); even = (n % 2 == 0);

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

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

if Statement with Two Alternatives Form: if (condition) statementT else statementF E.g.: if (gross > 100.00) net = gross - tax; net = gross;

Figure 4.4 Flowchart of if statement with two alternatives

if Statement with Dependent Statement When condition evaluates to true, the statement is executed; when false, it is skipped Form: if (condition) statementT E.g.: if (x != 0) product = product * x;

Figure 4.5 Flowchart of if statement with a dependent

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

Example 4.11 if (popToday > popYesterday) { growth = popToday - popYesterday; growthPct = 100.0 * growth / popYesterday; cout << “The growth percentage is “ << growthPct; }

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;

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.

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

Table 4.9 Step-by-Step Hand Trace of if statement

Decision Steps in Algorithms Algorithm steps that select from a choice of actions are called decision steps Typically coded as if statements

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.

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.

Case Study: Data Requirements Problem Constants MAX_NO_DUES = 100.00 DUES = 15.00 MAX_NO_OVERTIME = 40.0 OVERTIME_RATE = 1.5

Case Study: Data Requirements Problem Input float hours float rate Problem Output float gross float net

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.

Figure 4.6 Structure chart for payroll problem

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.

Case Study: instructUser Function Global constants - declared before function main MAX_NO_DUES DUES MAX_NO_OVERTIME OVERTIME_RATE

Case Study: instructUser Function Interface Input Arguments none Function Return Value Description Displays a short list of instructions and information about the program for the user.

Case Study: computeGross Function Interface Input Arguments float hours float rate Function Return Value float gross

Case Study: computeGross Function Formula Gross pay = Hours worked  Hourly pay Local Data float gross float regularPay float overtimePay

Case Study: computeGross Function - Algorithm 3.1 If the hours worked exceeds 40.0 (max hours before overtime) 3.1.1 Compute regularPay 3.1.2 Compute overtimePay 3.1.3 Add regularPay to overtimePay to get gross Else 3.1.4 Compute gross as house * rate

Case Study: computeNet Function Interface Input Arguments float gross Function Return Value float net Formula net pay = gross pay - deductions Local Data

Case Study: computeNet Function - Algorithm 4.1 If the gross pay is larger than $100.00 4.1.1 Deduct the dues of $15 from gross pay Else 4.1.2 Deduct no dues

Listing 4.1 Payroll problem with functions

Listing 4.1 Payroll problem with functions (continued)

Listing 4.1 Payroll problem with functions (continued)

Listing 4.1 Payroll problem with functions (continued)

Listing 4.1 Payroll problem with functions (continued)

Listing 4.2 Sample run of payroll program with functions

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

Identifier Scope Variable gross in main function Local variable gross in function computeGross. No direct connection between these variables.

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.

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

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

Example - Trace of Payroll Problem 1. Display user instructions. 2. Enter hours worked and hourly rate. 3. Compute gross pay. 3.1. If the hours worked exceed 40.0 (max hours before overtime) 3.1.1. Compute regularPay. 3.1.2. Compute overtimePay. 3.1.3. Add regularPay to overtimePay to get gross. else 3.1.4. Compute gross as hours * rate.

Example - Trace of Payroll Problem 4. Compute net pay. 4.1. If gross is larger than $100.00 4.1.1. Deduct the dues of $15.00 from gross pay. else 4.1.2. Deduct no dues. 5. Display gross and net pay.

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

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;

Example of Nested Logic X numPos numNeg numZero 3.0 _______ _______ _______ -3.6 _______ _______ _______ 0 _______ _______ _______ Assume all variables initialized to 0

Comparison of Nested if to Sequence of if Statements if (x > 0) numPos = numPos + 1; if (x < 0) numNeg = numNeg + 1; numZero = numZero + 1;

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.

Multiple-Alternative Decision Form if (condition1) statement1; else if (condition2) statement2; . else if (conditionn) statementn; else statemente;

Multiple-Alternative Example if (x > 0) numPos = numPos + 1; else if (x < 0) numNeg = numNeg + 1; else numZero = numZero + 1;

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

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;

Table 4.12 Decision Table for Example 4.16

Listing 4.4 Function computeTax

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

4.8 The switch Control Statement switch ( switch-expression ) { case label1: statements1; break; case label2: statements2; ... case labeln: statementsn; default: statementsd; // optional but highly recommended }

Switch Control Statement Alternative to multiple if statements in some cases Most useful when switch selector is single variable or simple expression Switch selector must be an integral type (int, char, bool)

Switch Control Statement Switch selector value compared to each case label. When there is an exact match, statements for that case are executed. If no case label matches the selector, the entire switch body is skipped unless it contains a default case label. break is typically used between cases to avoid fall through.

Listing 4.5 switch statement to determine life expectancy of a lightbulb

4.9 Common Programming Errors Use parentheses to clarify complex expressions Use logical operators only with logical expressions Use brackets { } to group multiple statements for use in control structures

Common Programming Errors When writing a nested if statement, use multiple-alternative form if possible if conditions are not mutually exclusive, put the most restrictive condition first Make sure switch selector and case labels are the same type. Provide a default case for a switch statement whenever possible.