Decisions. Arizona State University 1

Similar documents
Chapter 4: Making Decisions

Chapter 4: Making Decisions

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

LECTURE 04 MAKING DECISIONS

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

Lecture 5: Making Decisions

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

Looping. Arizona State University 1

Software Design & Programming I

The C++ Language. Arizona State University 1

5. Selection: If and Switch Controls

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

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

CSCE 206: Structured Programming in C++

CSCI 1061U Programming Workshop 2. C++ Basics

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

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

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;

Chapter 4 - Notes Control Structures I (Selection)

Topics. Chapter 5. Equality Operators

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

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

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

Introduction to C Programming

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

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

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

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Logical Operators and if/else statement. If Statement. If/Else (4.3)

Chapter 10 Characters, Strings, and the string class

Decision Making in C

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

Arrays. Arizona State University 1

Control Structures in Java if-else and switch

Chapter 4: Control Structures I (Selection)

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

LECTURE 02 INTRODUCTION TO C++

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

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

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

Introduction to Programming

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Boolean Expressions. Is Equal and Is Not Equal

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

LAB 4.1 Relational Operators and the if Statement

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

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Chapter 2: Introduction to C++

5. Control Statements

Lecture 5 Tao Wang 1

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Checking Multiple Conditions

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

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

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

Linear execution of statements. CISC 1600/1610 Computer Science I. Alternatives to linear execution. Linear execution of statements

today cs3157-fall2002-sklar-lect05 1

Chapter 7. Additional Control Structures

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

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

Advanced Computer Programming

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class

Maciej Sobieraj. Lecture 1

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Chapter 3. More Flow of Control

UEE1302(1102) F10: Introduction to Computers and Programming

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Boolean Expressions. Is Equal and Is Not Equal

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

CS150 Introduction to Computer Science 1. Logical Operators and if/else statement

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Control Structures in Java if-else and switch

CS3157: Advanced Programming. Outline

CSI33 Data Structures

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Functions. Arizona State University 1

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

Selection Statements. Pseudocode

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

Boolean evaluation and if statements. Making decisions in programs

Chapter 2. C++ Basics

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

Announcements. Homework 0: using cin with 10/3 is NOT the same as (directly)

Transcription:

Decisions CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 4 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University 1

Relational Operators Are used to compare numeric and char values to determine relative order Operators: > Greater than < Less than >= Greater than or equal to <= Less than or equal to == Equal to!= Not equal to Arizona State University 2

Relational Expressions Relational expressions are Boolean (i.e., evaluate to true or false) Examples: 12 > 5 is true 7 <= 5 is false if x is 10, then x == 10 is true, x <= 8 is false, x!= 8 is true, and x == 8 is false Arizona State University 3

Relational Expressions The value can be assigned to a variable bool result = (x <= y); Assigns 0 for false, 1 for true Do not confuse = (assignment) and == (equal to) Arizona State University 4

Hierarchy Operator Precedence > >= < <= Highest ==!= Lowest Use this when evaluating an expression that contains multiple relational operators. Arizona State University 5

if Supports the use of a decision structure, giving a program more than one path of execution Allows statements to be conditionally executed or skipped over It models the way we evaluate real-life situations If it is cold outside, wear a coat and wear a hat. Arizona State University 6

if (cont.) if (condition) { statement1; statement2; statementn; } The block of statements inside the braces is called the body of the if statement. If there is only 1 statement in the body, the { } may be omitted. Arizona State University 7

if (cont.) If (condition) is true, then the statement(s) in the body are executed. If (condition) is false, then the statement(s) are skipped. Arizona State University 8

Examples if (score >= 60) cout << "You passed." << endl; if (score >= 90) { grade = 'A'; cout << "Wonderful job!" << endl; } Arizona State University 9

Key Notes if is a keyword. It must be lowercase (condition)must be in ( ) Do not place ; after (condition) Don't forget the { } around a multi-statement body Don t confuse = (assignment) with == (comparison) Arizona State University 10

Comparisons with Floating-Point It is difficult to test for equality when working with floating point numbers. It is better to use greater-than or less-than tests, or test to see if value is very close to a given value Arizona State University 11

What s true/false? An expression whose value is 0 is considered false. An expression whose value is non-zero is considered true. An expression need not be a comparison it can be a single variable or a mathematical expression. Arizona State University 12

!s A flag is a variable that signals a condition It is usually implemented as a bool Meaning: true: the condition exists false: the condition does not exist The flag value can be both set and tested with if statements Arizona State University 13

Flag Example Example: bool validmonths = true; if (months < 0) validmonths = false; if (validmonths) monthlypayment = total / months; Arizona State University 14

Integer Flags Integer variables can be used as flags Remember that 0 means false, any other value means true int alldone = 0; // set to false if (count > MAX_STUDENTS) alldone = 1; // set to true if (alldone) cout << "Task finished"; Arizona State University 15

if/else Allows a choice between statements depending on whether (condition) is true or false Format: if (condition) { statement set 1; } else { statement set 2; } Arizona State University 16

if/else (cont.) If (condition) is true, statement set 1 is executed and statement set 2 is skipped. If (condition) is false, statement set 1 is skipped and statement set 2 is executed. Arizona State University 17

if/else Example if (score >= 60) cout << "You passed.\n"; else cout << "You did not pass.\n"; if (intrate > 0) { interest = loanamt * intrate; cout << interest; } else cout << "You owe no interest.\n"; Arizona State University 18

When to use just if? If there are two conditions and both of them can be true or both can be false, then use two if statements: if (num > 0) cout << num << " is positive\n"; if (num % 2 == 0) cout << num << " is even\n"; If the two conditions cannot both be true, then a single if/else statement can work: if (num %2 == 0) cout << num << " is even\n"; else cout << num << " is odd\n"; Arizona State University 19

if/else Chains This is a chain of if statements that test in order until one is found to be true This also models thought processes If it is raining, take an umbrella, else, if it is windy, take a hat, else, if it is sunny, take sunglasses. Arizona State University 20

Trailing else Is used with a set of if/else if statements It provides a default statement or action that is performed when none of the conditions is true It can be used to catch invalid values or handle other exceptional situations if (age >= 21) cout << "Adult"; else if (age >= 13) cout << "Teen"; else if (age >= 2) cout << "Child"; else cout << "Baby"; Arizona State University 21

Nested if Statements An if statement that is part of the if or else part of another if statement This can be used to evaluate > 1 data item or to test > 1 condition if (score < 100) { if (score > 90) grade = 'A'; } Arizona State University 22

Key Note: Nested if Statements An else matches the nearest previous if that does not have an else if (score < 100) if (score > 90) grade = 'A'; else... // goes with second if, // not first one Proper indentation aids understanding Arizona State University 23

Example Program: Menu Menu: list of choices presented to the user on the computer screen Menu-driven program: program execution is controlled by user selecting from a list of actions A menu-driven program can be written using if/else if statements Display a list of numbered or lettered choices for actions. Input user s selection of number or letter Test the user selection in (condition) if a match, then execute code to carry out desired action if not, then test with next (condition) Arizona State University 24

Logical Operators Are used to create relational expressions from other relational expressions Operator Meaning Explanation && AND New relational expression is true if both expressions are true OR New relational expression is true if either expression is true! NOT Reverses the value of an expression; true expression becomes false, false expression becomes true Arizona State University 25

Logical Operator Examples int x = 12, y = 5, z = -4; (x > y) && (y > z) true or 1 (x > y) && (z > y) false or 0 (x <= z) (y == z) false (x <= z) (y!= z) true!(x >= z) false Arizona State University 26

Logical Operators and bools Logicial operators can be used with bool variables as well as expressions that evaluate to true or false. Ex: bool done = false; if ((!done) && (count < 6)) {... } Arizona State University 27

Short-Circuit Evaluation If an expression using the && operator is being evaluated and the subexpression on the left side is false, then there is no reason to evaluate the subexpression on the right side. It is skipped. If an expression using the operator is being evaluated and the subexpression on the left side is true, then there is no reason to evaluate the subexpression on the right side. It is skipped. Arizona State University 28

Logical Operator Precedence Highest! && Lowest Example: (2 < 3) (5 > 6) && (7 > 8) is true because AND is evaluated before OR Arizona State University 29

More on Precedence Highest Lowest arithmetic operators relational operators logical operators Example: 8 < 2 + 7 5 == 6 is true Arizona State University 30

Example: Check Valid Range Used to test if a value is within a range if (grade >= 0 && grade <= 100) cout << "Valid grade"; You can also test if a value lies outside a range if (grade <= 0 grade >= 100) cout << "Invalid grade"; Note that you cannot use mathematical notation if (0 <= grade <= 100) //Doesn t //work! Arizona State University 31

User Input Validation Input validation: inspecting input data to determine if it is acceptable You want to avoid accepting bad input You can perform various tests Range Reasonableness Valid menu choice Zero as a divisor Arizona State University 32

Scope The Scope of a variable is the block in which it is defined, from the point of definition to the end of the block Variables are usually defined at the beginning of a function They may instead be defined close to the place where they are first used Variables defined inside { } have local or block scope When in a block that is nested inside another block, you can define variables with the same name as in the outer block. When the program is executing in the inner block, the outer definition is not available This generally not a good idea. The program may be hard to read or understand. Arizona State University 33

Characters/Strings and if You can use relational operators with characters and string objects if (menuchoice == 'A') if (name1 >= name2) Comparing characters is really comparing the ASCII values of characters Comparing string objects is comparing the ASCII values of the characters in the strings. Comparison is character-by-character, starting with the first character of each string. You cannot compare C-style strings with relational operators Arizona State University 34

Testing Characters These functions require the cctype header file FUNCTION MEANING isalpha true if arg. is a letter, false otherwise isalnum true if arg. is a letter or digit, false otherwise isdigit true if arg. is a digit 0-9, false otherwise islower true if arg. is lowercase letter, false otherwise isprint true if arg. is a printable character, false otherwise ispunct true if arg. is a punctuation character, false otherwise isupper true if arg. is an uppercase letter, false otherwise isspace true if arg. is a whitespace character, false otherwise Arizona State University 35

Switch Is uses the value of an integer expression to determine the statements to execute It may sometimes be used instead of if/else if statements switch (IntExpression) { case exp1: statement set 1; case exp2: statement set 2;... case expn: statement set n; default: statement set n+1; } Arizona State University 36

Switch Requirements 1) IntExpression must be an integer variable or a char,or an expression that evaluates to an integer value 2) exp1 through expn must be constant integer type expressions and must be unique in the switch statement 3) default is optional but recommended Arizona State University 37

How Switch Works 1) IntExpression is evaluated 2) The value of intexpression is compared against exp1 through expn. 3) If IntExpression matches value expi, the program branches to the statement(s) following expi and continues to the end of the switch 4) If no matching value is found, the program branches to the statement after default: Arizona State University 38

break Is used to stop execution in the current block It is also used to exit a switch statement It is used to execute a single case statement without executing statements following it switch (gender) { case 'f': cout << "female"; } break; case 'm': cout << "male"; break; default : cout << "invalid gender"; Arizona State University 39

Switch with Menu A switch statement is a natural choice for a menu-driven program display menu get user input use user input as IntExpression in switch statement use menu choices as exp values to test against in the case statements Arizona State University 40

Enums Is a data type created by the programmer Contains a set of named integer constants Format: enum name {val1, val2, valn}; Examples: enum Fruit {apple, grape, orange}; enum Days {Mon, Tue, Wed, Thur, Fri}; Arizona State University 41

Enumerated Variables To define variables, use the enumerated data type name Fruit snack; Days workday, vacationday; A variable may contain any valid value for the data type snack = orange; // no quotes if (workday == Wed) // none here Enumerated data type values are associated with integers, starting at 0 enum Fruit {apple, grape, orange}; 0 1 2 You can override the default association enum Fruit {apple = 2, grape = 4, orange = 5}; Arizona State University 42

Enumerated Values Enumerated data type values can be compared using their integer values if (snack == 1) Enumerated data type values cannot be assigned using their integer values snack = 2; // won t work Arizona State University 43

Enum Notes Enumerated data types improve the readability of a program Enumerated variables cannot be used with input statements, such as cin An enumerated variable will not display the name associated with the value of an enumerated data type if used with cout Arizona State University 44