1 / 41

CPS 125: Digital Computation and Programming

CPS 125: Digital Computation and Programming. Selection Structures: if and switch Statements. Outline. Control Structures Conditions The if Statement Decision Steps in Algorithms: Case Study The switch Statement Common Programming Errors. Control Structures.

ashton
Télécharger la présentation

CPS 125: Digital Computation and Programming

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. CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements

  2. Outline • Control Structures • Conditions • The if Statement • Decision Steps in Algorithms: Case Study • The switch Statement • Common Programming Errors

  3. Control Structures • All programs can be written with three basic structures • Sequence • Selection • Repetition (Looping, Iteration) • Compound statement { Statement 1; …… Statement n; }

  4. Condition Process 1 Process 2 Selection

  5. Condition • An expression to perform comparisons, which is either false (represented by 0) or true (usually represented by 1, actually could be anything other than 0) • Relational expressions • Logical expressions

  6. Relational Expressions • operand relational operator operand

  7. Character Examples

  8. More Examples key = ‘m’; i = 5; j = 7; k = 12; x = 22.5;

  9. Logical Expressions • operand logical operator operand

  10. Operator Precedence Operator Precedence function calls ! + - & (unary operators) * / % + - < <= >= > == != && || = highest lowest

  11. Examples x = 3.0; y = 4.0; z = 2.0; flag = 0; 1. !flag 2. x + y / z <= 3.5 3. !flag || (y + z >= x – z) 4. !(flag || (y + z >= x – z)) • Short-circuit evaluation

  12. English Condition in C

  13. Complementing a Condition • Complementing item == SENT: ! (item == SENT) or item != SENT • DeMorgan’s Theorem • The complement of expr1 && expr2 is written as comp1 || comp2, where comp1 is the complement of expr1 and comp2 is complement of expr2 • The complement of expr1 || expr2 is written as comp1 && comp2, where comp1 is the complement of expr1 and comp2 is complement of expr2 • age <= 25 && (status == ‘S’ || status == ‘D’)

  14. Logical Assignment int senior_citizen; senior_citizen = (age >= 65); Expression !senior_citizen && gender == ‘M’ int in_range, is_letter; in_range = (n > -10 && n < 10); is_letter = (ch >= ‘A’ && ch <= ‘Z’) || (ch >= ‘a’ && ch <= ‘z’); int even; even = (n % 2 == 0);

  15. The if Statement • Syntax if (condition) statement1; else statement2; • If condition is true, statement1 will be executed • If condition is false, statement2 will be executed • The else part is optional

  16. F T == ‘C’ ? Display “Frigate” Display “Cruiser” Examples if (crsr_or_frgt == ‘C’) printf(“Cruiser\n”); else printf(“Frigate\n”); if crsr_or_frgt == ‘C’ printf(“Cruiser\n”); if (crsr_or_frgt == ‘C’); printf(“Cruiser\n”);

  17. Compound Statements • Syntax if (condition) { statements; } else { statements; } if (ctri <= MAX_SAFE_CTRI) { printf(“Car #%d: safe\n”, auto_id); safe = safe + 1; } else { printf(“Car #%d: unsafe\n”, auto_id); unsafe = unsafe + 1; } if (ctri <= MAX_SAFE_CTRI) printf(“Car #%d: safe\n”, auto_id); safe = safe + 1; else ……

  18. Example if (x > y) { temp = x; /* Store old x in temp */ x = y; /* Store old y in x */ y = temp; /* Store old x in y */ } Tracing its execution with x = 12.5; y = 5.0;

  19. Tracing an if Statement

  20. Nested if Statements if (expression1) statement1; else if (expression2) statement2; else statement3;

  21. if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else num_zero = num_zero + 1; if (x > 0) num_pos = num_pos + 1; if (x < 0) num_neg = num_neg + 1; if (x == 0) num_zero = num_zero + 1;

  22. Multiple Variables to Test /* print a message if all criteria are met */ if (marital_status == ‘S’) if (gender == ‘M’ ) if (age >= 18) if (age <= 26) printf(“ All criteria are met. \n”); if (marital_status == ‘S’ && gender == ‘M’ && age >= 18 && age <= 26 ) printf(“ All criteria are met. \n”);

  23. if (road_status == ‘S’) if (temp > 0) { printf(“Wet roads ahead\n”); printf(“Stopping time doubled\n”); } else { printf(“Icy roads ahead\n”); printf(“Stopping time quadrupled\n”); } else printf(“Drive carefully\n”);

  24. Nested if Statements • May be nested to any depth • Each “statement” may be a compound statement • else matches closest unmatched if • Braces may be used to change if-else matching

  25. Example What is the difference, if any? • if (expression1) • if (expression2) • statement1; • else • statement2; • if (expression1) • if (expression2) • statement1; • else • statement2;

  26. if (road_status == ‘D’) printf(“Drive carefully\n”); else if (temp > 0) { printf(“Wet roads ahead\n”); printf(“Stopping time doubled\n”); } else { printf(“Icy roads ahead\n”); printf(“Stopping time quadrupled\n”); }

  27. Multiple-Alternative Decision if (expression_1) statement_1; else if (expression_2) statement_2; …… else if (expression_n) statement_n; else statement_e;

  28. Example if (marks >= 50) printf (“Average\n”) ; else if (marks >= 60) printf (“Pass\n”) ; else if (marks >= 75) printf (“Distinction\n”) ; else printf (“Fail\n”) ; if (marks >= 75) printf (“Distinction\n”) ; else if (marks >= 60) printf (“Pass\n”) ; else if (marks >= 50) printf (“Average\n”) ; else printf (“Fail\n”) ; Order of the conditions will affect the outcome as well as efficiency.

  29. Decision Table

  30. Case Study: Computing Compass Bearings • Problem: Write a program that automates the table you use to transform compass headings in degrees (0 to 360 degrees) to compass bearings. The program should require entry of a compass heading, such as 110 degrees, and should display the corresponding bearing (e.g. south 70 degrees east).

  31. Analysis • Input: double heading; /* in degree */ • Output: equivalent bearing message (direction you face, an angle between 0-90, direction to turn)

  32. Case Study • Design • Initial Algorithm: 1. Display instructions 2. Get the compass heading 3. Display the equivalent compass bearing • Algorithm Refinement on Step 3 multiple alternative if statements catch the value out of range (0, 360), show the error message

  33. The switch Statement switch ( integer or char expression ) { case const1: statements 1 break; case const2: statements 2; break; …… default: statements d; break; }

  34. switch • Selection is based on one variable or expression • MUST have INTEGER or CHAR condition for branching • Like a special instance of if else-if else ... • Evaluates expression then compares it to CONSTANT VALUES in each case

  35. switch • There can be as many “case” values as needed • There can be as many “statements” as needed following the ‘:’ (no brace needed) • There can be as few “statements” as needed following the ‘:’ • The default statement is optional

  36. Flowchart of switch Statement ? 1 2 3 default

  37. switch (class) { case 'B': case 'b': printf("Battleship\n"); break; case 'C': case 'c': printf("Cruiser\n"); break; case 'F': case 'f': printf("Frigate\n"); break; default: printf("Unknown ship class %c\n", class); }

  38. /* determine average life expectancy of a standard light bulb */ switch (watts) { case 25: life = 2500; break; case 40: case 60: life = 1000; break; case 75: case 100: life = 750; break; default: life =0; }

  39. Common Programming Errors • Cannot use a < x < b to represent a range comparison, instead, we should use x > a && x < b e.g. if (0 <= x <= 4) printf(“Condition is true\n”); When x = 5, what is the result? • Equality operator is == instead of = e.g. int age = 30; if (age = 40) printf(“Happy Birthday”); Always prints Happy Birthday!!!!

  40. Common Programming Errors • if (condition) { …… } • Use braces to change the if-else order • Always try to use multiple alternative format when writing a nested if statement • else match with closest unmatched if • switch statement format

More Related