Presentation is loading. Please wait.

Presentation is loading. Please wait.

A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.

Similar presentations


Presentation on theme: "A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming."— Presentation transcript:

1 A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming Errors

2 A. Abhari CPS1252 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

3 A. Abhari CPS1253 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

4 A. Abhari CPS1254 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

5 A. Abhari CPS1255 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

6 A. Abhari CPS1256 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

7 A. Abhari CPS1257 Logical operators && (and) op1 op2 op1 && op2 ------------------------------------- T T T T F F F T F F F F

8 A. Abhari CPS1258 Logical operators || (or) op1 op2 op1 || op2 ------------------------------------- T T T T F T F T T F F F

9 A. Abhari CPS1259 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

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

11 A. Abhari CPS12511 Operator Precedence -2 – 1 * 2 => -4 ( 2 3 ) && 2 > 1  1 (true) 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)

12 A. Abhari CPS12512 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 )

13 A. Abhari CPS12513 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

14 A. Abhari CPS12514 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 )

15 A. Abhari CPS12515 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’)

16 A. Abhari CPS12516 THE if STATEMENT if ( mark > 50 ) printf ( “pass”); else printf(“fail”); Display “pass” Display “fail” mark> 50 TF

17 A. Abhari CPS12517 THE if STATEMENT if ( mark == 50 ) mark = mark + 1; if ( mark > 50 ) printf ( “pass”); else printf(“fail”); mark==50 mark = mark + 1 F T

18 A. Abhari CPS12518 THE if STATEMENT if statement (One Alternative) if ( condition ) statement T ; if statement ( Two Alternatives) if ( condition ) statement T ; else statement F ;

19 A. Abhari CPS12519 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

20 A. Abhari CPS12520 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” );

21 A. Abhari CPS12521 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); }

22 A. Abhari CPS12522 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; }

23 A. Abhari CPS12523 if statements with compound statements if (condition) { statements; } else { statements; }

24 A. Abhari CPS12524 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

25 A. Abhari CPS12525 Nested if Statements if (expression1) statement1; else if (expression2) statement2; else statement3;

26 A. Abhari CPS12526 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;

27 A. Abhari CPS12527 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;

28 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;

29 A. Abhari CPS12529 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 ” );

30 A. Abhari CPS12530 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”);

31 A. Abhari CPS12531 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”);

32 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 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);

33 A. Abhari CPS12533 /* 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); }

34 A. Abhari CPS12534 /* * 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.

35 A. Abhari CPS12535 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.

36 A. Abhari CPS12536 Syntax of the switch statement switch ( integer or char expression ) { caseconst1: statements 1 break; caseconst2: statements 2; break; …… default: statements d; break; } Controlling Expression Label Set1

37 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); }

38 A. Abhari CPS12538 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 ?

39 A. Abhari CPS12539 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


Download ppt "A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming."

Similar presentations


Ads by Google