CSE202: Lecture 5The Ohio State University1 Selection Structures.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

If Statements & Relational Operators Programming.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
CS 1400 Jan 2007 Chapter 4, sections Relational operators Less than< Greater than> Less than or equal= Equal== Not equal!=
The If/Else Statement, Boolean Flags, and Menus Page 180
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Programming in C++ Lecture Notes 2 – Choice Statements Andreas Savva.
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 4 Program Control Statements
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
CONDITIONAL STATEMENTS OVERVIEW.  Many times we want programs to make decisions  What drink should we dispense from the vending machine?  Should we.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
CONTROLLING PROGRAM FLOW
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
Fundamental Programming: Fundamental Programming Introduction to C++
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
1 09/15/04CS150 Introduction to Computer Science 1 Life is Full of Alternatives Part 2.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
PEG200/Saidatul Rahah 1.  Selection Criteria › if..else statement › relational operators › logical operators  The if-then-else Statement  Nested if.
CSCI 161 Lecture 7 Martin van Bommel. Control Statements Statements that affect the sequence of execution of other statements Normal is sequential May.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Fundamental Programming Fundamental Programming More Expressions and Data Types.
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.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
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,
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
The Ohio State University
Branching statements.
Introduction to Computer Programming
Chapter 3 Selection Statements
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.
A mechanism for deciding whether an action should be taken
EGR 2261 Unit 4 Control Structures I: Selection
Summary Two basic concepts: variables and assignments Basic types:
If Statements.
Chapter 4: Control Structures I (Selection)
Life is Full of Alternatives
Life is Full of Alternatives
Life is Full of Alternatives
Presentation transcript:

CSE202: Lecture 5The Ohio State University1 Selection Structures

CSE202: Lecture 5The Ohio State University2 Consider the following code: int main() { int x; x = 46; x++; cout << x << endl; return 0; } Its control flow Flow of Control (1)

CSE202: Lecture 5The Ohio State University3 Flow of Control (2) Notice in the previous slide, that the flow of control is completely sequential. In other words, every statement is executed in order. This makes for powerless and probably insignificant programs. Can we do better? Can the flow of control not be as deterministic?

CSE202: Lecture 5The Ohio State University4 Selection Structures We want to add some branching to the flow of control, which allow certain statements to be executed out of sequential order, or skipped entirely. C++ allows for this with selection structures: - if-then-else statements - switch statements

CSE202: Lecture 5The Ohio State University5 if–then Statement Syntax The if-then statement is the first selection structure we examine. Basically, it says: “IF some condition is true, THEN run a sequence of statements.” The if-then syntax is shown below: if (conditional expression) { statements executed if condition is true }

CSE202: Lecture 5The Ohio State University6 if–else Statement Syntax (1) We can optionally extend the if-then statement to an if-then-else statement, meaning: “IF some condition is true, THEN run a sequence of statements. ELSE, run a sequence of other statements.” The ELSE portion is optional because it is not always the case that the program should take action if some condition is false.

CSE202: Lecture 5The Ohio State University7 if–else Statement Syntax (2) The if-then-else syntax is shown below: if (conditional expression) { statements executed if condition is true } else { statements executed if condition is false }

CSE202: Lecture 5The Ohio State University8 Example of an if-then-else Statement... int main() { double x(0.0); cout << “Enter a number: “; cin >> x; // Handle divide by zero! if (x == 0) { cout << “ERROR: Input must be not be 0!” << endl; } else { cout << “The fraction is: “ << 1/x << endl; } return 0; }

CSE202: Lecture 5The Ohio State University9 Notice how of the flow of control is able to branch and select which statements to execute, and which ones to avoid from running! Also notice that after the selection structure execution, the code returns back to sequential operation.

CSE202: Lecture 5The Ohio State University10 Nested Conditional Statements... int main() { int age(0); cout << "Enter your age: "; cin >> age; if (age >= 15) { if (age == 15) { cout << "You can get a learners permit." << endl; } else { cout << "You can get a license." << endl; } } else { cout << "You are too young to drive." << endl; } return 0; } What is the output on input:

CSE202: Lecture 5The Ohio State University11 Nested Conditional Statements... int main() { int age(0); cout << "Enter your age: "; cin >> age; if (age >= 18) { cout << "You can vote." << endl; if (age >= 35) { cout << "You can become President." << endl; } } else { cout << "You are too young to vote." << endl; } return 0; } What is the output on input: Does the else clause execute on input 20? Why or why not?

CSE202: Lecture 5The Ohio State University12 Selection Criteria The if- conditions are common relational expressions. The outcomes of the expression is Boolean; it can only have two outcomes: true or false (or 1 or 0 respectively). In the previous example, age >= 16 is a relational expression that evaluates to either true or false depending on what the user inputs!

CSE202: Lecture 5The Ohio State University13 Relational Operators (1) OperatorMeaningExample < less than x < 0 > greater than speed > 65 <= less than or equal to age <=17 >= greater than or equal to gpa >= 3.5 == equal to initial == ‘a’ != not equal to divisor != 0 Relational operators return 0 and 1

CSE202: Lecture 5The Ohio State University14 Relational Operators (2) Relational operators can compare character data, for example ‘a’ < ‘b’ evaluates to true (why is this true?) ‘G’ > ‘M’ evaluates to 0 (or false) ‘E’ != ‘e’ evaluates to 1 (or true) 2 < 0 evaluates to 0

CSE202: Lecture 5The Ohio State University15 Ascii Table

CSE202: Lecture 5The Ohio State University16 booleanExpr.cpp // Examples of Boolean expressions #include using namespace std; int main() { double x(10); cout << "(4 != 4) evaluates to " << (4 != 4) << endl; cout << "('a' <= 'b') evaluates to " << ('a' <= 'b') << endl; cout << "('B' < 'b') evaluates to " << ('B' < 'b') << endl; cout 1.0) evaluates to " 1.0) << endl; cout << "(10 == 10) evaluates to " << (10 == 10) << endl; cout << "(x == 10) evaluates to " << (x == 10) << endl; cout << "(x = 8) evaluates to " << (x = 8) << endl; return 0; }

CSE202: Lecture 5The Ohio State University17 Logical Operators (1) Every one of these expressions only take 2 operands, so it is NOT possible to use the familiar expression 18 < x < 60 in order to test if x is a number in between 18 and 60. Instead, to build more complicated expressions, we can use the logical operators used in Boolean algebra: –AND (in C++, && ) –OR (in C++, || ) –NOT (in C++, ! )

CSE202: Lecture 5The Ohio State University18 Logical Operators (2) Going back to the previous example, if you wanted to verify that a variable x is between 18 and 60 inclusive, you could use the following expression: (age >= 18 && age <= 60) AND, OR are both binary operators, NOT is a unary operator. –If an expression has an && operator, then both operands must evaluate to 1 for the entire expression to be 1 –The || operator returns 1 if either operand evaluates to 1 –The unary ! Operator returns 1 if its operand is 0, and 0 if its operand is 1

CSE202: Lecture 5The Ohio State University19 The NOT Operator NOT is a unary operator (it only takes one operand), so how does it work? Let’s say that now we want to check if x is not between 18 and 60. We simply use: !(age >= 18 && age <= 60) The NOT operator only takes one operand, evaluates it to true or false, then flips the result.

CSE202: Lecture 5The Ohio State University20 logicalOperators1.cpp // Examples of logical operators #include using namespace std; int main() { int x(5); int y(25); if (x < 7 && y < 12) { cout << “true” << endl; } else { cout << “false” << endl; }; if (x < 7 || y < 12) { cout << “true” << endl; } else { cout << “false” << endl; }; if (x < 7 && !(y < 12)) { cout << “true” << endl; } else { cout << “false” << endl; }; return 0; }

CSE202: Lecture 5The Ohio State University21 logicalOperators2.cpp // Examples of logical operators #include using namespace std; int main() { int x(5); int y(25); if ((x 7 && y > 12)) { cout << “true” << endl; } else { cout << “false” << endl; }; if ((x 7 || y > 12)) { cout << “true” << endl; } else { cout << “false” << endl; }; return 0; }

Exercises Give a boolean expression which is true if x is a non-negative number strictly less than 50; Give a boolean expression which is true if x is not in the range [25-30]. (Multiple solutions.) CSE202: Lecture 5The Ohio State University22

CSE202: Lecture 5The Ohio State University23 Example of Boolean variables... int main() { int age(0); bool flag_discount(false); cout << "Enter your age: "; cin >> age; if (age < 18) { flag_discount = true; } if (age >= 65) { flag_discount = true; } if (flag_discount) { cout << "You receive a discount." << endl; } else { cout << "No discount." << endl; }...

CSE202: Lecture 5The Ohio State University24 Note on Truth Any number that is greater than 0 is considered to be a Boolean true in C++ Relational and logical operators only ever return 0 and 1

CSE202: Lecture 5The Ohio State University25 Order of (more) Operations OperatorAssociativity ! unary right to left * / % left to right + - left to right >= left to right == != left to right && left to right || left to right = += -= *= /= right to left

CSE202: Lecture 5The Ohio State University26 comparisonExample.cpp // comparison example #include using namespace std; int main() { int year(0); cout << "Enter year: "; cin >> year; int k = year%4; if (k == 0) { cout << year << " is a US presidential election year." << endl; } else { cout << year << " is NOT a US presidential election year." << endl; } return 0; }

CSE202: Lecture 5The Ohio State University27 > comparisonExample Enter year: is NOT a US presidential election year. > comparisonExample Enter year: is a US presidential election year. … int k = year%4; if (k == 0) // if k is equal to 0,... { cout << year << " is a US presidential election year." << endl; } else { cout << year << " is NOT a US presidential election year." << endl; } …

CSE202: Lecture 5The Ohio State University28 comparisonError.cpp // comparison error #include using namespace std; int main() { int year(0); cout << "Enter year: "; cin >> year; int k = year%4; if (k = 0) { cout << year << “ is a US pres election year.” << endl; } else { cout << year << “ is NOT a US presidential election year.” << endl; } return 0; }

CSE202: Lecture 5The Ohio State University29 > comparisonError Enter year: is NOT a US presidential election year. > comparisonError Enter year: is NOT a US presidential election year. … int k = year%4; if (k = 0) { cout << year << " is a US presidential election year." << endl; } else { cout << year << " is NOT a US presidential election year." << endl; } …

CSE202: Lecture 5The Ohio State University30 comparisonError2.cpp // comparison example #include using namespace std; int main() { int year(0); cout << "Enter year: "; cin >> year; int k = year%4; if (k == 0) // if k is equal to 0,... { cout << year << " is a US presidential election year." << endl; }; else { cout << year << " is NOT a US presidential election year." << endl; }; return 0; }

CSE202: Lecture 5The Ohio State University31 comparisonError2.cpp … int k = year%4; if (k == 0) // if k is equal to 0,... { cout << year << " is a US presidential election year." << endl; }; else { cout << year << " is NOT a US presidential election year." << endl; }; … What’s the error? (Try compiling this program.)

CSE202: Lecture 5The Ohio State University32 Warning Use ‘ == ’ (equal to), not ‘ = ’ (assignment). Use ‘ && ’ not ‘ & ’. Use ‘ || ’, not ‘ | ’. Do not put a semi-colon before an “else” clause.