34
Chapter 3 More Flow Of Control

Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Embed Size (px)

Citation preview

Page 1: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Chapter 3

More Flow Of Control

Page 2: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Boolean Expression

• Expression that yields bool result

• Include:6 Relational Operators

< <= > >= == != 3 Logical Operators

! && ||

Page 3: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Boolean Expression (examples)

taxRate is over 25% and income is less than $20000

temperature is less than or equal to 75 or humidity is less than 70%

age is between 21 and 60

age is 21 or 22

Page 4: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Boolean Expression (examples)

(taxRate > .25) && (income < 20000)

(temperature <= 75) || (humidity < .70)

(age >= 21) && (age <= 60)

(age == 21) || (age == 22)

Page 5: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Precedence Chart

• ++, --, !, - (unary minus), + (unary plus)• *, /, %• + (addition), - (subtraction)• <<, >>• <, <=, >, >=• ==, !=• &&• ||• =

Highest

Lowest

Page 6: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

“Short-Circuit” Evaluation

• C++ uses short circuit evaluation of logical expressions

• This means logical expressions are evaluated left to right and evaluation stops as soon as the final truth value can be determined

Page 7: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Short-Circuit Example

(age > 50) && (height > 60)When age is less than 50, evaluation can stop now because result of

&& is only true when both sides are true. It is already determined that the entire expression will be false.

(age > 50) || (height > 60)When age is greater than 50, evaluation can stop now because result

of is true if one side is true. It is already determined that the entire expression will be true.

However, when age is less than 50, evaluation must continue because result of the entire expression has not been determined.

Page 8: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Short-Circuit Benefits

• One Boolean expression can be placed first to “guard” a potentially unsafe operation in a second Boolean expression

• Time is saved in evaluation of complex expressions using operators || and &&

• Optimize code by placing most telling condition first.

Page 9: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Boolean evaluation on Arithmetic Expressions

• All yields either 1 or 0. – Thus, !5 = 0, !(-5) = 0, !0 = 1

• In C++, these values (0 and 1) can be used arithmetically, there is no difference between a 1 derived from !5 and 1 derived from 3 - 2.

Page 10: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Enumeration Types

• Is a type whose values are defined by a list of constants type int.enum Fruits {ORANGE, GRAPE, APPLE};

Page 11: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Enumeration Types (Notes)

• Sets must be finite• Members are called enumerators- unique identifier• Members are constants of type int with default value

starting from 0• Can initialize values to other than 0:

– enum sizes {small, medium = 10, large = 20}

• Values need not be unique• enum economy {recession = -1, depression = -2, growth = 1}

• Positive or negative numbers can be associated – enum economy {recession = -1, depression = -2, growth = 1}

• Can declare type and variable of that type at same time.– enum economy {recession = -1, depression = -2, growth = 1} bear ;

Page 12: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Enumeration Types (Notes)

• Can use in switch as case label->integral constants • Can compare 2 different enumerated type variables by

casting to int– Ex: int(jan_len) < int(false)

• Cannot read or write directly because the compiler doesn’t know the rules for this type.

• Why use enumerated types? – Used for program clarity

• Compiler will do type checking - prevent mixing types – Use 6 for Saturday and 6 for Date allows incorrect comparison.

Page 13: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Multiway Branches

• When there are more than 2 options to consider

• Used in:– Nested if statements – Multiway if-else statements – switch statements

Page 14: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Nested if Statements

• An if statement nested inside another if statement

• Indent each statement.

• Use braces for clarity.

Page 15: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Dangling else in nested if statements

• Compiler matches else with most recent if:

if (fuel-gauge_reading < 0.75)if (fuel-gauge_reading <0.25)

cout<<”Fuel very low. Caution!\n”;else

cout<<”Fuel over 3/4. Don’t stop now!\n”;

If fuel is 0.8, there is no ouput.If fuel is 0.5, output is:

Fuel over 3/4. Don’t stop now!

• Need to force compiler to match if-else correctly.

Page 16: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Dangling else in nested if statements (Solutions)

• Use braces to set off inner elseif (fuel-gauge_reading < 0.75){

if (fuel-gauge_reading <0.25)cout<<”Fuel very low. Caution!\n”;

}else

cout <<”Fuel over 3/4. Don’t stop now!\n”;

• Use null statement for elseif (fuel-gauge_reading < 0.75)

if (fuel-gauge_reading <0.25)cout<<”Fuel very low. Caution!\n”;

else; else

cout <<”Fuel over 3/4. Don’t stop now!\n”;

Page 17: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Multiway if-else Statements

• Is another form of nested if• EXACTLY 1 of these statements will be executed.• Syntax

if ( Expression1 ) Statement1

else if ( Expression2 )Statement2

.

.

.

else if ( ExpressionN )StatementN

elseStatement N+1

Page 18: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Multiway if-else Statements (Notes)

• Order is important.

• More efficient to put most probable result first.

if (grade<70) cout<<’F’;

else if ( grade>=70) cout<<‘C’;

else if (grade>=80) cout<<‘B’;

else cout<<‘A’;

If grade is 82: C

if (grade>=90) cout<<‘A’;

else if (grade>=80) cout<<‘B’;

else if (grade>=70) cout<<‘C’

else cout<<‘F’;

If grade is 82: B

Page 19: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

switch Statement

• Replaces the multiple alternative if statement

• Work with exact value only• Computer evaluates value of grade and

finds case label that matches that value.• Value must be of integral type (enum, int,

char, bool)• Will not work on string, double or float.• For efficiency, put most likely options

first.

Page 20: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

switch Statement (Syntax)

switch ( Integral Expression ){

case Constant1 :Statement(s); // optional

case Constant2 :Statement(s); // optional

. . .

default : // optionalStatement(s); // optional

}

Page 21: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

switch Statement (break use)

• Switch statement does action after case statement until it reaches break.

• No {} needed for multiple statements.

• If no break occurs in that case, execution will “fall through” and do the next case, etc. until a break is reached.

• break statement returns control to next line outside switch statement.

Page 22: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

switch Statement (default case)

default can be used for values not represented by any case label.

Only 1 default statement in a switch.

Page 23: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

switch Statement (Example)char finalGrade;…. // get value for finalGrade

switch ( finalGrade ){

case ‘A’ :cout << “Excellence!” << endl ;break ;

case ‘B’ :cout << “Good!” << endl ;break ;

case ‘C’ :cout << “Pass!” << endl ;break ;

case ‘D’ :cout << “Sorry!” << endl ;

case ‘F’ :cout << “You failed!” << endl ;break ;

default :cout << “It is not a grade! “ <<

endl ;break ; // not needed

}

finalGrade Output

A Excellence! B Good!

C Pass!

D Sorry!You failed!

F You failed!Anything else It is not a grade

Page 24: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

break and exit

• break exits that particular control statement. Used to break out of loops, switches.

• exit exits the program and can return a value EXIT_SUCCESS and EXIT_FAILURE (defined in stdlib.h) to the invoking process. (Not recommend to use in this class)

Page 25: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Blocks

• A compound statement which contains local variables – denoted by braces {}.

• Scope:– Visibility: Local variables can only be seen within the block.

Other functions and the main program do not know they exist. Therefore, there is no conflict and other functions or programs can use variables of the same name.

– Viability: Local variables are created and destroyed within the block. Saves on memory.

• Block allows use of global variables and local variables.

• local variable: visibility and viability is within block only!

• Blocks can be nested inside other blocks.

Page 26: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Blocks (Example)

float price 50.0;

int num;

… // Get num

{

float subtotal;

subtotal = price * num;

}

cout << “The total for “ << num

<< “ is “ << subtotal;

Syntax error!

float price 50.0;

int num;

… // Get num

{

float subtotal;

subtotal = price * num;

cout << “The total for “ << num

<< “ is “ << subtotal;

}

Legal

Page 27: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Chapter 2 Review

• Open Chapter 2 slides

• Review While and Do-While Loops

• Review Increment and Decrement

Page 28: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

FOR Loop

Used when Syntax:

for (initialize; test condition; update) {

… //loop body}

Example:int sum = 0;for (int i=1; i<=10; i++) //i is a local variable

sum = sum + i;

Page 29: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

FOR Loop (Notes)Can use commas to do more than 1 action in any part

for(i=1,sum=0;i<10; sum+=i++); //complete loop-no body needed

Can eliminate any part of loopfor (; Test; Action)- start missing - allows the same loop to be used for different starting points

as long as initialized before used. (allows flexibility)Ex: cin>>i;

for(; i<10; i++);

Increment in loop rather than in loop bodyfor (i=0; i<10; i++)

Omit everythingfor (;;) // (infinite loop) {

//body of loopif (I % 5 == 0) break; // use break to exit loop

}

Accidentally eliminating loop body by placing a semicolon at the endfor (i=0; i<10; i++);

cout << i << endl; // Only 10 in the output

Page 30: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Designing Loops

• What kind of loop to use – Must iterate at least once? Do-While

– Must iterate at least never? While

– Numerically increases/decreases by a set amount? While

– Know exactly how many times to execute. For

– Execution depends on events? While

• What do we need to know?– What is the process being repeated? THE BODY

– How must the process be initialized and updated? INITIALIZATION.

– What is the ending condition for our loop? EXIT CONDITIONS

Page 31: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Loop For Sums and Products

• Used when a value (accumulator) is to be increased/decreased by the new value.

• Notes:– Accumulator for a sum must be initialized to 0. – Accumulator for a product must be initialized to

nonzero.

Page 32: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Loop Ending

• List headed by sizeInput list known beforehand

• Count controlled loopnumber of iterations known before loops begin

• Ask before iteration Used for menus and for repeated processing

• Using SENTINELS A special value which has no valid meaning to the program and is

entered by the user to terminate a loop

• Running out of inputCannot read any more input from a file

• Using boolean flagRaise flag when something happened

Page 33: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Nest Loops

• A loop within a loop.

• Example:for (int i=0; i<3; i++)

{

cout << “Row# “ << i << “: ”;

for (int j=0; j<5; j++)

cout << j << “ ”;

cout << endl;

}

Row# 0: 0 1 2 3 4Row# 1: 0 1 2 3 4Row# 2: 0 1 2 3 4

Page 34: Chapter 3 More Flow Of Control. Boolean Expression Expression that yields bool result Include: 6 Relational Operators >= == != 3 Logical Operators !&&||

Debugging Loops

• Set breakpoint at the beginning of the loop. Check the LCV value when this breakpoint is hit.

• Set breakpoint at the first line of the loop body. Check if the execution stops at this breakpoint.

• Repeat 2 above steps would help to find problem with the loops