Download presentation
Presentation is loading. Please wait.
Published byWesley Smith Modified over 9 years ago
1
CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements
2
Outline Control Structures Control Structures Conditions Conditions The if Statement The if Statement Decision Steps in Algorithms: Case Study Decision Steps in Algorithms: Case Study The switch Statement The switch Statement Common Programming Errors Common Programming Errors
3
Control Structures All programs can be written with three basic structures All programs can be written with three basic structures Sequence Selection Repetition (Looping, Iteration) Compound statement Compound statement{ Statement 1; …… Statement n; }
4
Selection Process 1Process 2 Condition
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) 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 Relational expressions Logical expressions Logical expressions
6
Relational Expressions operand relational operator operand operand relational operator operand OperatorMeaningExample < less than age < 30 > greater than age > 30 <= less than or equal to taxable <= 20 >= greater than or equal to temp >= 98.6 == equal to grade == 90 != not equal to number != 250
7
Character Examples ‘1’ < ‘7’ 1True ‘D’ <= ‘Z’ 1True ‘c’ >= ‘v’ 0False ‘m’ <= ‘M’ System dependent ‘b’ == ‘B’ 0False
8
More Examples key = ‘ m ’ ; i = 5; j = 7; k = 12; x = 22.5; (i + 2) = = (k – 1) ((3 * i) – j) < 22 (i + (2 * j)) > k (‘a’ + 1) = = ‘b’ (k + 3) <= ((-j) + (3 * i)) (key – 1) > ‘p’ (key + 1) == ‘n’ 25 <= (x + 1.0)
9
Logical Expressions operand logical operator operand OperatorNameUseTruth && Logical and (a > 10) && (b < 20) (b < 20) both operands true || Logical or (a > 10) || (b < 20) either operand true ! Logical complement !(a == b) complement operand
10
OperatorPrecedence function calls ! + - & (unary operators) * / % + - = > = > == != &&||= Operator Precedence 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 Short-circuit evaluation
12
English Condition in C English Condition Logical Expression x and y are greater than z x is equal to 1.0 or 3.0 x is in the range z to y, inclusive x is outside the range z to y
13
Complementing a Condition Complementing item == SENT: Complementing item == SENT: ! (item == SENT) or item != SENT DeMorgan ’ s Theorem DeMorgan ’ s Theorem The complement of expr 1 && expr 2 is written as comp 1 || comp 2, where comp 1 is the complement of expr 1 and comp 2 is complement of expr 2 The complement of expr 1 || expr 2 is written as comp 1 && comp 2, where comp 1 is the complement of expr 1 and comp 2 is complement of expr 2 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 && n < 10); is_letter = (ch >= ‘ A ’ && ch = ‘ A ’ && ch <= ‘ Z ’ ) || (ch >= ‘ a ’ && ch = ‘ a ’ && ch <= ‘ z ’ ); int even; even = (n % 2 == 0);
15
The if Statement Syntax Syntax if (condition) statement1;elsestatement2; If condition is true, statement1 will be executed If condition is true, statement1 will be executed If condition is false, statement2 will be executed If condition is false, statement2 will be executed The else part is optional The else part is optional
16
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 ” ); Display “Cruiser” Display “Frigate” == ‘C’ ? TF
17
Compound Statements Syntax Syntax if (condition) { statements; }else } 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 Statementsxytemp 12.55.0? if (x > y) { temp = x; temp = x; x = y; x = y; y = temp; y = temp;
20
Nested if Statements if (expression1) statement1;else if (expression2) statement2;elsestatement3;
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 (gender == ‘M’ ) if (age >= 18) if (age >= 18) if (age <= 26) if (age <= 26) printf(“ All criteria are met. \n”); printf(“ All criteria are met. \n”); if (marital_status == ‘S’ && gender == ‘M’ && age >= 18 && age = 18 && age <= 26 ) printf(“ All criteria are met. \n”); 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 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;elsestatement_e;
28
Example if (marks >= 75) printf ( “ Distinction\n ” ) ; printf ( “ Distinction\n ” ) ; else if (marks >= 60) printf ( “ Pass\n ” ) ; printf ( “ Pass\n ” ) ; else if (marks >= 50) printf ( “ Average\n ” ) ; printf ( “ Average\n ” ) ;else printf ( “ Fail\n ” ) ; printf ( “ Fail\n ” ) ; if (marks >= 50) printf ( “ Average\n ” ) ; printf ( “ Average\n ” ) ; else if (marks >= 60) printf ( “ Pass\n ” ) ; printf ( “ Pass\n ” ) ; else if (marks >= 75) printf ( “ Distinction\n ” ) ; printf ( “ Distinction\n ” ) ;else printf ( “ Fail\n ” ) ; printf ( “ Fail\n ” ) ; Order of the conditions will affect the outcome as well as efficiency.
29
Decision Table Salary Range ($) Base Tax ($) Percentage of Excess 0.00- 14,999.99 0.0015 15,000.00- 29,999.99 2,250.0018 30,000.00- 49,999.99 5,400.0022 50,000.00- 79,999.99 11,000.0027 80,000.00- 150,000.00 21,600.0033
31
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). 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).
32
Analysis Analysis Input: double heading; /* in degree */ Output: equivalent bearing message (direction you face, an angle between 0-90, direction to turn) Heading in Degrees Bearing Computation 0 – 89.999 …… north (heading) east 90 – 179.999 …… south (180.0 – heading) east 180 – 269.999 …… south (heading – 180.0) west 270 – 360 north (360.0 – heading) west
33
Case Study Design Design Initial Algorithm: 1. Display instructions 1. Display instructions 2. Get the compass heading 2. Get the compass heading 3. Display the equivalent compass bearing 3. Display the equivalent compass bearing Algorithm Refinement on Step 3 multiple alternative if statements multiple alternative if statements catch the value out of range (0, 360), show the error message catch the value out of range (0, 360), show the error message
34
The switch Statement switch ( integer or char expression ) { caseconst1: statements 1 break; caseconst2: statements 2; break; …… default: statements d; break; }
35
switch Selection is based on one variable or expression Selection is based on one variable or expression MUST have INTEGER or CHAR condition for branching MUST have INTEGER or CHAR condition for branching Like a special instance of if else-if else... Like a special instance of if else-if else... Evaluates expression then compares it to CONSTANT VALUES in each case Evaluates expression then compares it to CONSTANT VALUES in each case
36
switch There can be as many “case” values as needed 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 ‘:’ There can be as few “statements” as needed following the ‘:’ The default statement is optional
37
Flowchart of switch Statement ? 123default
38
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); }
39
/* 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; }
40
Common Programming Errors Cannot use a a && x a && x < b e.g. if (0 <= x <= 4) printf(“Condition is true\n”); When x = 5, what is the result? When x = 5, what is the result? Equality operator is == instead of = Equality operator is == instead of = e.g. int age = 30; if (age = 40) if (age = 40) printf(“Happy Birthday”); Always prints Happy Birthday!!!!
41
Common Programming Errors if (condition) { if (condition) { …… …… } Use braces to change the if-else order Use braces to change the if-else order Always try to use multiple alternative format when writing a nested if statement Always try to use multiple alternative format when writing a nested if statement else match with closest unmatched if else match with closest unmatched if switch statement format switch statement format
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.