Chapter 5. Selection 5-1



Similar documents
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 8 Selection 8-1

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Conditions & Boolean Expressions

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Lecture 2 Notes: Flow of Control

Conditionals (with solutions)

Object Oriented Software Design

Chapter One Introduction to Programming

ALGORITHMS AND FLOWCHARTS

Selection Statements

While Loop. 6. Iteration

6. Control Structures

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

The While Loop. Objectives. Textbook. WHILE Loops

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

Statements and Control Flow

Object Oriented Software Design

Logic in Computer Science: Logic Gates

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

Comp151. Definitions & Declarations

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

UEE1302 (1102) F10 Introduction to Computers and Programming

Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)

VB.NET Programming Fundamentals

COMPUTER SCIENCE 1999 (Delhi Board)

Chapter 5 Functions. Introducing Functions

13 Classes & Objects with Constructors/Destructors

Boolean Data Outline

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Moving from C++ to VBA

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

The if Statement and Practice Problems

C++FA 5.1 PRACTICE MID-TERM EXAM

Conditional Statements Summer 2010 Margaret Reid-Miller

Sources: On the Web: Slides will be available on:

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Boolean Expressions & the if Statement

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

if and if-else: Part 1

Intermediate Code. Intermediate Code Generation

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Gates, Circuits, and Boolean Algebra

Python Programming: An Introduction To Computer Science

I PUC - Computer Science. Practical s Syllabus. Contents

Passing 1D arrays to functions.

WESTMORELAND COUNTY PUBLIC SCHOOLS Integrated Instructional Pacing Guide and Checklist Computer Math

Boolean Logic in MATLAB

Handout #1: Mathematical Reasoning

Chapter 3 Operators and Control Flow

Informatica e Sistemi in Tempo Reale

Lecture 12: More on Registers, Multiplexers, Decoders, Comparators and Wot- Nots

Accentuate the Negative: Homework Examples from ACE

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

1. True or False? A voltage level in the range 0 to 2 volts is interpreted as a binary 1.

COMP 110 Prasun Dewan 1

Python Evaluation Rules

CHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r.

PIC 10A. Lecture 7: Graphics II and intro to the if statement

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Python Programming: An Introduction to Computer Science

CSC 221: Computer Programming I. Fall 2011

Basic Programming and PC Skills: Basic Programming and PC Skills:

Selection: Boolean Expressions (2) Precedence chart:

Adding and Subtracting Positive and Negative Numbers

Two-way selection. Branching and Looping

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script

Lecture Notes on Linear Search

Binary Adders: Half Adders and Full Adders

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

=

Common Beginner C++ Programming Mistakes

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

A.2. Exponents and Radicals. Integer Exponents. What you should learn. Exponential Notation. Why you should learn it. Properties of Exponents

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

COMBINATIONAL CIRCUITS

Writing Control Structures

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Moving from CS 61A Scheme to CS 61B Java

Compiler Construction

C H A P T E R Regular Expressions regular expression

Answers to Review Questions Chapter 7

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Flowcharting, pseudocoding, and process design

Transcription:

Chapter 5 Selection 5-1

Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow of instructions in a program. This is done using selection statements. When we make the computer choose between two alternatives we will define one of the alternatives as begin true and the other as being false. This choice will be made using a boolean expression. Boolean Expression an expression that evaluates to either true or false When boolean expressions are formed they must set up a relationship between items in the expression. This relationship is set up using a set of operators called the relational operators. Relational Operators: == (equal) < (less than) > (greater than) <= (less than or equal) >= (greater than or equal)!= (not equal) NOTE: The assignment operator is (=) but the relational operator is(= =). In other words, if you are assigning a value to a variable, use (=) but if you are asking whether two things are equal, use (= =). 5-2

Comparing Floating Point Numbers It is common to use numeric values in decision statements. Due to the way floating point numbers are stored in memory, do not compare two floating point values for equality. Floating point numbers must be rounded when they are stored in memory and rarely evaluate to be exactly the same. What we want to do is check to see if they are close enough to equal for us to call them equal. One easy method for doing this is to compare the absolute value of the difference of the numbers with some very small epsilon value. Given the following const float EPSILON = 0.00001; float val1, val2; if (fabs(val1 - val2) < EPSILON) cout << "values are equal"; fabs is a C++ library function that returns the absolute value of a floating point expression. 5-3

Examples of boolean expressions: Expression Result 5 == 5 TRUE a < c TRUE 4 + 3 > 10 FALSE 10!= 20 TRUE 6 <= 6 TRUE 5 >= 9 FALSE A < Z TRUE a < Z FALSE (WHY?) Given two variables n1 and n2, assume n1 contains 5 and n2 contains 3. Evaluate each of the following boolean expressions: n1 + 3!= n2 + 5 n1 * 2 <= n2 * 2 n1 >= n2 n2 <= n1 n2 + n1 + 3 == n1 + 6 The precedence order when the relational operators are added is as follows: * / % + - < <= > >= ==!= = Parentheses may be used to alter the order of evaluation. 5-4

The C++ If-Then and If-Then-Else Statements The use of the If-Then and If-Then-Else statements in a program allows the programmer to include all possible options in the program code and the computer to select the appropriate option during program execution. Flowchart for the If-Then statement boolean expression F T statement The boolean expression is evaluated and if it evaluates to TRUE the statement inside the If is executed and the program continues to the next executable statement. If the expression evaluates to FALSE, the statement inside the If is ignored and the program continues with the next executable statement. GENERAL FORM of the If-Then statement: if (boolean expression) statement; 5-5

hours <= 40 F T output No overtime if (hours <= 40) cout << No overtime << endl; cout << Continue << endl; Given a value of 25 in the location hours, the program would output No overtime Continue If location hours contained the value 50, the program would output Continue 5-6

Nested If-Then Statements A nested If-Then is an If-Then that contains another If-Then within it. Suppose we wanted to identify 18 year old males. We could first determine whether the age requirement was met and if so, check to see whether the individual is a male. Outer If age == 18 T F sex == M T Inner If F output The Marine Corps is looking for a few good men. if (age == 18) if (sex == M ) cout << The Marine Corps is looking for a few good men. ; 5-7

The If-Then-Else Statement In the If-Then statement a condition was evaluated and if the condition was true, an instruction was executed and the program continued on, if the condition was false, the program simply continued on. The If-Then-Else statement assures that some action will take place before the program continues. If the condition is true then do this else do that. GENERAL FORM If-Then-Else Statement if (Expression) statement 1; else statement 2; Flowchart for If-Then-Else F boolean T expression statement 2 statement 1 5-8

Example: F hours <= 40 T output overtime due output no overtime C++ code: if (hours <= 40) cout << no overtime ; else cout << overtime due ; It is possible to nest If-Then-Else statements just as we did with If-Then statements. 5-9

If-Then-Else Exercise 1.) Draw the flowchart for a program that will receive three integers from the user. Your program is to output the largest of the three. We will assume that the three values are not equal. KEEP THIS AS AN EXAMPLE OF THE CORRECT FLOWCHART STYLE FOR NESTED IF/ELSE STATEMENTS. 5-10

The Conditional Operator The conditional operator is a shortcut method that may be used to create simple if/else expressions. GENERAL FORM: Expression? expression : expression; Example: overtime = hrswkd > 40? (hrswkd-40)*rate*1.5 : 0.0; The part of the conditional expression that precedes the? is the expression to be tested (like the expression in parentheses in an if statement). If the expression is true, the statement between the? and : is executed otherwise the expression after the : is executed. The statement above could replace the block if shown below. if (hrswkd > 40) overtime = hrswkd-40) * rate * 1.5; else overtime = 0.0; or even cout << Overtime is << (hrswkd > 40? (hrswkd-40)* rate * 1.5 : 0.0); 5-11

Logical/Boolean Operators and Expressions George Boole s The Mathematical Analysis of Logic was published in 1847. The formal axioms of logic were set forth in this book and the field of symbolic logic was built. This logic eventually formed the basis for the development of digital computers. We will use the boolean operators to form complex decision statements. NOT! unary operator AND && binary operator OR binary operator By using these operators in conjunction with the relational operators, more complex expressions may be formed. NOT (!) precedes a single expression and gives its opposite as the result. hrswkd <= 40 is equivalent to!(hrswkd > 40) 5-12

AND (&&) combines two logical expressions and requires that both expressions be TRUE for the entire expression to be TRUE num1 <= 10 && num1!= 5 The value of num1 would need to be less than or equal to 10 and also not equal to 5 for this expression to be TRUE OR ( ) combines two logical expressions and states that if either or both of the expressions are TRUE, the entire expression is TRUE num1 <1 num1 > 10 If the value of num1 is not in the range 1-10 this expression evaluates to TRUE Rewrite the following expressions:!(num1 == num2)!(num1 == num2 num1 == num3)!(num1 == num2 && num3 > num4) 5-13

In math books the notation 5 < x < 15 is common. It means that x is between 5 and 15. While the expression is legal in C++ the result is unexpected. What is the result and why? How should the expression be written? 5-14

Short-Circuit Evaluation: Evaluation of a logical expression in left-toright order with evaluation stopping as soon as the final truth can be determined. When AND is used in an expression, the computer stops evaluation as soon as a FALSE condition is found. When OR is used in an expression, evaluation can stop as soon as the first TRUE condition is found. Some languages use full evaluation of logical expressions where both subexpressions are evaluated before the && or operator is applied. Precedence of Operators ( ) Highest ++ --! * / % + - < <= > >= ==!= && = Lowest 5-15

Exercises 1 Given the following values for variables a, b and c: a = TRUE b = FALSE c = TRUE evaluate each of the following expressions a) a && b a && c b)!(a && c) b c)!a c && b 2. Rewrite the following expressions so they would be valid in C++. a) a, b and c are all less than 10 b) a > b >= c c) a does not equal either b or c d) a equals b but does not equal c 5-16

Boolean Expressions Programming Exercise A military academy accepts candidates according to the following height and weight requirements. Gender Min. Height Max. Height Min. Weight Max. Weight Male 62 in. 78 in. 130 lbs. 250 lbs. Female 60 in. 72 in. 110 lbs. 185 lbs. Design a program that accepts as input the gender, height and weight of a candidate. Check to see if the candidate meets the height requirements and store the result in a bool variable called heightok. Next check the weight requirements and store the result in a bool variable called weightok. Using these results, determine whether the candidate was accepted, rejected for height only, rejected for weight only or rejected for both height and weight. Output an appropriate message for each possible outcome. 5-17

Multi-way Selection The switch statement in C++ provides a way to eliminate some nested if structures. The general form for the switch statement is switch (IntegralExpression) SwitchLabel statement;.. The general form for the SwitchLabel is case ConstantExpression: default: where The switch expression is the expression whose value determines which label is selected. It cannot be a floating point expression. The SwitchLabel is either a case label or a default label. In the case label, the ConstantExpression must be an integral literal or a named constant. Each case constant may appear only once in the statement. The switch expression is evaluated and if the value matches one of the constants in the case label, control branches to to the statement following the label. From there it proceeds sequentially until the end of the switch statement or until a break is encountered. If there is no matching label for the expression, it looks for a default label and if found, executes the statement following the label. If no default label is present, control transfers to the statement following the end of the switch statement. 5-18

Example: classcode F S J R default Freshman Sophomore Junior Senior Invalid switch (classcode) case F : cout << You are a freshman ; break; case S : cout << You are a sophomore ; break; case J : cout << You are a junior ; break; case R : cout << You are a senior ; break; default : cout << You entered an invalid code ; break; // not necessary but a good habit 5-19

The fact that without the break statement, the program follows through can be helpful in some situations. Suppose we wanted to allow for lower case input as well. switch (classcode) case F : case f : cout << You are a freshman ; break; case S : case s : cout << You are a sophomore ; break; etc. Switch Exercises: 1. Flowchart a code segment that reads a letter grade from the keyboard and prints good work for A and B students, average work for C students, and poor work for D and F students. Draw this flowchart as a nested if. 2 Write the C++ code to match the flowchart from #1. 3 Draw the flowchart to convert the nested if into a switch statement. 4 Write the C++ code for the flowchart from #3. 5-20