410 likes | 563 Views
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.
E N D
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 • All programs can be written with three basic structures • Sequence • Selection • Repetition (Looping, Iteration) • Compound statement { Statement 1; …… Statement n; }
Condition Process 1 Process 2 Selection
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
Relational Expressions • operand relational operator operand
More Examples key = ‘m’; i = 5; j = 7; k = 12; x = 22.5;
Logical Expressions • operand logical operator operand
Operator Precedence Operator Precedence function calls ! + - & (unary operators) * / % + - < <= >= > == != && || = highest lowest
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
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’)
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);
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
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”);
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 ……
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;
Nested if Statements if (expression1) statement1; else if (expression2) statement2; else statement3;
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;
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”);
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”);
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
Example What is the difference, if any? • if (expression1) • if (expression2) • statement1; • else • statement2; • if (expression1) • if (expression2) • statement1; • else • statement2;
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”); }
Multiple-Alternative Decision if (expression_1) statement_1; else if (expression_2) statement_2; …… else if (expression_n) statement_n; else statement_e;
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.
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).
Analysis • Input: double heading; /* in degree */ • Output: equivalent bearing message (direction you face, an angle between 0-90, direction to turn)
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
The switch Statement switch ( integer or char expression ) { case const1: statements 1 break; case const2: statements 2; break; …… default: statements d; break; }
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
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
Flowchart of switch Statement ? 1 2 3 default
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); }
/* 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; }
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!!!!
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