CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout <<

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.
CSE202: Lecture 2The Ohio State University1 Variables and C++ Data Types.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Conditional Operator (?:) Conditional operator (?:) takes three arguments (ternary) Syntax for using the conditional operator:
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
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.
Thursday, December 14, 2006 “Would you tell me, please, which way I ought to go from here?” “That depends a good deal on where you want to get to,” said.
The If/Else Statement, Boolean Flags, and Menus Page 180
C++ for Engineers and Scientists Third Edition
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
Programming with MATLAB. Relational Operators The arithmetic operators has precedence over relational operators.
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.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
True or False: Boolean Expression Boolean expression are expressions which evaluate to "true" or "false“ Primary operators to combine expressions: && (and),
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Fundamental Programming Fundamental Programming More on Selection.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
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.
Selection Structures (if & switch statements) (CS1123)
Chapter 4 Selection Structures: Making Decisions.
Conditional Execution
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
CS101 Computer Programming I Chapter 4 Extra Examples.
CS Class 05 Topics  Selection: switch statement Announcements  Read pages 74-83, ,
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
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
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Control Structures RepetitionorIterationorLooping Part I.
Input Validation 10/09/13. Input Validation with if Statements You, the C++ programmer, doing Quality Assurance (by hand!) C++ for Everyone by Cay Horstmann.
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,
CPS120: Introduction to Computer Science Decision Making in Programs.
31/01/ Selection If selection construct.
Lecture 01b: C++ review Topics: if's and switch's while and for loops.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Programming Fundamentals by Dr. Nadia Y. Yousif1 Control Structures (Selections) Topics to cover here: Selection statements in the algorithmic language:
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Basic C++ Programming.
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.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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,
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
The Ohio State University
Introduction to Computer Programming
Factoring if/else code
Scripts & Functions Scripts and functions are contained in .m-files
More Selections BIS1523 – Lecture 9.
Conditions and Ifs BIS1523 – Lecture 8.
If Statements.
Objectives You should be able to describe: The while Statement
Life is Full of Alternatives
Presentation transcript:

CSE1222: Lecture 6The Ohio State University1

Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout << “You are 18.” } else { cout << “You are not 18.”; }  Will output “You are 18.” Why? CSE1222: Lecture 6The Ohio State University2

Common Mistakes with Conditions (2) if (age = 18)  The equality operator == is different from the assignment operator =  We are actually assigning age to the value 18  The expression age = 18 evaluates to 18  So the condition (boolean expression) becomes this when executed: if (18) { cout << “You are 18.” }  0 evaluates to false and any other number evaluates to true. Thus, the boolean expression in the condition, i.e. 18, evaluates to true CSE1222: Lecture 6The Ohio State University3

else-if Statements (1)  The if-then-else statement allows for at most two alternatives to select The code to execute if the condition succeeds OR The code to execute if the condition fails  What if there are many alternatives to consider? CSE1222: Lecture 6The Ohio State University4

else-if Statements (2)  The variable age contains a person’s age: If 1 ≤ age ≤ 12, print “You are very young” If 13 ≤ age ≤ 19, print “You are a teenager” If 20 ≤ age ≤ 39, print “You are getting old” If 40 ≤ age, print “You are over the hill”  How do we handle many alternatives? CSE1222: Lecture 6The Ohio State University5

Solve It With What We Know (1) if (1 <= age && age <= 12)// Line 1 { cout << “You are a child” << endl; } if (13 <= age && age <= 19) // Line 2 { cout << “You are a teenager” << endl; } if (age <= 20 && age <= 39) // Line 3 { cout << “You are getting old” << endl; } if (40 <= age) // Line 4 { cout << “You are over the hill” << endl; } CSE1222: Lecture 6The Ohio State University6

 This works!  Is it undesirable? If so, why?  The value in age can only satisfy exactly of these ranges  If the condition at line 1 succeeds, do we need to continue checking the conditions at Lines 2, 3, and 4?  So this is a waste of time that the program could be using doing something more constructive!  Is there a better solution? CSE1222: Lecture 6The Ohio State University7

else-if Statements if (1 <= age && age <= 12) // Line 1 { cout << “You are a child” << endl; } else if (13 <= age && age <= 19) // Line 2 { cout << “You are a teenager” << endl; } else if (20 <= age && age <= 39) // Line 3 { cout << “You are getting old” << endl; } else if (40 <= age) // Line 4 { cout << “You are over the hill” << endl; } CSE1222: Lecture 6The Ohio State University8

 A much better solution in terms of efficiency  Only check other conditions upon failure!  Anytime a condition triggers true, run the corresponding statements and exit out of the selection structure  The use of else-if statements are perfect for multiple “exclusive selections” such as this CSE1222: Lecture 6The Ohio State University9

Notes about else-ifs  Like else statements, else-if statements are optional, but ALWAYS sandwiched in between the if- and the else statement  There is no limit to the number of else-if statements succeeding an if- statement  It is important to realize the difference between a chain of else-if s and a chain of if s CSE1222: Lecture 6The Ohio State University10

else-if Logic Error if (1 <= age && age <= 12) // Line 1 { cout << “You are a child” << endl; } else if (13 <= age && age <= 29) // Line 2 ERROR { cout << “You are a teenager” << endl; } else if (20 <= age && age <= 39) // Line 3 { cout << “You are getting old” << endl; } else if (40 <= age) // Line 4 { cout << “You are over the hill” << endl; } CSE1222: Lecture 6The Ohio State University11

Another Example of else-if if (a > 0) { //do something if condition succeeds } else if (b < 3) { //here, we know a ≤ 0 because the first condition //failed, now we also test for b < 3 do something //if condition succeeds } else { //here, we know neither conditions were met //do something else, if necessary } CSE1222: Lecture 6The Ohio State University12

ifExample.cpp... int main() { int a(0), b(0), c(0); cout << "Enter a, b, c: "; cin >> a >> b >> c; if (a < b) { if (b < c) { cout << "b < c" << endl; } else { cout = c" << endl; } } else if (a < c) { cout << "a < c" << endl; } else { cout = c" << endl; } return 0; } CSE1222: Lecture 6The Ohio State University13 What is the output on input:

Exercise  Write if-else-if statements which print: “You are too young to drive.” if age  14; “You can get a learners permit.” if age = 15; “You pay more for insurance.” if 16  age  25; “You can drive.” if age > 25; CSE1222: Lecture 6The Ohio State University14

The switch Statement  An alternative to the if-else chain (but not as general) switch (expression) { case value1:... case value2:... } (See Text) CSE1222: Lecture 6The Ohio State University15

CSE1222: Lecture 6The Ohio State University16

Error Handling  if-then statements are often used to detect and handle errors  Use cerr() instead of cout() for error output messages  Use exit() instead of return to quit a program on detecting an error CSE1222: Lecture 6The Ohio State University17

cerrExample.cpp #include // File cstdlib contains exit()... int main() { double x(0.0); cout << "Enter non-negative value: "; cin >> x; if (x < 0) { // Use cerr instead of cout. Use exit instead of return. cerr << "Error: Illegal negative value: " << x << endl; exit(20); } cout << "sqrt(" << x << ") = " << sqrt(x) << endl; return 0; } CSE1222: Lecture 6The Ohio State University18

exit()  To use exit(), we need: #include  To help in debugging, use a different number with each exit statement: exit(10); exit(20); exit(30); CSE1222: Lecture 6The Ohio State University19

cerrExample2.cpp... int main() { double x(0.0); cout << "Enter non-negative value: "; cin >> x; if (x < 0) { // Use cerr instead of cout. cerr << "Warning: Illegal negative value: " << x << endl; cerr << "Changing " << x << " to " << -x << endl; x = -x; } cout << "sqrt(" << x << ") = " << sqrt(x) << endl; return 0; } CSE1222: Lecture 6The Ohio State University20

Error Handling  cerr() instead of cout() Messages can be sent to a different place than cout() Forces messages to be printed immediately  exit() instead of return Quits the program and returns control to the operating system Frees up resources associated with the program “return” returns control to any calling program/function CSE1222: Lecture 6The Ohio State University21