Topic 4: Control structures • • • • • • Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming Errors A. Abhari CPS125 1 Control Structures • Using for control the flow of the execution in a program or function. • They are a combination of the individual instructions into a single logical unit with one entry point and one exit point. Three kinds of control instructions are: • Sequence • Selection • Repetition A. Abhari CPS125 2 Control Structures Sequence flow: • A compound statement is used to specify sequential flow { statement 1; statement 2; ….. Control flow statement n; } • A function body consist of a single compound statement A. Abhari CPS125 3 Conditions • An expression that is either false (represented by 0) or true (usually represented by 1) For example : rest_heart_rate > 75 • Conditions establish criteria for executing or skipping a group of statements A. Abhari CPS125 4 Relational and Equality Operators variable relational-operator variable/constant variable equality-operator variable/constant Examples : x <= 0 salary < MIN_SALARY x>Y dependents >= 5 item == 3 (It is not the assignment operator ‘=‘ ) num != SENTINEL A. Abhari CPS125 5 Logical Operators • Three logical operators && (and), || (or) and ! (not) can be used to form logical expressions: Examples: n >= 0 && n <= 100 0<= n && n <= 100 ! ( 0 <= n && n <= 100 ) 0 > n || n > 100 A. Abhari CPS125 6 Logical operators • && (and) op1 op2 op1 && op2 ------------------------------------T T T T F F F T F F F F A. Abhari CPS125 7 Logical operators • || (or) op1 op2 op1 || op2 ------------------------------------T T T T F T F T T F F F A. Abhari CPS125 8 Logical operators • ! (not) op1 ! op1 -------------------T F F T • The result of logical expression is always 0 or 1. C accepts any nonzero value as a representation of true A. Abhari CPS125 9 Operator Precedence Operator Precedence --------------------------------------------------------function calls highest ! + - & (unary operators) */% +< <= >= > == != && || = lowest A. Abhari CPS125 10 Operator Precedence -2 – 1 * 2 => -4 ( 2 < 3 || 2 > 3 ) && 2 > 1 1 (true) 2 < 3 || 2>3 && 2 >1 =>1(true) !0 || ( 4.0 + 2.0 >= 3.0 – 2.0) => 1(true) !(0 || ( 4.0 + 2.0 >= 3.0 – 2.0)) => 0(false) A. Abhari CPS125 11 Short-Circuit Evaluation • For && and || C uses the short-circuit evaluation. It means stopping the evaluation of the logical expression as soon as its value can be determined Examples: ! 1 && ( 5+ 7 >= 3 ) 1 || ( 6+ 4 < 7 ) A. Abhari CPS125 12 Examples • Range checking x > 2 && y > 2 but not using x && y > 2 • Character comparison ‘9’ >= ‘0’ 1(true) ‘Z’ == ‘z’ 0(false) ‘a’ <= ch && ch <=‘z’ true if ch is a lowercase letter ‘a’ <= ‘A’ system dependent A. Abhari CPS125 13 Logical Assignment • Example 1: int age, senior_citizen; scanf(“%d”, &age); senior_citizen = (age >= 65); • Example 2: int even, n; scanf(“%d”, &n); even = ( n %2 == 0 ) A. Abhari CPS125 14 Complementing a Condition • The condition item == sent complemented as !(item == sent ) or item != sent • DeMorgan’s Theorem age > 25 && ( s == ‘S’ || s == ‘D’) complemented as age <=25 || ( s != ‘S’ && s != ‘D’) A. Abhari CPS125 15 THE if STATEMENT if ( mark > 50 ) printf ( “pass”); else printf(“fail”); F T mark> 50 Display “fail” A. Abhari Display “pass” CPS125 16 THE if STATEMENT if ( mark == 50 ) mark = mark + 1; if ( mark > 50 ) printf ( “pass”); else printf(“fail”); A. Abhari T F mark==50 mark = mark + 1 CPS125 17 THE if STATEMENT • if statement (One Alternative) if ( condition ) statementT; • if statement ( Two Alternatives) if ( condition ) statementT; else statementF; A. Abhari CPS125 18 if ( mark == 50 ) mark = mark + 1; if ( mark > 50 ) printf ( “pass”); else printf(“fail”); if ( mark >= 90 ) printf (“outstanding\n” ); printf (“Enter another mark”); It is not depending on the last if statement A. Abhari CPS125 19 Errors, when using if statement • if mark == 100 printf (“highest mark \n” ); • if (mark = 100) printf (“highest mark \n” ); • if (mark == 100); printf (“highest mark \n” ); A. Abhari CPS125 20 if statements with compound statements • Computing the increase in fruit fly population if ( pop_today > pop_yesterday ) { growth = pop_today – pop_yesterday; growth_pct = 100.0 * growth /pop_yesterday; printf ( “ The growth percentage is %.2f \n” , growth_pct); } A. Abhari CPS125 21 if statements with compound statements • Keeping records of safety rating of the fleet cars if (ctri <= MAX_SAFE_CTRI) { printf(“Car #%d: safe\n”, auto_id); safe = safe + 1; } What is the result when omitting this brace else { printf(“Car #%d: unsafe\n”, auto_id); unsafe = unsafe + 1; } A. Abhari CPS125 22 if statements with compound statements if (condition) { statements; } else { statements; } A. Abhari CPS125 23 Tracing an if statement if (x > y) { /* Switch x and y */ temp = x; /* Store old x in temp */ x = y; /* Store old y in x */ y = temp; } Stat. x y temp -------------------------------------------------------------12.5 5.0 ? If (x>y) { temp = x; 12.5 x = y; 5.0 y = temp; 12.5 A. Abhari CPS125 24 Nested if Statements if (expression1) statement1; else if (expression2) statement2; else statement3; A. Abhari CPS125 25 Nested if statements if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else num_zero = num_zero + 1; • Sequence of if statements: (It is less readable and less efficient because all conditions are always tested) if (x > 0) num_pos = num_pos + 1; if (x < 0) num_neg = num_neg + 1; if (x == 0) num_zero = num_zero + 1; A. Abhari CPS125 26 Multiple-Alternative Decision Form of Nested if • Can be used instead of nested if, when each false task (except for the last) is followed by if-then-else statement • The conditions are evaluated in sequence until a true condition is reached • Upon a true condition the statements in the else part are skipped • The words else and if the next condition appear on the same line if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else /* x equal to 0 */ num_zero = num_zero + 1; A. Abhari CPS125 27 In multiple-alternative decision, the order of conditions affects the result. For example by placing if (salary <= 150000.00) at the beginning of the following if statement the result for the $40,000 salary input would be wrong: if (salary < 0.0) tax = -1.0; else if (salary < 15000.00) /* first range */ tax = 0.15 * salary; else if (salary < 30000.00) /* second range */ tax = (salary - 15000.00) * 0.18 + 2250.00; else if (salary < 50000.00) /* third range */ tax = (salary - 30000.00) * 0.22 + 5400.00; else if (salary < 80000.00) /* fourth range */ tax = (salary - 50000.00) * 0.27 + 11000.00; else if (salary <= 150000.00) /* fifth range */ tax = (salary - 80000.00) * 0.33 + 21600.00; else tax = -1.0; Multiple variables nested if if (marital_status == ‘S’) if (gender == ‘M’ ) if (age >= 18) if (age <= 26) printf(“ All criteria are met. \n”); Is equal to: if (marital_status == ‘S’ && gender == ‘M’ && age >= 18 && age <= 26 ) printf(“ All criteria are met. \n”); A. Abhari CPS125 29 • Always C associates an else with the most recent if 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”); A. Abhari CPS125 30 • By placing braces, else can be associated to the further if, For example: if (road_status == ‘S’){ if (temp > 0) { printf(“Wet roads ahead\n”); printf(“Stopping time doubled\n”); } } else printf(“Drive carefully\n”); A. Abhari CPS125 31 Case study: Computing Compass Bearing /* * Transforms a compass heading to a compass bearing using this table: * * 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 */ #include <stdio.h> void instruct(void); int main(void) { double heading; /* Input - compass heading in degrees */ instruct(); /* Get compass heading. */ printf("Enter a compass heading> "); scanf("%lf", &heading); /* Display equivalent compass bearing. */ if (heading < 0.0) printf("Error -- negative heading (%.1f)\n", heading); else if (heading < 90.0) printf("The bearing is north %.1f degrees east\n", heading); else if (heading < 180.0) printf("The bearing is south %.1f degrees east\n", 180.0 - heading); else if (heading < 270.0) printf("The bearing is south %.1f degrees west\n", heading - 180.0); else if (heading <= 360.0) printf("The bearing is north %.1f degrees west\n", 360.0 - heading); else printf("Error--heading > 360 (%.1f)\n", heading); return (0); } A. Abhari CPS125 33 /* * Display program purpose and user instructions */ void instruct(void) { printf("To convert a compass heading to a "); printf("compass bearing,\nenter a value "); printf("between 0.0 and 360.0 at the prompt.\n"); } • The results of bearing computation in the printf statements can be stored into output variable bearing. In that case it can be used later. • For testing the program the boundary values of 0, 90, 180, 270, 360 and also an out of range value can be used as the program input. A. Abhari CPS125 34 The switch Statement • The switch statement is useful when selection is based on the value of single value or of a simple expression (called controlling expression). • This value of controlling expression should be of type int or char, but not of type double • The controlling expression is evaluated and compared to each of the case labels in the label sets until a match is found • When this match is found the statements following the case label are executed until break statement then the rest of switch statement is skipped. • If no case label value matches the controlling expression, the entire switch statement body is skipped unless it contains a default label. In that case the statement following the default label are executed. A. Abhari CPS125 35 Syntax of the switch statement switch ( integer or char expression ) { Controlling Expression case const1: statements 1 break; Label Set1 case const2: statements 2; break; …… default: statements d; break; } A. Abhari CPS125 36 Example of a switch Statement with Type char Case Labels switch (class) { case 'B': case 'b': printf("Battleship\n"); break; case 'C': case 'c': printf("Cruiser\n"); break; case 'D': case 'd': printf("Destroyer\n"); break; case 'F': case 'f': printf("Frigate\n"); break; default: printf("Unknown ship class %c\n", class); } Example of a switch Statement with Type int Case Labels switch (watts) { case 25: life = 2500; break; what is the result of omission of this break ? case 40: case 60: life = 1000; break; case 75: case 100: life = 750; break; default: life =0; } what is the result of omission of this brace ? • What is the equivalent nested if statement for this switch statement ? A. Abhari CPS125 38 Common Programming Errors • Using 0 < x < 4 instead of (0< x && x<4) in the if statements • Confusing the operator = with == • Forgetting parentheses in the if condition • Missing braces in compound statements of the if statements • Confusion when matching else with related if in the nested if statements • Missing break and default in the switch statement A. Abhari CPS125 39