CS201 – Introduction to Computing – Sabancı University 1 Conditional Execution – Sections 4.2, 4.3, 4.4 and 4.7 l Up to now, we have seen that instructions.

Slides:



Advertisements
Similar presentations
Decision Structures - If / Else If / Else. Decisions Often we need to make decisions based on information that we receive. Often we need to make decisions.
Advertisements

Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
The "if structure" is used to execute statement(s) only if the given condition is satisfied.
Logic & program control part 3: Compound selection structures.
True or false A variable of type char can hold the value 301. ( F )
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
1 Lecture 8:Control Structures I (Selection) (cont.) Introduction to Computer Science Spring 2006.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
1 Conditionals In many cases we want our program to make a decision about whether a piece of code should be executed or not, based on the truth of a condition.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
C++ for Engineers and Scientists Third Edition
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
UNIT II Decision Making And Branching Decision Making And Looping
Introduction to Programming (in C++) Data and statements Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Repetition Statements Repeating an Action A specified number of times While a Condition is True Until a Condition is True.
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
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.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Announcements HW1 grades are announced at SUCourse You may see Belal Amro at his office hour for homework grades at FENS 2014 on Wednesday 10:40-12:30.
Other Conditional Methods. Conditional Operator Conditional Operator (?:) Conditional operator ( ?: ) – Ternary operator: 3 arguments expression1 ? expression2.
/* Documentations */ Pre process / Linking statements Global declarations; main( ) { Local Declarations; Program statements / Executable statements; }
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Decision making statements. Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
1 09/15/04CS150 Introduction to Computer Science 1 Life is Full of Alternatives Part 2.
Copyright 2003 Scott/Jones Publishing Making Decisions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 3 (2) & 4 September 8 & 10, 2009.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
PEG200/Saidatul Rahah 1.  Selection Criteria › if..else statement › relational operators › logical operators  The if-then-else Statement  Nested if.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
CPS120: Introduction to Computer Science Decision Making in Programs.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 9/26/05CS150 Introduction to Computer Science 1 Life is Full of Alternatives.
USING CONDITIONAL CODE AMIR KHANZADA. Conditional Statement  Conditional statements are the set of commands used to perform different actions based on.
Introduction to Programming Python Lab 7: if Statement 19 February PythonLab7 lecture slides.ppt Ping Brennan
Program Flow Control Addis Ababa Institute of Technology Yared Semu April 2012.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
An Introduction to Programming with C++1 The Selection Structure Tutorial 6.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Control Structures: Examples. for-loop example Q: If a=1, b=3, and x=7, what is the value of x when the loop terminates? A: x=1 for(k=a; k
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
IF STATEMENTS AND BOOLEAN EXPRESSIONS. BOOLEAN EXPRESSIONS Evaluate to a value of true or false Use relational or equivalence operators Boolean operators.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Flow of Control.
SELECTION STATEMENTS (1)
Bools & Ifs.
Computers & Programming Languages
Control Structures: Selection Statement
Bools & Ifs.
Visual Basic – Decision Statements
Control Structures Part 3
Understanding Conditions
There many situations comes in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations.
Control Structures: Selection Statement
Presentation transcript:

CS201 – Introduction to Computing – Sabancı University 1 Conditional Execution – Sections 4.2, 4.3, 4.4 and 4.7 l Up to now, we have seen that instructions are executed unconditionally one after another. l What if you want to execute an instruction depending on a condition? l Selection: choose from among many options according to a criteria ä E.g. If response is yes do this, else do that ä E.g. ä If year is a leap year, number of days is 366, else 365 if else statements

CS201 – Introduction to Computing – Sabancı University 2 Syntax if ( condition ) statement true ; else statement false ; l If condition is TRUE then statement true is executed, if FALSE statement false is executed. l else and statement false are optional if ( condition ) statement true ; ä if condition is FALSE then nothing will be executed and execution continues with the next statement in the program

CS201 – Introduction to Computing – Sabancı University 3 More Syntax l Condition must be in brackets l What happens if you have several statements to execute? ä write your statements within curly brackets ä book recommends using this all the time even if you have only one statement (defensive programming) if ( condition ) {... statement true list ;... } else {... statement false list ;... } Definiton Compound block: Statements written within matching curly brackets

CS201 – Introduction to Computing – Sabancı University 4 Example (not in the book) l Write a program that inputs two integer numbers and displays the minimum one. l Two solutions  using if and else together  using only if (no else )

CS201 – Introduction to Computing – Sabancı University 5 Solution 1 – with_if_else.cpp int main () { int num1, num2, min; cout << "Enter two numbers: "; cin >> num1 >> num2; if (num1 < num2) //check if first number is smaller than the second one { min = num1; //if so minimum is the first number } else { min = num2; //otherwise minimum is the second number } cout << "minimum of these two numbers is: " << min << endl; return 0; }

CS201 – Introduction to Computing – Sabancı University 6 Solution 2 – with_if.cpp (no else) int main () { int num1, num2, min; cout << "Enter two numbers: "; cin >> num1 >> num2; min = num1; // default assignment - minimum is the first number if (num2 < min) //check if second number is smaller than the first one { min = num2; //if so update the minimum, if not do nothing } cout << "minimum of these two numbers is: " << min << endl; return 0; }

CS201 – Introduction to Computing – Sabancı University 7 Boolean type and expressions l The condition in an if statement must be a Boolean expression (named for George Boole)  Values are true and false  bool is a built-in type like int, double int degrees; bool isHot = false; cout << "enter temperature: "; cin >> degrees; if (degrees > 35) { isHot = true; } l Boolean values have numeric equivalents ä false is 0, true is any nonzero value if (3*4 –8) cout << "hello"; else cout << "bye"; prints hello on sreen ä boolean output yields 0 (for false) or 1 (for true) cout << (4 < 5); prints 1 on screen cout << (5 == 7-2+1); prints 0 on screen

CS201 – Introduction to Computing – Sabancı University 8 Relational Operators l Relational operators are used to compare values: < less than <= less than or equal > greater than >= greater than or equal == equality check != inequality check l They take two operands ä operands can be literals, variables or expressions l Used for many types ä numeric comparisons ä string comparisons (lexicographical, i.e. alphabetical) ä boolean comparisons (false is less than true)

CS201 – Introduction to Computing – Sabancı University 9 Examples I used literals in the following numeric examples to see the results quickly. You can compare variables as well. 23 >= 45 false 49.0 == 7*7 true 34-3 != 30+1 false l Let’s see some string comparison examples string s1= "elma", s2= "armut", s3= "Elma"; s1 < s2 false s3 < s2 true Why s3 < s2 is true? ä ‘E’ has a smaller code than ‘a’ ä Uppercase letters have smaller codes than lowercase letters

CS201 – Introduction to Computing – Sabancı University 10 Logical operators l Boolean expressions can be combined using logical operators: AND, OR, NOT  In C++ we use && || ! respectively ABA || BA && B true falsetruefalse true false A!A truefalse true

CS201 – Introduction to Computing – Sabancı University 11 Example Range check: between and including 0 and 100,or not? If so, display a message saying that the number is in the range. If not, the message should say “out of the range”. Solution 1: using logical AND operator if (num >= 0 && num <= 100) cout << "number in the range"; else cout << "number is out of the range"; Solution 2: using logical AND and NOT operators if (!(num >= 0 && num <= 100)) cout << "number is out of the range"; else cout << "number is in the range"; Solution 3: using logical OR operator if (num 100) cout << "number is out of the range"; else cout << "number is in the range";

CS201 – Introduction to Computing – Sabancı University 12 De Morgan’s Rules (Section 4.7) l Compare solution 2 and 3 ä two conditions are equivalent (!(num >= 0 && num <= 100)) (num 100) l De Morgan’s Rules (assume a and b are two boolean expressions) ! (a && b) = !a || !b ! (a || b) = !a && !b l De Morgan’a Rules can be generalized to several expressions (e.g. 4 boolean expressions case) ! (a && b && c && d) = !a || !b || !c || !d ! (a || b || c || d) = !a && !b && !c && !d

CS201 – Introduction to Computing – Sabancı University 13 Operator Precedence - Revisited l Upper operator groups have precedence OperatorExplanationAssociativity + - ! plus and minus signs, logical NOTright-to-left * / % multiplication, division and modulus left-to-right + - addition, subtractionleft-to-right > stream insertion and extractionleft-to-right >= Inequality comparison operatorsleft-to-right == != equal, not equal comparisonleft-to-right && logical andleft-to-right || logical orleft-to-right = += -= *= /= %= assignment operatorsright-to-left

CS201 – Introduction to Computing – Sabancı University 14 Operator Precedence Examples cout << num1 < year; ä syntax error (very cryptic)  the problem is that << has precedence over < does not compile as intended  Solution: cout << (num1 < year); ä Advice: use parenthesized expressions in cout What about (0 <= num <= 100) for range check? ä not a syntax error ä but that expression does not make a range check. It is always true. Why? What is the value of !12+5&&32/35 ?  result is 0

CS201 – Introduction to Computing – Sabancı University 15 Nested if statements l if/else statements are inside other if/else statements l Method to select from multiple choices l Example: input a numeric grade and display messages according to its value low average good otherwise invalid grade l Several solutions exist (we’ll see three) – not in the book ä first two solution: ifs are after elses see if_after_else.cpp and if_after_else2.cpp ä third solution: ifs are after ifs see if_after_if.cpp

CS201 – Introduction to Computing – Sabancı University 16 Short-circuit Evaluation l Some subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known using the subexpression evaluated so far l Rule: Evaluate the first (leftmost) boolean subexpression. If its value is sufficient to judge about the value of the entire expression, then stop there. Otherwise continue evaluation towards right. if (count != 0 && scores/count < 60) { cout << "low average" << endl; } ä In this example, if the value of count is zero, then first subexpression becomes false and the second one is not evaluated. ä In this way, we avoid “division by zero” error (that would cause to crash the execution of the program) ä Alternative method to avoid division by zero without using short- circuit evaluation: if (count != 0) { if (scores/count < 60) { cout << "low average warning" << endl; }

CS201 – Introduction to Computing – Sabancı University 17 Dangling Else Problem if ( x % 2 == 0) if ( x < 0 ) cout << x << " is an even, negative number" << endl; else cout << x << " is an odd number << endl; l Do the above messages make sense? l The problem is that it displays “odd number” for positive even numbers and zero. l Reason is that, although indentation says the reverse, else belongs to second (inner) if l Solution: use braces (see next slide)

CS201 – Introduction to Computing – Sabancı University 18 Solution to Dangling Else Problem if ( x % 2 == 0) { if ( x < 0 ) cout << x << " is an even, negative number"<< endl; } else { cout << x << " is an odd number << endl; } l Now else belongs to first if

CS201 – Introduction to Computing – Sabancı University 19 if – else matching rule l Each else belongs to the nearest if for which there is no else and in the same compound block