The Ohio State University

Slides:



Advertisements
Similar presentations
If Statements & Relational Operators Programming.
Advertisements

Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
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.
CS 1400 Jan 2007 Chapter 4, sections Relational operators Less than< Greater than> Less than or equal= Equal== Not equal!=
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Chapter 4 Program Control Statements
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.
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
CSE1222: Lecture 3The Ohio State University1. Assignment Operations  The C++ assignment operator is: =  Examples: x = 3 * 5; y = x – 7; y = y + 4; Do.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
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,
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
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.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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,
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.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
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)
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Branching statements.
Introduction to Computer Programming
Chapter 3 Selection Statements
Repetitive Structures
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Bill Tucker Austin Community College COSC 1315
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.
More important details More fun Part 3
The Ohio State University
A mechanism for deciding whether an action should be taken
Chapter 2 Assignment and Interactive Input
EGR 2261 Unit 4 Control Structures I: Selection
Engineering Problem Solving with C++, Etter/Ingber
Introduction to C++ October 2, 2017.
Programming Fundamentals
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Selection By Ramin && Taimoor
Compound Assignment Operators in C++
Executes a block of statements only if a test is true
Selection Control Structure
Summary Two basic concepts: variables and assignments Basic types:
If Statements.
Chapter 4: Control Structures I (Selection)
Control Structures Part 1
By Hector M Lugo-Cordero September 3, 2008
Boolean Expressions to Make Comparisons
Life is Full of Alternatives
Arithmetic Operations
Life is Full of Alternatives
Life is Full of Alternatives
Branching statements Kingdom of Saudi Arabia
Selection Control Structure
Presentation transcript:

The Ohio State University Selection Structures CSE1222: Lecture 5 The Ohio State University

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

The Ohio State University 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? CSE1222: Lecture 5 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 5 The Ohio State University

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 } CSE1222: Lecture 5 The Ohio State University

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. CSE1222: Lecture 5 The Ohio State University

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 CSE1222: Lecture 5 The Ohio State University

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; CSE1222: Lecture 5 The Ohio State University

The Ohio State University 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. CSE1222: Lecture 5 The Ohio State University

The Ohio State University slope.cpp #include <iostream> using namespace std; int main() { double x1, y1, x2, y2, xdiff, ydiff, slope; cout << "Enter x and y coordinates of first point : "; cin >> x1 >> y1; cout << "Enter x and y coordinates of second point : "; cin >> x2 >> y2; ... CSE1222: Lecture 5 The Ohio State University

The Ohio State University slope.cpp (cont.) ... xdiff = x1 - x2; ydiff = y1 - y2; if (xdiff != 0.0) { slope = ydiff / xdiff; cout << "The slope is: " << slope << endl; } else cout << "The slope is infinite." << endl; return 0; CSE1222: Lecture 5 The Ohio State University

The Ohio State University ... xdiff = x1 - x2; ydiff = y1 - y2; if (xdiff != 0.0) { slope = ydiff / xdiff; cout << "The slope is: " << slope << endl; } else cout << "The slope is infinite." << endl; > slope.exe Enter x and y coordinates of first point : 0 3 Enter x and y coordinates of second point : 4 1 The slope is: -0.5 CSE1222: Lecture 5 The Ohio State University

The Ohio State University ... xdiff = x1 - x2; ydiff = y1 - y2; if (xdiff != 0.0) { slope = ydiff / xdiff; cout << "The slope is: " << slope << endl; } else cout << "The slope is infinite." << endl; > slope.exe Enter x and y coordinates of first point : 4 3 Enter x and y coordinates of second point : 4 1 The slope is infinite. CSE1222: Lecture 5 The Ohio State University

The Ohio State University ... xdiff = x1 - x2; ydiff = y1 - y2; if (xdiff != 0.0) { slope = ydiff / xdiff; cout << "The slope is: " << slope << endl; } else cout << "The slope is infinite." << endl; > slope.exe Enter x and y coordinates of first point : 4 3 Enter x and y coordinates of second point : 4 3 The slope is infinite. What is wrong with this answer? CSE1222: Lecture 5 The Ohio State University

The Ohio State University slope2.cpp: Nested ifs ... xdiff = x1 - x2; ydiff = y1 - y2; if (xdiff != 0.0) { slope = ydiff / xdiff; cout << "The slope is: " << slope << endl; } else if (ydiff != 0.0) { cout << "The slope is infinite." << endl; else { cout << "Input Error: First point equals second point." << endl; cout << "Slope undefined." << endl; CSE1222: Lecture 5 The Ohio State University

The Ohio State University ... if (xdiff != 0.0) { slope = ydiff / xdiff; cout << "The slope is: " << slope << endl; } else if (ydiff != 0.0) { cout << "The slope is infinite." << endl; else { cout << "Input Error: First point equals second point." << endl; cout << "Slope undefined." << endl; > slope.exe Enter x and y coordinates of first point : 4 3 Enter x and y coordinates of second point : 4 3 Input Error: First point equals second point. Slope undefined. CSE1222: Lecture 5 The Ohio State University

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; } } { cout << "You are too young to drive." << endl; } return 0; What is the output on input: 10 15 20 CSE1222: Lecture 5 The Ohio State University

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: 10 20 40 Does the else clause execute on input 20? Why or why not? CSE1222: Lecture 5 The Ohio State University

The Ohio State University 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! CSE1222: Lecture 5 The Ohio State University

Relational Operators (1) Meaning Example < 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 false (0) and true (1). CSE1222: Lecture 5 The Ohio State University

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

The Ohio State University Ascii Table CSE1222: Lecture 5 The Ohio State University

The Ohio State University booleanExpr.cpp // Examples of Boolean expressions #include <iostream> 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 << "((2.0+5.0) == 7) evaluates to " << ((2.0+5.0) == 7) << endl; cout << "((5/3) > 1.0) evaluates to " << ((5/3) > 1.0) << endl; cout << "(x == 10) evaluates to " << (x == 10) << endl; cout << "(x = 8) evaluates to " << (x = 8) << endl; return 0; } CSE1222: Lecture 5 The Ohio State University

The Ohio State University 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++, !) CSE1222: Lecture 5 The Ohio State University

The Ohio State University 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 true for the entire expression to be true. The || operator returns true if either operand evaluates to true. The unary ! Operator returns true if its operand is false, and false if its operand is true. CSE1222: Lecture 5 The Ohio State University

The Ohio State University 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. CSE1222: Lecture 5 The Ohio State University

The Ohio State University logicalOperators1.cpp // Examples of logical operators #include <iostream> 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; } if (x < 7 && !(y < 12)) { cout << “true” << endl; } return 0; } CSE1222: Lecture 5 The Ohio State University

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

The Ohio State University 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.) CSE1222: Lecture 5 The Ohio State University

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) if (flag_discount) { cout << "You receive a discount." << endl; } else { cout << "No discount." << endl; } CSE1222: Lecture 5 The Ohio State University

The Ohio State University Note on Truth Any integer that is not 0 is considered to be a Boolean true in C++. Relational and logical operators only ever return false (0) and true (1). CSE1222: Lecture 5 The Ohio State University

Order of (more) Operations Operator Associativity ! unary - ++ -- right to left * / % left to right + - < <= > >= == != && || = += -= *= /= CSE1222: Lecture 5 The Ohio State University

The Ohio State University comparisonExample.cpp // comparison example #include <iostream> 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; CSE1222: Lecture 5 The Ohio State University

The Ohio State University … 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; > comparisonExample Enter year: 2007 2007 is NOT a US presidential election year. Enter year: 2008 2008 is a US presidential election year. CSE1222: Lecture 5 The Ohio State University

The Ohio State University comparisonError.cpp // comparison error #include <iostream> 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; CSE1222: Lecture 5 The Ohio State University

The Ohio State University … 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; > comparisonError Enter year: 2007 2007 is NOT a US presidential election year. Enter year: 2008 2008 is NOT a US presidential election year. CSE1222: Lecture 5 The Ohio State University

The Ohio State University comparisonError2.cpp // comparison example #include <iostream> 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; } CSE1222: Lecture 5 The Ohio State University

The Ohio State University 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.) CSE1222: Lecture 5 The Ohio State University

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