1 / 35

Chapter 5

Chapter 5. If-Else statement. Control Flow. The order of executing statements in a program. What are the possibilities?. condition. condition. true. false. Statement 1. true. Statement 2. false. Statements 1. Statements 2. Statements . Statement 3. sequential. Repetition/looping.

faolan
Download Presentation

Chapter 5

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 5 If-Else statement

  2. Control Flow • The order of executing statements in a program. What are the possibilities? condition condition true false Statement 1 true Statement 2 false Statements 1 Statements 2 Statements Statement 3 sequential Repetition/looping Selection/branching

  3. IF statement int num1, num2; float quotient; cin >> num1 >> num2; quotient = float(num1) / num2; // Any possible issues? // What if num2 is zero? if (num2 != 0) quotient = float(num1) / num2;

  4. IF statement if ( expression ) statement; if ( num2 != 0 ) quotient = float(num1) / num2; • Semantics • do computation only when num2 is not zero • the statement is skipped when num2 is zero • Syntax • condition inside () • != for not equal • Style • on separate lines • indent 3 spaces • a space before and after each character How to print an error message?

  5. IF-ELSE statement if ( expression ) statement; else statement; if (num2 != 0) quotient = float(num1) / num2; else cout << "Error: divided by zero!" << endl; What if I also want to print the quotient if possible?

  6. if ( expression ) { statements; } else { statements; } IF-ELSE statement if (num2 != 0) { quotient = float(num1) / num2; cout << "The quotient is" << quotient << endl; } else cout << "Error: divided by zero!" << endl; • Semantics • do different things when num2 is zero or not • Syntax • braces for multiple statements (statement block) • braces are optional for single statement • Style • braces on separate lines

  7. Statement Block if (hour <= 40) salary = hour * payRate; else salary = ( hour - 40 ) * payRate * 1.5 + 40 * payRate; cout << endl << "You have " << ( hour - 40 ) << " hours overtime." << endl; cout << "Your salary is " << salary << endl; if (hour <= 40) salary = hour * payRate; else { salary = ( hour - 40 ) * payRate * 1.5 + 40 * payRate; cout << endl << "You have " << ( hour - 40 ) << " hours overtime." << endl; } cout << "Your salary is " << salary << endl; What will be the output if hour = 30 and payRate = 10? • Indentation and blank line is a style issue. It does not make a block. • Braces are required for block of multiple statements.

  8. Example: Find the MAX of two numbers int num1, num2, max; cin >> num1 >> num2; if ( num1 > num2 ) max = num1; else max = num2; cout << “The max value is ” << max << endl; // Another way if ( num1 >= num2 ) max = num1; else max = num2; cout << “The max value is ” << max << endl; How to find the MAX of three numbers?

  9. Nested IF statement int num1, num2, num3, max; cin >> num1 >> num2 >> num3; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3; cout << “The max value is ” << max << endl; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3;

  10. The Dangling else • else always look backwards for the closest if. • How about ? max = 0; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; max = 0; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; suppose num1 = 10, num2 = 20, num3 = 4, what is the value of max? max = 0; if ( num1 > num2 ) { if ( num1 > num3 ) max = num1; } else max = num3; Use braces to change the pairing!

  11. Multi-way branching using If-else if-else int score; char grade; cin >> score; if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else // NO if here! grade = 'F'; cout << “Your Grade: ” << grade; if (score >= 90) grade = ‘A’; if (score >= 80 && score < 90) grade = ‘B’; if (score >= 70 && score < 80) grade = ‘C’; if (score >= 60 && score < 70) grade = ‘D’; if (score < 60) grade = ‘F’; Which is better? What is the problem? Magic number! Can we change the order? NO!

  12. Order in If-else if-else int score; char grade; cin >> score; if (score >= 80) grade = ‘B'; else if (score >= 90) grade = ‘A'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else // NO if here! grade = 'F'; cout << “Your Grade: ” << grade; You will never get an ‘A’!

  13. Debugging in HiC • Run  set breakpoint • Run  run • Run  step over • Run  watches • Run  clear all breakpoints use debugging tool to observe the control flow!

  14. Problem: Input range check • check whether the 2 integer inputs are both in the range [10, 50]. 10 <= num1 <= 50 AND 10 <= num2 <= 50 How to express it in C++?

  15. Conditions if ( logical expression ) statement; • The value of a logical expression is either true or false. • The bool data type: true or false int x = 6, y = 5; bool result; result = ( x == y ); result = ( x != y ); result = ( x >= 7 );

  16. Comparison Operators == != > >= < <= No Space between!

  17. A common mistake int num; cin >> num ; if ( num = 10 ) cout << “num equals 10” << endl; else cout << “num doesn’t equals 10” << endl; • num = 10 is an assignment statement • num == 10 is a Boolean expression • conditions can only be Boolean expressions!

  18. Comparison Operators != !> // NO! <= // Yes! ≤ // NO! <= // Yes!

  19. Compare characters Expression • ‘M’ < ‘R’ • 'M' < 'm' • 't' < 'm' • 'a' >= '9' • 'a' >= 9 • '0' < 9 Result true true false true true false Comparing the ASCII codes!

  20. Compare strings • You can compare • two string variables • a string variable and a string literal • You CANNOT compare two string literals! • ==: two strings are exactly the same • >,>=,<,<=: character by character check

  21. Compare strings string myName = “Yan”; string herName = “Margaret”; string hisName = “Kyle”; Expression • myName < herName • myName == "Yan" • hisName > "Kevin" • "Zack" > "Kevin" • herName >= "Margareta" • myName < "Zack" + hisName Result false true true ERROR false true

  22. Logical (Boolean) operators • AND && • OR || • NOT ! • logical operators are used to connect multiple conditions into one compound condition. • the operands MUST be of bool data type! • precedence: ! > && > ||

  23. Truth Table

  24. Short-circuit evaluation • Evaluation proceeds from left to right • Evaluation stops as soon as the computer knows the value of the whole expression. • AND: if a sub-expression is false • OR: if a sub-expression is true • Example: • 10 * 2 - 5 > 0 || 5 / 0 == 1 • 10 * 2 - 5 < 0 && 5 / 0 == 1 • 10 * 2 - 5 > 0 || !5 true false ERROR

  25. Operator Precedence ( ) !, Unary +, Unary – *, /, % +, - <, <=, >, >= ==, != && || =

  26. De Morgans's Laws • ! ( cond1 && cond2 ) == ! cond1 || ! cond2 • ! ( cond1 || cond2 ) == ! cond1 && ! cond2

  27. Exercise char a = 'a', b = 'b'; string myName = "Yan"; int num1 = 3, num2 = 5; Expression • !(a == b) • !(a == b || a >= 97) • ! a != b • myName.length()<num1 && myName == "Yan" • num1 >= num2 && a != b • a && b Result true false ERROR false false ERROR

  28. Example: MAX of three numbers int num1, num2, num3, max; cin >> num1 >> num2 >> num3; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3; cout << “The max value is ” << max << endl; if ( num1 > num2 && num1 > num3 ) max = num1; else if ( num2 > num3 ) max = num2; else max = num3;

  29. Examples: input range check • check whether the 2 integer inputs are both in the range [10, 50]. int num1, num2; cin >> num1 >> num2; if ( num1 >= 10 && num1 <= 50 && num2 >= 10 && num2 <= 50 ) cout << "Both inputs are in the range [10, 50]. " << endl; else cout << "One or more inputs are out of range. " << endl;

  30. Examples: input range check (2) • check whether at least one of the 2 integer inputs is in the range [10, 50]. int num1, num2; cin >> num1 >> num2; if ( ( num1 >= 10 && num1 <= 50 ) || ( num2 >= 10 && num2 <= 50 ) ) cout << “One or more inputs are in the range [10, 50]. " << endl; else cout << “Both inputs are out of range. " << endl; Do we need braces?

  31. Examples: input range check (3) • check input range: 2 integer inputs • are they both positive? • are they both negative? • are they one positive and one negative? • print out the answers to all three questions in the same order. How will you design the program? rangeCheck3.cpp

  32. More Examples • couponCalc.cpp • compute the total charge after applying coupon code • decisionTree.cpp • get the result of a psychological test given the answers to a sequence of questions Y 1 N 2 2 3 3 3 3 4 4 4 4 4 4 4 4 A C D C A C C D B B A C D C A B after class exercise: try to combine conditions to compound conditions

  33. Summary • IF • IF-ELSE • Nested IF-ELSE • The dangling else • Conditions • Comparison operators • Logical operators • Short-circuit evaluation • IF-ELSE IF-ELSE

  34. After Class Exercise • write a program to find out whether the input is an odd or even number. • write a program to check if the input name belongs to a given list of names {Alex King, Alice Wonderland, John Smith}.

  35. C++ Style Check List • Comment Block! • Constants should be before main(). • Do not indent constants! • Magic Number! (any number besides -1, 0, and 1) • Braces on separate lines! • Brace alignment! • Line should not be too long (<=74 characters). • Alignment of multi-line statements! • Indentation! • Space before and after operator! • No blank line before/after else! • No blank line before/after brace!

More Related