Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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

3 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

4 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 )

5 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; }

6 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; }

7 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

8 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)

9 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

10 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

11 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";

12 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

13 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

14 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

15 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

16 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; }

17 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)

18 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

19 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


Download ppt "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."

Similar presentations


Ads by Google