cs 103 lecture 3 slides
play

CS 103 Lecture 3 Slides Control Structures Mark Redekopp 2 - PowerPoint PPT Presentation

1 CS 103 Lecture 3 Slides Control Structures Mark Redekopp 2 Announcements Lab 2 Due Friday 3 Review Write a program to ask the user to enter two integers representing hours then minutes. Output the equivalent number of


  1. 1 CS 103 Lecture 3 Slides Control Structures Mark Redekopp

  2. 2 Announcements • Lab 2 – Due Friday

  3. 3 Review • Write a program to ask the user to enter two integers representing hours then minutes. Output the equivalent number of seconds. • To get started… – Go to http://bytes.usc.edu/cs103/in-class-exercises • printseconds – We've started the program for you…look at the • General template for a program with the #includes, using namespace std; and int main() function which returns 0 – We've declared variables where you can store the input and computation results – Now you add code to • Get input from the user • And compute the answer and place it in the 'sec' variable

  4. 4 If..else statements MODULE 5: CONDITIONAL STATEMENTS

  5. 5 Comparison Operators • Control structures like if, while, and for require conditions to determine what code should execute • To perform comparison of variables, constants, or expressions in C/C++ we can use the basic 6 comparison operators Operator(s) Meaning Example Equality if(x == y) == Inequality if(x != 7) != Less-than if(x < 0) < Greater-than if(y > x) > Less-than OR equal to if(x <= -3) <= Greater-than OR equal to if(y >= 2) >=

  6. 6 Logical AND, OR, NOT • Often want to combine several conditions to make a decision • Logical AND => x > 0 && y > 0 • Logical OR => x == 1 || x == 2 • Logical NOT => !(x < 0) • Precedence (order of ops.) => ! then && then || – !cond1 || cond2 && !cond3 – ( ( !cond1 ) || (cond2 && ( !cond3 ) ) ) A B AND A B OR A NOT False False False False False False False True False True False False True True True False True False False True False True True True True True True True

  7. 7 Exercise • Which of the following is NOT a condition to check if the integer x is in the range [-1 to 5] • x >= -1 && x <= 5 • -1 <= x <= 5 • !( x < -1 || x > 5) • x > -2 && x < 6

  8. 8 bools, ints, and Conditions • Loops & conditional statements require a condition to be evaluated resulting in a true or false result. • In C/C++… – 0 means false / Non-Zero means true – bool type available in C++ => ‘ true ’ and ‘ false ’ keywords can be used but internally • true = non-zero (usually 1) and • false = 0 • Any place a condition would be used a bool or int type can be used and will be interpreted as bool int x = 100; bool done = false; int x=100, y=3, z=0; if(x) while( ! done ) if( !x || (y && !z) ) { x--; } { cin >> done; } { /* code */ } • Example:

  9. 9 Conditions and DeMorgans • Write a condition that eats a sandwich if it has neither tomato nor lettuce – if ( !tomato && !lettuce) { eat_sandwich(); } – if ( !(tomato || lettuce) ) { eat_sandwich(); } • DeMorgan's theorem says there is always two ways to express a logic condition – !a && !b  !(a || b) – !a || !b  !(a && b) • More details in EE 109 and CS 170

  10. 10 If..Else Flow Chart if ( condition1 ) { // executed if condition1 is true True False } condition else { // executed if condition1 // above is false } // following statements If Block Else Statements Block Statements Following statements

  11. 11 If…Else If…Else • Use to execute only if ( condition1 ) { certain portions of code // executed if condition1 is true } • else if is optional else if ( condition2 ) { – Can have any number of // executed if condition2 is true // but condition1 was false else if statements } • else is optional else if ( condition3 ) { • { … } indicate code // executed if condition3 is true // but condition1 and condition2 associated with the if, // were false } else if, else block else { optional // executed if neither condition if else if else if else // above is true }

  12. 12 else if if ( condition1 ) { // executed if condition1 is True } else if ( condition2 ) { // executed if condition2 is True True False condition // but condition1 was False } 1 else These 2 are equivalent { // executed if neither condition True False cond2 condition // above is True } if ( condition1 ) Else If Else If Block { If Block Else Statements Block Statements Statements Statements // executed if condition1 is True Statements } else { if ( condition2 ){ Following // executed if condition2 is True statements // but condition1 was False } else Following { // executed if neither condition Statements // above is True } }

  13. 13 Single Statement Bodies • The Rule: Place code for an if (x == 5) y += 2; if, else if, or else construct in else curly braces { … } y -= 3; • The Exception: – An if or else construct with a if (x == 5) single statement body does not y += 2; else require { … } if(x < 5) – Another if counts as a single y = 6; statement else • Prefer { … } even in single y = 0; statement bodies so that editing later does not introduce bugs

  14. 14 PROBLEM SOLVING IDIOMS

  15. 15 Rule/Exception Idiom • Name : Rule/Exception // Default action • Description : Perform a default if( /* Exceptional Case */ ) { action and then us an ‘if’ to // Code to apply to // exceptional case correct for exceptional cases } • Structure : Default action code Structure followed by if statement with code to correct the exceptional bool primeMember = /* set somehow */; case double shippingFee = 7.99; if( primeMember == true ) • Example(s) : { shippingFee = 0; – Shipping for "members" } Example

  16. 16 Look-up Table Idiom • Name : Look-up Table (Parallel cases) if( /* Condition 1 */ ) { – A table can describe the mapping of input // Case 1 code to output } else if( /* Condition 2 */ ) • Description : Break input into { // Case 2 code mutually exclusive cases, taking some } else if( /* Condition 3 */ ) action or producing some output in { each case // Case 3 code } • Structure : Single level else { /* Default */ // Default code 'if..else if..else' statement } Score Grade Look-up Table Structure (input) (output) if( weather == "hot" ) { > 90 A clothing = "t-shirt"; Weather Dress } 80-89 B else if( weather == "mild" ) { Hot T-shirt 70-79 C clothing = "long sleeves"; } Mild Long Sleeves 55-69 D else { /* Default */ clothing = "sweater"; Cold Sweater < 55 F }

  17. 17 Decision Tree (Subcase) Idiom • Name : Decision Tree (Subcase) if( /* Condition 1 */ ) { • Description : The result of one // Case 1 code condition determines which if( /* Subcondition 1a */ ) { // Subcase 1a code condition (subcase) to check next } else { • Structure : Nested 'if' statements // Subcase 1b code } } else if( /* Condition 2 */ ) Customer Service Call Menu { // Case 2 code Top-level Account Hours of if( /* Subcondition 2a */ ) { Cases: Operation Issues // Subcase 2a code } } Sub-Cases: Balance Cancel

  18. 18 Exercises • Conditionals In-Class Exercises – discount – weekday – nth

  19. 19 The Right Style • Is there a difference int x; between the following cin >> x; two code snippets if( x >= 0 ) { cout << "Positive"; } • Both are equivalent but if( x < 0 ) { cout << "Negative"; } – Two if statements implies both can execute – An if..else implies a int x; cin >> x; mutually exclusive relationship where only 1 if( x >= 0 ) { cout << "Positive"; } can execute else { cout << "Negative"; } • For mutually exclusive cases, use if..else for clarity sake

  20. 20 Find the bug // What’s the problem below • What's the problem with int x; this code… cin >> x; if (x = 1) { cout << "x is 1" << endl; } else • Common mistake is to { cout << "x is not 1" << endl; } use assignment '=' rather than equality comparison '==' operator // What’s the problem below int x; • Assignment puts 1 into x cin >> x; and then uses that value if (x = 1) // x == 1 of x as the "condition" { cout << "x is 1" << endl; } else – 1 = true so we will { cout << "x is not 1" << endl; } always execute the if portion

  21. 21 Switch (Study on own) • Again used to execute only switch(expr) // expr must eval to an int certain blocks of code { • Cases must be a constant case 0: // code executed when expr == 0 • Best used to select an action break; case 1: when an expression could be 1 // code executed when expr == 1 of a set of constant values break; case 2: • { … } around entire set of cases case 3: case 4: and not individual case // code executed when expr is • Computer will execute code // 2, 3, or 4 break; until a break statement is default: // code executed when no other encountered // case is executed – Allows multiple cases to be break; combined } • Default statement is like an else statement

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend