1 / 24

ECE 103 Engineering Programming Chapter 22 Selection

ECE 103 Engineering Programming Chapter 22 Selection. Herbert G. Mayer, PSU CS Status 6/22/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE. Syllabus. If if-else if-else if Switch Triadic Conditional Expression

derry
Download Presentation

ECE 103 Engineering Programming Chapter 22 Selection

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. ECE 103 Engineering ProgrammingChapter 22Selection Herbert G. Mayer, PSU CS Status 6/22/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE

  2. Syllabus • If • if-else • if-else if • Switch • Triadic Conditional Expression • Nested Selection Statements

  3. Making Decisions in Programs A selection statement uses a conditional test to control the flow of execution in a program “conditional test” is AKA “conditional expression” or “boolean expression” A conditional test contains relational and/or logical expressions Conditional test evaluates to “true” or “false”: If test is “true” (non-zero), one group of statements is executed, known as the “Then Clause” If test is “false” (zero), a different group of statements is executed

  4. Decisions can be documented by a flowchart or by pseudocode: expression branch A branch B IF expression is true THEN Execute branch A ELSE Execute branch B END IF true false Example of 2-way true or false decision

  5. Selection Statements in C In C, logic states have these definitions: “false” is the zero value (e.g., 0, 0.0, '\0') “true” is any non-zero value (e.g., -1, 5, 12.4, 'A’) C has three types of selection statements based on the if keyword: if if–else if–else if any number of times C has an additional selection called switch

  6. if pre-code; if (expression) Statement; post-code; Statement post-code pre-code T expression F

  7. expression must be inside parentheses ( ). Statement can be a single statement or a block: if (expression) Statement; /* Single statement */ if (expression) { Statement_1; /* Statement block */  Statement_k; } All statements in the block are executed if the expression is true.

  8. Example: #include <stdio.h> #define TRUE 1 #define FALSE 0 #define LO_LIMIT 20 #define HI_LIMIT 100 int main( void ) { // main int N; /* Input value */ int low = FALSE, high = FALSE; printf( "Enter N: ” ); scanf( "%d", &N ); /* Check input range */ if( N < LO_LIMIT ) low = TRUE; if( N > HI_LIMIT ) high = TRUE; if( low || high ) printf("Out of range.\n"); if( !low && !high ) printf("Within range.\n"); return 0; } if( temperature <= 65 ) turn_heat_on = 1; if( temperature > 65 ) turn_heat_on = 0; if( x < 0 ) { printf("x is negative.\n”); } //end if if( x < 0 ) { printf("x is negative.\n”); y = abs(x); } //end if Note: Indentation improves clarity. 7

  9. if–else pre-code; if (expression) Statement_T; else Statement_F; post-code; post-code pre-code T F expression Statement_T Statement_F

  10. Example: #include <stdio.h> #define TRUE 1 #define FALSE 0 #define LO_LIMIT 20 #define HI_LIMIT 100 int main( void ) { // main int N; /* Input value */ printf("Enter N: "); scanf("%d", &N); /* Check input range */ if( N < LO_LIMIT || N > HI_LIMIT ) printf("Out of range.\n"); else printf("Within range.\n"); // end if return 0; } if( temperature <= 65 ) turn_heat_on = 1; else turn_heat_on = 0; if( age >= 18 ) { printf( "Adult\n” ); allow_vote = 1; }else{ printf( "Pre-Adult\n” ); allow_vote = 0; } //end if 9

  11. Example: /* This is wrong! */ if( y ) m = 1; printf( "Yes!” ); else m = -1; is actually seen by the compiler as if( y ) m = 1; printf( "Yes!” ); else m = -1; Write code that does this: if y is true, then set m to 1 and display "Yes!". Otherwise, set m to -1 and display nothing. /* This is correct */ if( y ) { m = 1; printf( "Yes!” ); }else{ m = -1; } //end if 10

  12. if–else if pre-code; if (expression_1) Statement_1; else if (expression_2) Statement_2; else Statement_3; post-code; post-code pre-code expression_1 Statement_1 Statement_2 Statement_3 expression_2 T F T F Note: It is else if, not elseif.

  13. Example: #include <stdio.h> int main( void ) { // main int score; /* Numeric grade */ char grade; /* Letter grade */ printf("Enter score: "); scanf("%d", &score); /* Check grade brackets */ if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; printf("Grade = %c\n", grade); return 0; } //end main if( x > 0 ) { printf("Positive\n"); p_count++; }else if( x < 0 ) { printf( "Negative\n” ); n_count++; }else{ printf( "Zero\n” ); z_count++; } //end ifs 12

  14. switch switch (expression) if (expression==const_1) { { caseconst_1: Statements_1; Statements_1; } break; else if (expression==const_2) caseconst_2:{ Statements_2; Statements_2; break; } … … default: else Statements_d; { break; Statements_d; } //end switch } //end if

  15. expression must be inside parentheses and evaluate to a single char or integer value A case value must evaluate to a single char or integer constant that is known at compile-time A case value cannot be a string or floating-point number If expression matches a case value, then its associated statements are executed until a break is encountered 14

  16. When break is encountered, the switch exits and execution continues at post-code If no break exists in a case block, execution “falls through” to the following case default handles the “none of the above” case.It can be omitted if not needed 15

  17. Example: #include <stdio.h> #include "myfunctions.h" #define WARNING 1 #define DANGER 2 #define PANIC 3 int main (void) { int status, num_warnings = 0; scanf("%d", &status); switch (status) { case WARNING: printf("What?\n"); num_warnings++; break; case DANGER: printf("Leave now!\n"); notify_friends(); break; case PANIC: printf("HELP ME!!!!!\n"); freak_out(10); break; default: printf("All is fine.\n"); } return 0; } switch(experience) { case 'n': printf("Newbie\n"); N++; break; case 'a': disp('Amateur'); A++; break; case 'p': case 'P': printf("Professional\n"); P++; break; } 16

  18. Tip:Selection Ordering To improve the performance of a multi-conditional selection, arrange it in order of most likely occurrence. Example: Use an if-else if selection to test a character variable. The character value can be 'a', 'b', 'c', 'd', or 'e'. They are not all equally likely. Sorted from most likely to occur to least likely to occur: 'c', 'd' 'b' 'a' Assume c and d are equally likely. Inefficient ordering: if (ch == 'a') {…} else if (ch == 'b') {…} else if (ch == 'c') {…} else if (ch == 'd‘) {…} Better arrangement: if (ch=='c' || ch=='d') {…} else if (ch == 'b') {…} else if (ch == 'a') {…} MOST LEAST 17

  19. Triadic Conditional Expression var = (condition) ? expr1 : expr2; is equivalent to if (condition) var = expr1; else var = expr2; Both expressions should evaluate to the same data type as var. 18

  20. Example: /* If voltage > 2, then set state to high (1) else set state to low (0) */ state = (voltage > 2.0) ? 1 : 0; Example: /* Sinc calculation handles x == 0 case */ y = (fabs(x) < 1e-8) ? 1.0 : sin(x)/x; 19

  21. Nested Selection Statements The body of a selection statement can contain another selection statement within it. Each else is matched to the nearest if or else if. 20

  22. Example: Convert the if-else if to a nested if. /* Nested if version */ if (x == 0) t++; else { if (x==1 || x==2) printf("zen state\n"); else { if (x < 0) { m = sin(Q); f = 3 * m * sqrt(m); } else printf("Moo\n"); } } /* if-else if version */ if (x == 0) t++; else if (x==1 || x==2) printf("zen state\n"); else if (x < 0) { m = sin(Q); f = 3 * m * sqrt(m); } else printf("Moo\n"); 21

  23. Example: if (t >= 0 && t < 100) if (F < 1500e3) flim = 143.5; else { flim = 500.0; overload = 1; if (cps == 'x') cnt++; } else if (t2 > 750) { printf("D22 max\n"); if (!mox) mox = 1; else pc += 10; } else done = 1; if (t >= 0 && t < 100) if (F < 1500e3) flim = 143.5; else { flim = 500.0; overload = 1; if (cps == 'x') cnt++; } else if (t2 > 750) { printf("D22 max\n"); if (!mox) mox = 1; else pc += 10; } else done = 1; Use indenting to make it clear what you really mean! 22

  24. Nesting can lead to ambiguous situations. If necessary, use braces to clarify your intentions. Example: if (x >= 0) if (y > 5) printf("Hi!\n"); else printf("Goodbye!\n"); Is the "else" associated with the first or second "if"? if (x >= 0) if (y > 5) printf("Hi!\n"); else printf("Goodbye!\n"); if (x >= 0) { /* Braces clarify */ if (y > 5) printf("Hi!\n"); else printf("Goodbye!\n"); } 23

More Related