Download presentation
Presentation is loading. Please wait.
Published byTamsin Hubbard Modified over 9 years ago
1
A First Book of ANSI C Fourth Edition Chapter 4 Selection
2
A First Book of ANSI C, Fourth Edition2 Objectives Relational Expressions The if and if-else Statements The if-else Chain The switch Statement Case Study: Data Validation Common Programming and Compiler Errors
3
A First Book of ANSI C, Fourth Edition3 Introduction Flow of control refers to the order in which a program’s statements are executed Any algorithm can be built using combinations of four standardized flow of control structures: –Normal flow of control for all programs is sequential –Selection is used to select which statements are performed next based on a condition –Repetition is used to repeat a set of statements –Invocation is used to invoke a sequence of instructions using a single statement, as in calling a function
4
A First Book of ANSI C, Fourth Edition4 4.1 Relational Expressions Simplest decision structure: if (condition) statement executed if condition is true –The condition is evaluated to determine its numerical value, which is interpreted as either true (non-zero) or false (0) –If condition is “true” the statement following the if is executed; otherwise, this statement is not executed The condition used in all of C’s if statements can be any valid C expression –Most commonly, a relational expression (can yield only 0 or 1)
5
A First Book of ANSI C, Fourth Edition5 Relational Expressions (continued)
6
A First Book of ANSI C, Fourth Edition6 Relational Expressions (continued)
7
A First Book of ANSI C, Fourth Edition7 Relational Expressions (continued) Relational expressions are also known as conditions A relational expression evaluates to 1 (true) or 0 (false) –The expression 3 < 4 has a value of 1 –The expression 2.0 > 3.3 has a value of 0 –The value of hours > 0 depends on the value of hours Character data can also be compared using relational operators
8
A First Book of ANSI C, Fourth Edition8 Relational expressions are sometimes called conditions, and we will use both terms to refer to these expressions. Like all C expressions, relational expressions are evaluated to yield a numerical result. In the case of relational expressions, the value of the expression can only be an integer value of 1 or 0. A condition that we would interpret as true evaluates to an integer value of 1, and a false condition results in an integer value of 0.
9
A First Book of ANSI C, Fourth Edition9 For example, because the relationship 3 3.3 is always false, the expression has a value of 0.
10
A First Book of ANSI C, Fourth Edition10 This can be verified using the statements printf(“The value of 3<4 is %d”, 3<4); printf(“\nThe value of 2.0>3.3 is %d”, 2.0>3.3); which results in the display The value of 3<4 is 1 The value of 2.0>3.3 is 0
11
A First Book of ANSI C, Fourth Edition11 The value of a relational expression such as hours >0 depends on the value stored in the variable hours. In addition to numerical operands, character data can also be compared using relational operators. For example, in the ASCII code the letter A is stored using a code having a lower numerical value than the letter B, the code for a B is lower in value than the code for a C, and so on..
12
A First Book of ANSI C, Fourth Edition12 For character sets coded in this manner, the following expressions are evaluated as listed Expression Value Interpretation ‘A’ > ‘C’ 0 False ‘D’ <= ’Z’ 1 True ‘E’ == ’F’ 0 False ‘G’ >= ‘M’ 0 False ‘B’ != ‘C’ 1 True
13
A First Book of ANSI C, Fourth Edition13 Comparing letters is essential in alphabetizing names or using characters to select a particular choice in decision-making situations.
14
A First Book of ANSI C, Fourth Edition14 Relational Expressions (continued)
15
A First Book of ANSI C, Fourth Edition15 Logical Operators In addition to using simple relational expressions as conditions, more complex conditions can be created using the logical operations AND,OR, and NOT. These operations are represented by the symbols &&, ︱ ︱, and !, respectively. When the AND operator, &&, is used with two simple expressions, the condition is true only if both expressions are true by themselves.
16
A First Book of ANSI C, Fourth Edition16 AND Operator Thus, the compound condition (age > 40) && (term < 10) is true (has a value of 1) only if age is greater than 40 and term is less than 10. Because relational operations have a higher precedence than logical operators, the parentheses in this logical expression could have been omitted.
17
A First Book of ANSI C, Fourth Edition17 OR Operator The logical OR operator, ︱︱, is also applied between two expressions. When using the OR operator, the condition is satisfied if either one or both of the two expressions are true. Thus, the compound condition (age > 40) ︱︱ (term < 10) is true if either age is greater than 40, term is less than 10, or both conditions are true.
18
A First Book of ANSI C, Fourth Edition18 For the declarations int i, j; float a, b, complete; the following represent valid conditions; a > b i ==j ︱︱ a < b ︱︱ complete a/b > 5 && i<=20 Before these conditions can be evaluated, the values of a,b,i,j, and complete must be known.
19
A First Book of ANSI C, Fourth Edition19 Assuming a = 12.0, b=2.0,i=15 , j=30, and complete = 0.0 the expressions yield the folowing results: a > b i==j ︱︱ a < b ︱︱ complete a/b > 5 && i<=20
20
A First Book of ANSI C, Fourth Edition20 Expression Value Interpretation a > b 1 True i==j ︱︱ a < b ︱︱ complete 0 False a/b > 5 && i<=20 1 True
21
A First Book of ANSI C, Fourth Edition21 NOT Operator The NOT operator is used to change an expression to its opposite state; that is, if the expression has any nonzero value (true), !expression produces a zero value (false). For example, assuming the number 26 is stored in the variable age, the expression age> 40 has a value of zero (it is false), while the expression !(age>40) has a value of 1. Since the NOT operator is used with only one expression, it is a unary operator.
22
A First Book of ANSI C, Fourth Edition22 The relational and logical operators have a hierarchy of execution similar to that of the arithmetic operators. Table 4.6 lists the precedence of these operators in relation to the other operators we have used.
23
A First Book of ANSI C, Fourth Edition23 Table 4.6 Precedence of operators in C
24
A First Book of ANSI C, Fourth Edition24 As with all expressions, parentheses can be used to alter the assigned operator priority and improve the readability of relational expressions. By evaluating the expressions within parentheses first, the following compound condition is evalusted as:
25
A First Book of ANSI C, Fourth Edition25 (6 * 3 == 36 / 2) ︱︱ (13 < 3* 3 + 4) && ! (6-2<5) (18 == 18) ︱︱ (13 <9 + 4) && !(4 < 5) 1 ︱︱ (13 < 13) && !1 1 ︱︱ 0 && 0 1 ︱︱ 0 1
26
4.2 The if and if-else Statements if (expression) statement1; A First Book of ANSI C, Fourth Edition26
27
A First Book of ANSI C, Fourth Edition27 4.2 The if and if-else Statements No semicolon here One-way if statement
28
A First Book of ANSI C, Fourth Edition28 Program 4.1 #define LIMIT 3000.0 #include int main() { int idNum; float miles; printf(“Please type in car number and mileage:”); scanf(“%d %f”, &idNum, &miles); if(miles > LIMIT) printf(“ Car %d is over the limit.\n”,idNum); printf(“End of program output.\n”); return 0; }
29
A First Book of ANSI C, Fourth Edition29 Compound Statements Although only a single statement is permitted in an if statement, this statement can be a single compound statement
30
A First Book of ANSI C, Fourth Edition30 Compound Statements (continued)
31
A First Book of ANSI C, Fourth Edition31 Compound Statements (continued) For example, if (expression) { statement1; /*as many statements as necessary*/ statement2; /*can be placed within the braces*/ /*each statement must end with ; */ statementn; } For very short statements, you can code a complete if statement placed on a single line –if (grade > 69) ++passTotal;
32
A First Book of ANSI C, Fourth Edition32 The if-else Statement The most commonly used if-else statement is if (expression) statement1; else statement2; –If the value of expression is 0 statement2, the statement after the reserved word else, is executed
33
A First Book of ANSI C, Fourth Edition33 The if-else Statement (continued)
34
A First Book of ANSI C, Fourth Edition34 4.2 The if-else Statement The if-else statement directs the computer to select a sequence of one or more instructions based on the result of a comparison.
35
A First Book of ANSI C, Fourth Edition35 The general form of the if-else statement is if (expression) statement1; else statement2;
36
A First Book of ANSI C, Fourth Edition36 The expression is evaluated first. If the value of the expression is nonzero, statement1 is executed. If the value is zero, statement2, the statement after the reserved word else, is executed.
37
A First Book of ANSI C, Fourth Edition37 Thus, one of the two statements (either statement1 or statement2) is always executed depending on the value of the expression. Notice that the tested expression must be put in parentheses and a semicolon is placed after each statement.
38
A First Book of ANSI C, Fourth Edition38 For clarity, the if-else statement may also be written on four lines using the form if (expression) ← no semicolon here statement1; else ← no semicolon here statement2;
39
A First Book of ANSI C, Fourth Edition39 The form of the if-else statement that is selected generally depends on the length of statements 1 and 2. However, when using the second form, do not put a semicolon after the parentheses or the reserved word else. The semicolons go only after the ends of the statements.
40
A First Book of ANSI C, Fourth Edition40 As an example, let us write an income tax computation program containing an if-else statement. As preciously described, New Jersey state income tax is assessed at 2 percent of taxable income for incomes less than or equal to $20,000. For taxable income greater than $20,000, state taxes are 2.5 percent of the income that exceeds $20,000 plus a fixed amount of $400(which is 2 percent of $20,000).
41
A First Book of ANSI C, Fourth Edition41 The expression to be tested is whether taxable income is less than or equal to $20,000. if (taxable <= 20000.0) taxes = 0.02 * taxable; else taxes = 0.025 * (taxable -2000.0) +400.0; Program 4.2 illustrates the use of this statement in a complete program using named constants for the actual numerical values.
42
A First Book of ANSI C, Fourth Edition42 Program 4.2 #include #define LOWRATE 0.02 /*lower tax rate */ #define HIGHRATE 0.025 /*higher tax rate */ #define CUTOFF 20000.0 /*cut off for low rate*/ #define FIXEDAMT 400 /*fixed dollar amount for higher rate amounts*/
43
A First Book of ANSI C, Fourth Edition43 int main () { float taxable, taxes; printf (“Please type in the taxable income: ”); scanf (“%f ”, &taxable); if (taxable <= CUTOFF) taxes = LOWRATE * taxable; else taxes = HIGHRATE * (taxable -CUTOFF) + FIXEDAMT; printf (“Taxes are $%7.2f”, taxes); return 0; }
44
A First Book of ANSI C, Fourth Edition44 A blank line was inserted before and after the if- else statement to highlight it in the complete program. We will continue to do this throughout the text to emphasize the statement being presented. To illustrate this selection in action, Program 4.2 was run twice with different input data.
45
A First Book of ANSI C, Fourth Edition45 The results are Please type in the taxable income: 10000. Taxes are $ 200.00 and Please type in the taxable income: 30000. Taxes are $ 650.00
46
A First Book of ANSI C, Fourth Edition46 The if-else Statement (continued)
47
A First Book of ANSI C, Fourth Edition47 Compound Statements Although only a single statement is permitted in both the if and else parts of the if-else statement, this statement can be a single compound statement.
48
A First Book of ANSI C, Fourth Edition48 The use of braces to enclose a set of individual statements creates a single block of statements, which may be used anywhere in a C program in place of a single statement. The next example illustrates the use of a compound statement within the general form of an if-else statement.
49
A First Book of ANSI C, Fourth Edition49 Program 4.3 #include int main() { char tempType; float temp, fahren, Celsius; printf(“Enter the temperature to be converted:”); scanf(“%f”,&temp); printf(“Enter an f if the temperature is in Fahrenheit”); printf(“\n or a c if the temperature is in Celsius:”); scanf(“\n%c”,&tempType);
50
A First Book of ANSI C, Fourth Edition50 if (tempType == ‘f’) { Celsius = (5.0/9.0) * (temp – 32.0); printf(“\nThe equivalent Celsius temperature is %6.2f”, celsiur); } else { fahren = (9.0 / 5.0) * temp + 32.0; printf(“\nThe equivalent Fahrenheit temperature is %6.2F”, fahren); } return 0; }
51
A First Book of ANSI C, Fourth Edition51 Program 4.3 checks whether the value in tempType is f. If the value is f, the compound statement corresponding to the if part of the if-else statement is executed. Any other letter results in execution of the compound statement corresponding to the else part.
52
A First Book of ANSI C, Fourth Edition52 Following is a sample run of Program 4.2. Enter the temperature to be converted: 212 Enter an f if the temperature is in Fahrenheit or a c if the temperature is in Celsius: f The equivalent Celsius temperature is 100.00
53
A First Book of ANSI C, Fourth Edition53 The if-else Statement (continued)
54
A First Book of ANSI C, Fourth Edition54 The if-else Chain Nested if statement: if (expression1) statement1; else if (expression2) statement2; else statement3; Whether the indentation exists or not, the compiler will, by default, associate an else with the closest previous unpaired if, unless braces are used to alter this default pairing
55
A First Book of ANSI C, Fourth Edition55 Nested if Statements An if-else statement can contain simple or compound statements. Any valid C statement can be used, including another if-else statement. Thus, one or more if-else statements can be included within either part of an if-else statement. This construction is called an if-else chain.
56
A First Book of ANSI C, Fourth Edition56 It is used extensively in applications programs. Each condition is evaluated in order, and if any condition is true the corresponding statement is executed and the remainder of the chain is terminated. The final else statement is only executed if none of the previous conditions are satisfied. This serves as a default or catchall case that is useful for detecting an impossible or error condition
57
A First Book of ANSI C, Fourth Edition57 The if-else Chain (continued)
58
A First Book of ANSI C, Fourth Edition58 The if-else Chain (continued) if-else chain: if (expression1) statement1; else if (expression2) statement2; else statement3;
59
A First Book of ANSI C, Fourth Edition59 As with all C statements, each individual statement can be a compound statement bounded by the braces { and }. To illustrate an if-else chain, Program 4.4 displays a person’s marital status corresponding to a letter input. The following letter codes are used :
60
A First Book of ANSI C, Fourth Edition60 Marital StatusInput Code MarriedM SingleS DivorcedD WidowedW
61
A First Book of ANSI C, Fourth Edition61 Program 4.4 #include int main ( ) { char marcode ; printf (“Enter a marital code : ”) ; scanf (“%c”, &marcode ) ; if (marcode == ‘M’) printf (“\nIndividual is married.”) ; else if (marcode == ‘S’) printf (“\nIndividual is single.”);
62
A First Book of ANSI C, Fourth Edition62 else if (marcode == ‘D’) printf (“\nIndividual is divorced.\ ); else if (marcode == ‘W’) printf (“\nIndividual is widowed.”); else printf (“\nAn invalid code was entered.”); return 0 ; }
63
A First Book of ANSI C, Fourth Edition63 The if-else Chain (continued)
64
A First Book of ANSI C, Fourth Edition64 Monthly SalesIncome greater than or equal to $50,000$375 plus 16% of sales less than $50,000 but greater than or equal to $40,000 $350 plus 14% of sales less than $40,000 but greater than or equal to $30,000 $325 plus 12% of sales less than $30,000 but greater than or equal to $20,000 $300 plus 9% of sales less than $20,000 but greater than or equal to $10,000 $250 plus 5% of sales less than $10,000$200 plus 3% of sales The if-else Chain (continued)
65
A First Book of ANSI C, Fourth Edition65 Program 4.5 #include int main ( ) { float monthlySales,income ; printf (“Enter the value of monthly sales :”); scanf (“%f”, &monthlySales ); if (monthlySales >= 50000.00) income = 375.00 +.16 * monthlySales ; else if (monthlySales >= 40000.00) income = 350.00 +.14 * monthlySales ;
66
A First Book of ANSI C, Fourth Edition66 else if (monthlySales >= 30000.00) income = 325.00 +.12 * monthlySales ; else if (monthlySales >= 20000.00) income = 300.00 +.09 * monthlySales ; else if (monthlySales >= 10000.00) income = 250.00 +.05 * monthlySales ; else income = 200.00 +.03 * monthlySales ; printf (“The income is $%7.2f”, income ); return 0; } A sample run using Program 4.5 is illustrated below. Enter the value of monthly sales : 36243.89 The income is $4674.27
67
A First Book of ANSI C, Fourth Edition67 The if-else Chain (continued)
68
A First Book of ANSI C, Fourth Edition68 4.4 The switch Statement The if-else chain is used in programming applications where one set of instructions must be selected from many possible alternatives. The switch statement provides an alternative to the if-else chain for cases that compare the value of an integer expression to a specific value.
69
A First Book of ANSI C, Fourth Edition69 The switch Statement Terminated with a colon default is optional If the break statement was omitted, the following case would be executed
70
A First Book of ANSI C, Fourth Edition70 The switch Statement (continued)
71
A First Book of ANSI C, Fourth Edition71 The switch statement uses four new keywords : switch, case, default, and break. Let’s see what each of these words does. The keyword switch identifies the start of the switch statement.
72
A First Book of ANSI C, Fourth Edition72 The expression in parentheses following this word is evaluated, and the result of the expression is compared to various alternative values contained within the compound statement. The expression in the switch statement must evaluate to an integer result or a compilation error occurs.
73
A First Book of ANSI C, Fourth Edition73 Internal to the switch statement, the keyword case is used to identify or label individual values that are compared to the value of the switch expression. The switch expression’s value is compared to each of these case values in the order that these values are listed until a match is found. When a match occurs, execution begins with the statement immediately following the match.
74
A First Book of ANSI C, Fourth Edition74 Any number of case labels may be contained within a switch statement, in any order. If the value of the expression does not match any of the case values, however, no statement is executed unless the keyword default is encountered.
75
A First Book of ANSI C, Fourth Edition75 The word default is optional and operates the same as the last else in an if-else chain. If the value of the expression does not match any of the case values, program execution begins with the statement following the word default.
76
A First Book of ANSI C, Fourth Edition76 Once an entry point has been located by the switch statement, no further case evaluations are done ; all statements that follow within the braces are executed unless a break statement is encountered. This is the reason for the break statement, which identifies the end of a particular case and causes an immediate exit from the switch statement.
77
A First Book of ANSI C, Fourth Edition77 Thus, just as the word case identifies possible starting points in the compound statement, the break statement determines terminating points. If the break statements are omitted, all cases following the matching case value, including the default case, are executed.
78
A First Book of ANSI C, Fourth Edition78 switch(score) { case 5: printf(“Very good!”); case 4: printf(“Good!”); case 3: printf(“Pass!”); case 2: printf(“Fail!”); default : printf(“data error!”); }
79
A First Book of ANSI C, Fourth Edition79 void main() { int x=1,y=0,a=0,b=0; switch(x) { case 1: switch(y) { case 0: a++; break; case 1: b++; break; } case 2: a++;b++; break; case 3: a++;b++; } printf(“\na=%d,b=%d”,a,b); }
80
A First Book of ANSI C, Fourth Edition80 When you write a switch statement, you can use multiple case values to refer to the same set of statements ; the default label is optional. For example, consider the following :
81
A First Book of ANSI C, Fourth Edition81 switch (number) { case 1 : printf (“Have a Good Morning\n”) ; break ; case 2 : printf (“Have a Happy Day\n”) ; break : case 3 : case 4 :case 5 : printf (“Have a Nice Evening\n”) ; }
82
A First Book of ANSI C, Fourth Edition82 If the value stored in the variable number is 1, the message Have a Good Morning is displayed. Finally, if the value of number is 3 or 4 or 5, the last message is displayed. Since the statement to be executed for these last three cases is the same, the cases for these values can be “stacked together ” as is done in the example.
83
A First Book of ANSI C, Fourth Edition83 Also, since there is no default, no message is printed if the value of number is not one of the listed case values. Although it is good programming practice to list case values in increasing order, this is not required by the switch statement. A switch statement can have any number of case values, in any order ; only the values being tested for need be listed.
84
A First Book of ANSI C, Fourth Edition84 Program 4.6 uses a switch statement to select the arithmetic operation to be performed on two numbers depending on the value of the variable opselect.
85
A First Book of ANSI C, Fourth Edition85 Program 4.6 #include int main( ) { int opselect ; double fnum, snum ; printf (“Please type in two numbers :”); scanf (“%lf %lf”, &fnum, &snum ) ; printf (“Enter a select code :”) ; printf (“\n 1 for addition ”) ; printf (“\n 2 for multiplication ”) ; printf (“\n 3 for division : ”); scanf (“%d”, &opselect );
86
A First Book of ANSI C, Fourth Edition86 switch (opselect) { case 1 ; printf (“The sum of the numbers entered is %6.31f ”, fnum + snum ) ; break ; case 2 ; printf (“The product of the numbers entered is %6.31f ”, fnum * snum ) ; break ; case 3 ; printf (“The first number divided by the second is %6.31f ”, fnum / snum ) ; break ; /* this break is optional */ } /* end of switch statement */ return 0 ; } /* end of main */
87
A First Book of ANSI C, Fourth Edition87 Program 4.6 was run twice. The resulting displays clearly identify the case selected. The results are Please type in two numbers : 12 3 Enter a select code : 1 for addition 2 for multiplication 3 for division : 2
88
A First Book of ANSI C, Fourth Edition88 The product of the numbers entered is 36.000 and Please type in two numbers : 12 3 Enter a select code : 1 for addition 2 for multiplication 3 for division : 3 The first number divided by the second is 4.000
89
A First Book of ANSI C, Fourth Edition89 In reviewing Program 4.6, notice the break statement in the last case. Although this break is not necessary, it is a good practice to terminate the last case in a switch statement with a break. This prevents a possible program error later, if an additional case is subsequently added to the switch statement.
90
A First Book of ANSI C, Fourth Edition90 With the addition of a new case, the break between cases becomes necessary ; having the break in place ensures you will not forget to include it at the time of the modification.
91
A First Book of ANSI C, Fourth Edition91 Since character data are always converted to their integer values in an expression, a switch statement can also be used to “switch” based on the value of a character expression. For example, assuming that choice is a character variable, the following switch statement is valid :
92
A First Book of ANSI C, Fourth Edition92 switch (choice) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: printf (“\nThe character in choice is a vowel”) ; break ; default : printf (“\nThe character in choice is not a vowel”); } /* end of switch statement */
93
A First Book of ANSI C, Fourth Edition93 The switch Statement (continued)
94
A First Book of ANSI C, Fourth Edition94 Case Study: Data Validation Defensive programming is a technique where the program includes code to check for improper data before an attempt is made to process it further –Checking user input data for erroneous or unreasonable data is called input data validation Requirements: –Write a program to calculate the square root and the reciprocal of a user-entered number. Validate that the number is not negative before attempting to take its square root, and that the number is not 0 before calculating the number’s reciprocal value.
95
A First Book of ANSI C, Fourth Edition95 Case Study: Data Validation (continued)
96
A First Book of ANSI C, Fourth Edition96 Common Programming Errors Using the assignment operator, =, in place of the relational operator, == Letting the if-else statement appear to select an incorrect choice Nesting if statements without including braces to clearly indicate the desired structure Using a single & or | in place of the logical && and logical || operators, respectively
97
A First Book of ANSI C, Fourth Edition97 Common Compiler Errors
98
A First Book of ANSI C, Fourth Edition98 Summary Relational expressions, which are also called simple conditions, are used to compare operands Conditions can be constructed from relational expressions using C’s logical operators, &&, ||, and ! A one-way if statement has the general form if (expression) statement; A compound statement consists of any number of individual statements enclosed within braces An if-else selects between two alternative statements based on the value of an expression
99
A First Book of ANSI C, Fourth Edition99 Summary (continued) An if-else statement can contain other if-else statements The if-else chain is a multiway selection statement The switch statement is a multiway selection statement; program execution is transferred to the first matching case and continues through the end of the switch statement unless an optional break statement is encountered
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.