Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 103 Engineering Programming Chapter 22 Selection

Similar presentations


Presentation on theme: "ECE 103 Engineering Programming Chapter 22 Selection"— Presentation transcript:

1 ECE 103 Engineering Programming Chapter 22 Selection
Herbert G. Mayer, PSU CS Status 6/2 6/19/2015 Initial content copied verbatim from ECE 103 material developed by Professor Phillip 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 Example of 2-way true or false decision
Decisions can be documented by a flowchart or by pseudocode: IF expression is true THEN Execute branch A ELSE Execute branch B END IF expression branch A branch B 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; if expression is
Execution Sequence true ( != 0 ) Statement is executed Execution then continues at post-code false ( == 0 ) Statement is skipped Execution continues at post-code

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: Note: Indentation improves clarity.
#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 y = abs(x); Note: Indentation improves clarity. 7

9 if–else pre-code; if (expression) Statement_T; else Statement_F;
post-code; pre-code expression post-code Statement_T T F Statement_F if expression is Execution Sequence true ( != 0 ) Statement_T is executed Execution continues at post-code false ( == 0 ) Statement_F is executed

10 Example: if( temperature <= 65 ) turn_heat_on = 1; else
#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! */ Write code that does this: if( y )
printf( "Yes!” ); else m = -1; is actually seen by the compiler as 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; pre-code expression_1 post-code Statement_1 T F expression_2 Statement_2 Statement_3 Note: It is else if, not elseif.

13 Example: if( x > 0 ) { printf("Positive\n"); p_count++;
#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) { {
{ { case const_1: Statements_1; Statements_1; } break; else if (expression==const_2) case const_2: { Statements_2; Statements_2; break; } … … default: else Statements_d; { break; Statements_d; } //end switch } //end if

15 A case value cannot be a string or floating-point number
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: switch(experience) { case 'n': printf("Newbie\n"); N++;
#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(); case PANIC: printf("HELP ME!!!!!\n"); freak_out(10); default: printf("All is fine.\n"); } return 0; switch(experience) { case 'n': printf("Newbie\n"); N++; break; case 'a': disp('Amateur'); A++; case 'p': case 'P': printf("Professional\n"); P++; } 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; /* 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.
/* 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"); /* Nested if version */ if (x == 0) t++; else { if (x==1 || x==2) printf("zen state\n"); if (x < 0) m = sin(Q); f = 3 * m * sqrt(m); } printf("Moo\n"); 21

23 Example: Use indenting to make it clear what you really mean!
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; pc += 10; 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; pc += 10; done = 1; Use indenting to make it clear what you really mean! 22

24 Nesting can lead to ambiguous situations
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


Download ppt "ECE 103 Engineering Programming Chapter 22 Selection"

Similar presentations


Ads by Google