1 / 34

Boolean Expressions and Flow Control

Learn about boolean expressions, relational and logical operators, and how they are used in flow control. Understand the benefits of short-circuit evaluation and how to optimize code using boolean expressions. Explore enumeration types and multiway branches.

cynthiap
Download Presentation

Boolean Expressions and Flow Control

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3 More Flow Of Control

  2. Boolean Expression • Expression that yields bool result • Include: 6 Relational Operators < <= > >= == != 3 Logical Operators ! && ||

  3. 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

  4. Boolean Expression (examples) (taxRate > .25) && (income < 20000) (temperature <= 75) || (humidity < .70) (age >= 21) && (age <= 60) (age == 21) || (age == 22)

  5. Precedence Chart Highest Lowest ++, --, !, - (unary minus), + (unary plus) *, /, % + (addition), - (subtraction) <<, >> <, <=, >, >= ==, != && || =

  6. “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

  7. 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.

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

  9. 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.

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

  11. 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 = -1, 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 ;

  12. 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.

  13. Multiway Branches • When there are more than 2 options to consider • Used in: • Nested if statements • Multiway if-else statements • switch statements

  14. Nested if Statements • An if statement nested inside another if statement • Indent each statement. • Use braces for clarity.

  15. 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.

  16. Dangling else in nested if statements (Solutions) • Use braces to set off inner else 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”; • Use null statement for else if (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”;

  17. 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 else Statement N+1

  18. 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

  19. 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.

  20. switch Statement (Syntax) switch ( Integral Expression) { case Constant1 : Statement(s); // optional case Constant2 : Statement(s); // optional . . . default : // optional Statement(s); // optional }

  21. 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.

  22. switch Statement (default case) default can be used for values not represented by any case label. Only 1 default statement in a switch.

  23. 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

  24. 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)

  25. 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.

  26. 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

  27. Chapter 2 Review • Open Chapter 2 slides • Review While and Do-While Loops • Review Increment and Decrement

  28. 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;

  29. 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 loop for (; 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 body for (i=0; i<10; i++) Omit everything for (;;) // (infinite loop) { //body of loop if (I % 5 == 0) break; // use break to exit loop } Accidentally eliminating loop body by placing a semicolon at the end for (i=0; i<10; i++); cout << i << endl; // Only 10 in the output

  30. 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

  31. 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.

  32. Loop Ending • List headed by size Input list known beforehand • Count controlled loop number 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 input Cannot read any more input from a file • Using boolean flag Raise flag when something happened

  33. 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 4 Row# 1: 0 1 2 3 4 Row# 2: 0 1 2 3 4

  34. 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

More Related