Conditional Execution – Sections 4.2, 4.3 , 4.4 and 4.7

23
CS201 – Introduction to Computing – Sabancı University 1 Announcements Homework 2 is assigned at SUCourse About if statements and parametric functions The use of “if” is natural The use of “functions” is enforced The functions that you have to implement are explained in the homework document There are some other rules Please read the homework specification very carefully Deadline is Wednesday , October 14 , 2015, 1 9 :00

description

Conditional Execution – Sections 4.2, 4.3 , 4.4 and 4.7. Up to now, we have seen that instructions are executed unconditionally one after another. What if you want to execute an instruction depending on a condition? Selection: choose from among many options according to a criteria - PowerPoint PPT Presentation

Transcript of Conditional Execution – Sections 4.2, 4.3 , 4.4 and 4.7

Page 1: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 1

Announcements

Homework 2 is assigned at SUCourse About if statements and parametric functions The use of “if” is natural The use of “functions” is enforced

• The functions that you have to implement are explained in the homework document

There are some other rules• Please read the homework specification very carefully

Deadline is Wednesday, October 14, 2015, 19:00

Page 2: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 2

Conditional Execution – Sections 4.2, 4.3, 4.4 and 4.7

Up to now, we have seen that instructions are executed unconditionally one after another.

What if you want to execute an instruction depending on a condition?

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 You achieve conditional execution with if else statements

Page 3: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 3

Syntax

if (condition)

statementtrue;else

statementfalse;

If condition is TRUE then statementtrue is executed; if condition is FALSE then statementfalse is executed.

else and statementfalse are optional

if (condition)

statementtrue;

if condition is FALSE then nothing will be executed and execution continues with the next statement in the program

Page 4: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 4

More Syntax Condition must be in brackets 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){

statementtrue 1;statementtrue 2;...statementtrue N;

}else{

statementfalse 1;statementfalse 2;...statementfalse N;

}

DefinitonCompound block: Statements written within matching curly brackets

Page 5: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 5

Flow diagram of if-else

test condition

truestatements

true

nextstatement

false

falsestatements

Page 6: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 6

Example (not in the book)

Write a program that inputs two integer numbers and displays the minimum one.

Two solutions using if and else together using only if (no else)

Page 7: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 7

Solution 1 – with_if_else.cppint 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;

}

Page 8: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 8

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;

}

Page 9: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 9

Boolean type and expressions 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; } Boolean values have numeric equivalents

false is 0, true is any nonzero valueif (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

Page 10: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 10

Relational Operators Relational operators are used to compare values:

They take two operands operands can be literals, variables or expressions

Used for many types numeric comparisons string comparisons (lexicographical, i.e. alphabetical) boolean comparisons (false is less than true)

Operator Meaning Example use

< less than number < 5

<= less than or equal 0 <= number

> greater than 48 > 62

>= greater than or equal num1 >= num2

== equality check num1 == 0

!= inequality check num1 != num2

Page 11: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 11

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 true34-3 != 30+1 false

Let’s see some string comparison examples

string s1= "elma", s2= "armut", s3= "Elma";s1 < s2 falses3 < s2 true

Why s3 < s2 is true? ‘E’ has a smaller code than ‘a’ Uppercase letters have smaller codes than lowercase

letters

Page 12: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 12

Logical operators

Boolean expressions can be combined using logical operators: AND, OR, NOT In C++ we use && || ! respectively

A B A || B A && B

true true true true

true false true false

false true true false

false false false false

A !A

true false

false true

Page 13: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 13

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

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

elsecout << "number is in the range";

• Solution 3: using logical OR operator

if (num < 0 || num > 100)cout << "number is out of the range";

elsecout << "number is in the range";

Page 14: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 14

De Morgan’s Rules (Section 4.7)

Compare solution 2 and 3 two conditions are equivalent

(!(num >= 0 && num <= 100))

(num < 0 || num > 100)

De Morgan’s Rules (assume a and b are two boolean expressions)!(a && b) = !a || !b!(a || b) = !a && !b

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

Page 15: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 15

Operator Precedence - Revisited

Upper operator groups have precedence

Operator Explanation Associativity

+ - ! plus and minus signs, logical NOT right-to-left

* / % multiplication, division and modulus

left-to-right

+ - addition, subtraction left-to-right

<< >> stream insertion and extraction left-to-right

< <= > >= Inequality comparison operators left-to-right

== != equal, not equal comparison left-to-right

&& logical and left-to-right

|| logical or left-to-right

= += -= *= /= %=

assignment operators right-to-left

Page 16: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 16

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

Page 17: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 17

Nested if statements

if/else statements are inside other if/else statements Method to select from multiple choices Example: input a numeric grade and display messages

according to its value

0 .. 50 low

51 .. 70 average

71 .. 100 good

otherwise invalid grade 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

Page 18: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 18

if (condition_1)

{

statements_1true;

}

else if (condition_2)

{

statements_2true;

}

else if (condition_3)

{

statements_3true;

}

.

.

.

else

{

statements_allfalse;

}

Nested if-else Syntax (else after if) if condition_1 is TRUE then statements_1true are executed. All subsequent elses are skipped. if condition_1 is FALSE then check condition_2. If condition_2 is TRUE then

statements_2true are executed. All subsequent elses are skipped. if both condition_1 and condition_2

are FALSE then check condition_3. If condition_3 is TRUE then

statement_3true are executed. All subsequent elses are skipped.

.

.

. if all of the conditions are FALSE then

statement_allfalse are executed.

Page 19: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 19

if (condition_1)

{

if (condition_2)

{

if (condition_3)

{

statements_alltrue;

}

else

{

statements_true_1and2;

}

}

else

{

statements_true_1;

}

}

else

{

statements_1_false;

}

Nested if-else Syntax (if after if) For three conditions, use analogy for more condition cases

if condition_1 is TRUE then check

condition_2

if condition_2 is also TRUE then check condition_3if condition_3 is also TRUE

statements_alltrue are executed,

if condition_1 and 2 are TRUE but condition_3 is FALSEstatements_true_1and2 are executed,

if condition_1 is TRUE but condition_2 is FALSE

statements_true_1 are executed,

if condition_1 is FALSEstatements_1_false are executed.

Page 20: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 20

Short-circuit Evaluation Some subexpressions in Boolean expressions are not evaluated if the

entire expression’s value is already known using the subexpression evaluated so far

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

Page 21: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 21

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;

Do the above messages make sense? The problem is that it displays “odd number” for positive even

numbers and zero. Reason is that, although indentation says the reverse, else

belongs to second (inner) if Solution: use braces (see next slide)

Page 22: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 22

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;} Now else belongs to first if

Page 23: Conditional Execution – Sections 4.2, 4.3 ,  4.4  and 4.7

CS201 – Introduction to Computing – Sabancı University 23

if – else matching rule

Each else belongs to the nearest if for which there is no else and in the same compound block