Chapter 4 Selection Structures: Making Decisions PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Similar documents
Another Simple Program: Adding Two Integers

Chapter 4: Making Decisions

Chapter 4: Making Decisions

LECTURE 04 MAKING DECISIONS

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Chapter 4 - Notes Control Structures I (Selection)

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Main Memory Organization

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Chapter 17. Fundamental Concepts Expressed in JavaScript

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Digital Data

Conditional Programming

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Programming Logic and Design Sixth Edition

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

Chapter 4: Control Structures I (Selection)

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Algorithms Lecture 11. UC Davis, ECS20, Winter Discrete Mathematics for Computer Science

LESSON 3 CONTROL STRUCTURES

BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER. Chapter 2

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

Data types Expressions Variables Assignment. COMP1400 Week 2

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

C++ Programming: From Problem Analysis to Program Design, Third Edition

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Relational Operators and if. Class 10

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures

Lecture 9. Monday, January 31 CS 205 Programming for the Sciences - Lecture 9 1

Topics. Chapter 5. Equality Operators

Introduction to Decision Structures. Boolean & If Statements. Different Types of Decisions. Boolean Logic. Relational Operators

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

Lecture 3 Tao Wang 1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Boolean Expressions. Is Equal and Is Not Equal

Boolean Expressions. Is Equal and Is Not Equal

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Checking Multiple Conditions

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

Course Outline. Introduction to java

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Chapter 2, Part III Arithmetic Operators and Decision Making

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

3 The L oop Control Structure

ITP 342 Mobile App Dev. Code

Chapter 5 : Repetition (pp )

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Chapter 4: Making Decisions

5. Control Statements

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

Objectives. In this chapter, you will:

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Computer Science & Engineering 150A Problem Solving Using Computers

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

BITG 1233: Introduction to C++

Chapter 4 : Selection (pp )

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College

Expressions & interactions Conditionals Solving a problem. binary representation (8 bits)

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

QUIZ: What value is stored in a after this

Making Decisions In Python

The C++ Language. Arizona State University 1

Decisions. Arizona State University 1

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

C++ Programming: From Problem Analysis to Program Design, Third Edition

D0010E Object- oriented programming and design. Today. Today An introduc<on to the basic syntax and seman<cs of Java

9. Elementary Algebraic and Transcendental Scalar Functions

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

Selection. Chapter 6. Figure 6.1 The relational operators. = Equal to. < Less than. <= Less than or equal to. > Greater than

5. Selection: If and Switch Controls

Transcription:

Chapter 4 Selection Structures: Making Decisions

4.1 An Introduc/on to Selec/on Structures Single- alterna+ve (If-Then) A single block of statements to be executed or skipped Dual- alterna+ve (If-Then-Else) Two blocks of statements, one of which is to be executed, while the other one is to be skipped Mul+ple- alterna+ve (If-Then-Else-If or Case/Switch) More than two blocks of statements, only one of which is to be executed and the rest skipped

Single Alterna/ve If something is true Then Do something (any number of statements) End If Write How old are you? Input Age If Age >= 18 Set Eligibility = Yes Write You can vote. Do other things End If

Dual Alterna/ve If something is true Then Do something Else End If Do something else Write How old are you? Input Age If Age >= 18 Set Eligibility = Yes Write You can vote. Else Set Eligibility = No Write You re too young. End If

Flowcharts for Selec/on Structures: Single Alterna/ve and Dual Alterna/ves

Flowcharts for Selec/on Structures: Mul/ple Alterna/ve

Guidelines Ø An Else condioon does not have to exist. SomeOmes we only want to do something if something is true and do nothing if it is not true. Ø Do not manufacture alternaove condioons. Ø In an If statement, the body of the If is executed if, and only if, the test condioon is true. Otherwise, no acoon is taken. Ø Be sure to indent for readability.

Example: two ways to write a test condi/on Write Do you have any children? 8 Type Y for yes, N for no Input Response If Response is Y Then End If Write How many? Input NumberChildren Write Questionnaire is complete.8 Thank you. Write Do you have any children? 8 Type Y for yes, N for no Input Response If Response is not N Then End If Write How many? Input NumberChildren Write Questionnaire is complete.8 Thank you.

Example: Mul/ple Alterna/ves 1 Write Enter total cost: 2 Input Cost 3 Write Enter total revenue: 4 Input Revenue 5 Set Amount = Revenue Cost 6 If Amount > 0 Then 7 Set Profit = Amount 8 Write The profit is $ + Profit 9 Else 10 Set Loss = Amount 11 Write The loss is $ + Loss 12 End If

4.2 Rela/onal and Logical Operators Decision making involves tesong a condioon To help construct these condioons use relaoonal operators logical operators

Rela/onal Operators Rela+onal operators are the symbols used in the condioon to be evaluated in If statements: = = is the same as (the comparison operator)!= is not the same as (not equal to) < less than > greater than <= less than or equal to >= greater than or equal to

Example Assume the variables A and B have the values: Then the If statement: If A > B Then End If can be read: A = 9, B = 6 Write A + is greater than + B If it is true that the value of the variable A is greater than the value of the variable B, then write the value of B to the screen. The display will be: 9 is greater than 6

More examples: Given: A = 23, B = 16 Then: A > B is true A < B is false A >= B is true A <= B is false A!= B is true A == B is false

Comparison vs. Assignment Operators There is a significant difference between the use of an equals sign (=) as the assignment operator and a double equals sign (==) as the comparison operator. As an assignment operator, the equals sign sets the value of an expression on the right side to the variable on the ley side. As a comparison operator, the double equals sign asks the quesoon, Is the value of the variable on the ley side the same as the value of the expression, number, or variable on the right side? a single equals sign (=) signifies the assignment operator a double equals sign (==) signifies the comparison operator

The Assignment Operator Given: A = 14, B = 27 In programming code, the assignment statement: A = B sets the value of B to the variable A. In other words, ayer this statement is executed, both A = 27 and B = 27. In this case, the equals sign is used as an assignment operator.

The Comparison Operator Given: A = 14, B = 27 Using rela+onal operators, the statement: is a comparison. A == B This statement asks the quesoon, Is the value of A the same as the value of B? In this case, since A and B have different values, the answer is no and the statement would result in a value of False.

Two ways to obtain a posi/ve result If Number >= 0 Then If Number < 0 Then Write Number Set PosNum = -Number Else Write PosNum Set PosNum = -Number Else Write PosNum Write Number End If End If

Be careful! Do these two give the same result? If Age > 16 Then Write You can drive! Else Write Sorry, you re8 too young. End If If Age < 16 Then Write Sorry, you re8 too young. Else Write You can drive! End If

Logical Operators Ø Logical operators are used to connect simple condioons into a more complex condioon called a compound condi+on. Ø The simple condioons each contain one relaoonal operator. Ø Using compound condioons reduces the amount of code that must be wri\en. Ø Three logical operators we will use: AND, OR, NOT

Logical operators can save space: The following are equivalent Input X If X < 5 Then Write OK End If If X > 10 Then Write OK End If Input X If (X < 5) OR (X > 10) Then Write OK End If

The AND Operator A compound condioon consisong of two simple condioons joined by an AND is true only if both simple condioons are true. It is false if even one of the condioons is false. The statement: If (X > 5) AND (X < 10) Then is true only if X is 6, 7, 8, or 9. It has to be both greater than 5 and less than 10 at the same Ome.

The OR Operator A compound condioon consisong of two simple condioons joined by an OR is true if even one of the simple condioons is true. It is false only if both are false. For example: If (Response == Y ) OR (Response == y ) Then This is true if Response is uppercase ( Y ) or lowercase ( y ). For the above condioon to be false, Response would have to be something other than either Y or y.

The NOT Operator AND and OR affect 2 simple condioons. NOT affects only one condioon. If you need to negate more than one simple condioon, you will need more than one NOT. A condioon with the NOT operator is true only if the condioon is false. NOT(A < B) is true only if B is greater than or equal to A. If (X > 100) AND NOT(X == Y) Then is true only if X is greater than 100 but not equal to the value of Y.

Truth Tables for OR, AND, and NOT Operators X Y X OR Y X AND Y NOT X true true true true false true false true false false false true true false true false false false false true 1-24

Hints In a compound condioon, it is necessary to use complete simple condioons. This is correct: If (X < 5) OR (X > 10) Then This is not correct: If (X < 5 OR > 10) Then

Example: First way using AND Workers who earn less than $10 per hour are paid 1.5 /mes their normal rate for over/me hours. Workers who earn $10 or more per hour are paid their regular hourly rate regardless of number hours worked. Working more than 40 hours per week is considered over/me. 1 If (PayRate < 10) AND (Hours > 40) Then 2 Set OvertimeHours = Hours 40 3 Set OvertimePay = OvertimeHours * 1.5 * PayRate 4 Set TotalPay = 40 * PayRate + OvertimePay 5 Else 6 Set TotalPay = Hours * PayRate 7 End If

Example: Second way using OR Workers who earn less than $10 per hour are paid 1.5 /mes their normal rate for over/me hours. Workers who earn $10 or more per hour are paid their regular hourly rate regardless of number hours worked. Working more than 40 hours per week is considered over/me. 1 If (PayRate >= 10) OR (Hours <= 40) Then 2 Set TotalPay = Hours * PayRate 3 Else 4 Set OvertimeHours = Hours 40 5 Set OvertimePay = OvertimeHours * 1.5 * PayRate 6 Set TotalPay = 40 * PayRate + OvertimePay 7 End If

Flowcharts for the two ways:

Descrip+on Symbol Arithme+c Operators are evaluated first in the order listed Hierarchy of OperaOons (Order of Precedence) First: Parentheses ( ) Second: Exponents Third: Mul+plica+on / Division / Modulus *, /, % Fourth: Addi+on / Subtrac+on + Rela+onal Operators are evaluated second and all rela+onal operators have the same precedence ^ Less than < Less than or equal to <= Greater than > Greater than or equal to >= The same as, equal to == Not the same as!= Logical Operators are evaluated last in the order listed First: NOT Second: AND Third: OR! or NOT or not && or AND or and or OR or or

Combining Logical and Rela/onal Operators Example: Let Q = 3 and let R = 5 Is the following expression true or false? NOT Q > 3 OR R < 3 AND Q R <= 0 Step 1: (NOT(false)) OR (false AND true) Step 2: true OR (false AND true) Step 3: true OR false Step 4: true

The Boolean Type Most programming languages allow variables to be of logical (or Boolean) type. A Boolean variable may only be either true or false. Example: Can declare a variable, Answer, to be of Boolean type and use it in a statement anywhere that a value of true or false is valid, such as the following C++ snippet: bool Answer; Answer = true; if(answer) cout << Congratulations! ; This means: If the value of Answer is true, then write Congratulations! to the screen. The following C++ statement is equivalent to the if statement shown above and may be clearer: if (Answer == true ) cout << Congratulations! ;

4.3 ASCII Code and Comparing Strings Ø A character can be defined as any symbol that can be typed on the keyboard. Ø These symbols include special characters like asterisks (*), ampersands (&), @ signs, as well as le\ers, digits, punctuaoon marks, and blank spaces. Ø There is a more precise definioon of a character using how characters are represented in a computer s memory. Ø RelaOonal operators <, <=, >,!=,==, and >= can be applied to any string of characters.

ASCII Code Ø A programming language uses a scheme to associate each character with a number. Ø The standard is the American Standard Code for Informa+on Interchange (ASCII code). Ø All data, including characters, are stored in the computer s memory in binary form. Ø It is pronounced askey. Ø Each character is associated with a number from 0 to 127. Examples: Uppercase A is 65 Uppercase Z is 90 Digits have codes from 48 ( 0 ) to 57 ( 9 )

Ordering Arbitrary Strings Ø Le\ers are in alphabeocal order. Ø All uppercase le\ers precede all lowercase le\ers. Ø Digits (viewed as characters) retain their natural order. For example, 1 < 2, 2 < 3 Ø The blank precedes all digits and le\ers. Examples: All of the following condioons are true: a > B 1 <= 5 2 >= 2

Rules for Ordering Strings Two strings, S1 and S2, are equal (S1 == S2) if they have exactly the same characters in exactly the same order; they are not equal (S1!= S2) otherwise. To see which of two unequal strings comes first, use the following procedure: 1. Scan strings from ley to right, stopping at the first posioon for which the corresponding characters differ or when one of the strings ends. 2. If two corresponding characters differ before either string ends, the ordering of these characters determines the ordering of the given strings. 3. If one string ends before any pair of corresponding characters differ, then the shorter string precedes the longer one. When applying this procedure, the following is true: If string S1 precedes string S2, then S1 < S2. If string S1 follows string S2, then S1 > S2.

Beware of Strings of Digits Ø A character string may be numbers like 123. But 123 is not the same as 123. Ø The numeric constant is stored in memory by storing the binary equivalent of 123, but the string constant is stored in memory by successively storing the ASCII codes for 1, 2, and 3. There is no mechanism to compare numbers with strings so, if the variable (Num) is a numeric variable, statements like the following: Num == 123 make no sense, and will lead to an error message if used in a program. Also, using the procedure given for ordering strings, we see that: 123 < 25 and 24.0!= 24 are both true statements!

4.4 Selec/ng from Several Alterna/ves To handle more than two opoons in a program we use mulople If-Then statements or mulople If-Then-Else statements. If (something is true) Then Do something Else If (something else is true) Then Do something else Else Do a different something else End If End If

Example If Age >= 18 Then Set Eligibility = Yes Else If Age > 15 Then Set Eligibility = Maybe Else Set Eligibility = No End If End If

Hints Ø The number of End If s must equal the number of If s. Ø You can draw a line to connect them to check. Ø In the previous example, the check for Age > 15 will never be done if the Age is >= 18. Ø Regardless of how many possible condioons are included, only one will ever be executed.

Assigning Ra+ngs the Long Way 1 Declare Score As Integer 2 Declare Rating As Character 3 Write Enter score: 4 Input Score 5 If Score == 10 Then 6 Set Rating = A 7 End If 8 If (Score == 8) OR (Score == 9) Then 9 Set Rating = B 10 End If 11 If (Score == 6) OR (Score == 7) Then 12 Set Rating = C 13 End If 14 If (Score >= 1) AND (Score <= 5) Then 15 Set Rating = D 16 End If

Assigning Ra+ngs the Long Way

Assigning Ra+ngs the Nested If-Then-Else Way 1 Declare Score As Integer 2 Declare Rating As Character 3 Write Enter score: 4 Input Score 5 If Score == 10 Then 6 Set Rating = A 7 Else 8 If (Score == 8) OR (Score == 9) Then 9 Set Rating = B 10 Else 11 If (Score == 6) OR (Score == 7) Then 12 Set Rating = C 13 Else 14 Set Rating = D 15 End If 16 End If 17 End If

Assigning Ra+ngs the Nested If-Then-Else Way

Using Case- Like (or Switch) Statements Select Case Of??? test expression to be evaluated Case 1st value: Statements execute if test expression is a match Break out of Cases Case 2nd value: Statements execute if test expression is a match Break out of Cases Case 3rd value: Statements execute if test expression is a match Break out of Cases.. all the rest of the values that can be chosen. Case nth value: Statements execute if test expression is a match Break out of Cases Default: Statements execute if test expression does not match any of the above End Case

Assigning Ra+ngs Using a Case Statement 1 Declare Score As Integer 2 Declare Rating As Character 3 Write Enter score: 4 Input Score 5 Select Case Of Score 6 Case 10: 7 Set Rating = A 8 Break 9 Case 8, 9: 10 Set Rating = B 11 Break 12 Case 6, 7: 13 Set Rating = C 14 Break 15 Case 1 5: 16 Set Rating = D 17 Break 18 End Case

Assigning Ra+ngs using A Case Statement

4.5 Applica/ons of Selec/on Structures Defensive Programming: Program defensively in order to prevent bad data from entering our program. To do this, set error traps. If our program should accept only a Cost greater than 0, we can stop any other value from entering with the following trap: Input Cost If Cost <= 0 Then Write Invalid cost Else Write The cost is + Cost End If

Error Trap for a Division by Zero Error The reciprocal of a number is 1 divided by that number. But division by zero is not allowed ao the reciprocal of 0 is undefined. The following example will display the reciprocal of any number: Write Enter a number. Write This program will display its reciprocal. Input Number If Number!= 0 Then Set Reciprocal = 1/Number Write The reciprocal of + Number + is + Reciprocal Else Write The reciprocal of 0 is not defined. End If

Avoiding Illegal Opera/ons: the Sqrt() func/on The following program segment displays the square root of a number unless the number is negaove: Write Enter a number: Write This program will display its square root. Input Number If Number >= 0 Then Write The square root of + Number + is + 8 Else End If Sqrt(Number) Write The square root of + Number + is not defined.

Defensive Programming Ø Be sure to test your program by playing computer. Ø This is also called desk checking. Ø Perform all calculaoons mulople Omes manually or with a calculator. Ø Use data that will show the results when each branch of each selecoon structure is executed at least once. Ø Check for division by zero, negaove values for a square root funcoon, and any other special condioons.

Menu- Driven Programs Ø A major goal of a programmer is to create user friendly programs. Ø When the user has many opoons, menus are oyen used. Ø Such programs are menu- driven. Ø Menus are usually arranged in a row near the top of the screen. Ø The user clicks the mouse on the desired choice. Ø The main menu (a list of the program s major funcoons) is usually the first thing the user sees.

Sample Menu The Legendary Lawn Mower Company Inventory Control Leave the program... Enter 0 Add an item to the list... Enter 1 Delete an item from the list... Enter 2 Change an item on the list... Enter 3