C Programming -Topic 4 Revision 2 – Sep 2000 C Programming - Topic 4 Selection Structure 1.0 Conditions 1.1 A condition in C typically consists of one or more comparisons that compare one value to another. A comparison has the form expression comparison-operator expression For example: x+4>9 Where we compare the value of the expression x + 4 with the value 9. An expression is anything that reduces to a single value; and always compares two values. 2.0 Relational and Equality Operators 2.1 The comparison-operator comes from one of two categories: relational operators and equality operators. The operators differ in function, but the categories also differ in precedence with the relational operators being higher than the equality operators. 2.2 Equal operator (==) is not the same as the assignment operator (=). 2.3 Operators of both categories have left-to-right associativity. In precedence, all the arithmetic operators are first, followed by the relational operators, followed by the equality operators, and ending with the assignment operators. 4 + 8 != 36 / 3 \ / \ / 12 12 \ / \ / \ / False 16 % 3 < 22 == 6 / 3 >= 2 \/ / \ / 1 / 2 / \ / \ / True True \ / \ / True / 2.4 Relational, Equality, logical, and Conditional Operators table. Operator Explanation Symbol Example ArithmeticRelational - Left-to-right associativity Greater First greater than second? > Less First less than second? Greater or equal First greater than or equal to second? >= Less or equal First less than or equal to second? <= X+Y > Z-19 < cost < maximum-100 load >= limit TestValue <= Norm Equality - Left-to-right associativity Equal First equals second? == Not equal First not equal to second? Logical AND - Left-to-right associativity First and second true? Logical OR - Left-to-right associativity != Count+1 == EndCount CheckSum != NewSum && day > 28 && month != 2 1 C Programming -Topic 4 Revision 2 – Sep 2000 First or second or both true? Conditional - Right-to-left associativity If test true, perform first expression, otherwise perform second. || ?: Score > 90 || Grade == 'A' x > 4 ? p + 9 : p - 14 Assignment - 3.0 Logical Operators 3.1 Conditions can consist of more than one comparison. We can tie multiple comparisons together with logical operators, of which we have two - AND (&&) and OR (||). 3.2 Using the AND operator, if the comparisons on both sides are true, then the whole condition is true. If even one comparison is false, then the whole condition is false 9 >= 7 + 3 && 7 % 3 == 1 \ \ / \ / \ 10 1 \ / \ False True \ / False / / / 3.3 Using the OR operator, if either or both of the comparisons are true, then the whole condition is true. Both comparisons would have to be false for the whole condition to be false. 6 > 2 || 25 / 5 == 4 \ / \ / / True 5 / \ \ / \ False \ / True 3.5 The AND operator is higher in precedence than OR. Both of them are lower than the comparison operators, but higher than assignment. 3.6 In C anything that evaluates to true is assigned the value one; false is assigned zero. 7 <= 9 || 6 > 5 && 7 == 2 \ / \ / \ / True True False \ \ / \ False \ / True (7 <= 9 || 6 > 5) && 7 == 2 \ / \ / True True False \ / True / \ / False \ / / 3.7 The NOT operator (!) is a logical operator, but it is also unary, acting on only one expression. In precedence and associativity, it falls with the other unary operators. The logical NOT operator makes what was true false, and what was false true, 25 > 3 && !(6 == 4) \ / \\ / \/ \False True \/ \ True \ / True 2 C Programming -Topic 4 Revision 2 – Sep 2000 4.0 The if statement: 4.1 General form: if (condition) statement; 4.2 We can substitute a block of statements for the single statement in the general form, giving us the more common form if (condition) { statement; statement; ... } 4.3 Please note that the condition is enclosed in parentheses, and there is no semicolon after the condition. Sample Program : #include <stdio.h> void main(void) { float weight, price = 0.2; printf("Enter weight of apple:”); scanf("%f”, &weight); printf('Royal '); if (weight > 10) { printf('Premium “); price += 0.1; } printf('Apple. $%4.2f.\n', price); } Execution Enter weight of apple: 11.3 Royal Premium Apple. $0.30. Execution Enter weight of apple: 7.8 Royal Apple. $0.20. 5.0 The else Clause 5.1 General format: if (condition) statement; else statement; or if (condition) { statement; statement: ... } else { statement; statement; ... } 5.2 Sample Program 3 C Programming -Topic 4 Revision 2 – Sep 2000 #include <stdio.h> void main(void) { float weight, price = .2; printf("Enter weight of apple: scanf("%f”, &weight); printf("Royal” ); if (weight > 10) { printf("Premium”); price += .1: } else { printf("Juicy" ); } printf(“Apple. $%4.2f.\n", price); } Execution Enter weight of apple: 9.2 Royal Juicy Apple. $0.20. Execution Enter weight of apple: 10.1 Royal Premium Apple. $0.30. 5.3 Sample Program #include <stdio.h> void main(void) { float weight, price = .2; printf("Enter weight of apple:"); scanf("%f", &weight); printf("Royal"); if (weight > 10) { printf("Premium"); price += .1; } else {if (weight > 8) /* Brace necessary/ { printf("Juicy"); } else { if (weight > 6) /* Brace necessary/ { printf("Snack”); price -= .05; } else { printf("Cooking"); price -= .1; } /* Brace necessary? } /* Brace necessary/ } printf('Apple. $%4.2f.\n", price); } Executions Executions 4 C Programming -Topic 4 Revision 2 – Sep 2000 Enter weight of apple: 12 Royal Premium Apple. $0.30. Enter weight of apple: 7.5 Royal Snack Apple. $0.15. Enter weight of apple: 9.2 Royal Juicy Apple. $0.20. Enter weight of apple: 5.9 Royal Cooking Apple. $0.10. 6.0 The else if Construct 6.1 Sample Program if (weight > 10) { printf("Premium”); price +=0.1; } else if (weight > 8) { printf("Juicy”); } else if (weight > 6) {printf("Snack”); price -= .05; } else { printf("Cooking”); price -= .1; } 7.0 The switch statement 7.1 The C language includes a multibranch alternative to the if statement called the switch statement. It has some limitations, but within these limitations, it can be very handy. 7.2 The format is: switch (integral_expression) {statement block} 7.3 The statement block is a number of statements within the various branches. The beginnings of the branches are distinguished by case identifiers, all beginning with the key word case. 7.4 Example: switch (integral_expression) { case integral_value: statement; statement; case integral_value: statement; statement; case as many as are necessary: ... default: statement; statement; } 7.5 The integral_expression following the switch key word must evaluate to some integral data type, char or int; floating point results are not allowed. The value of the expression becomes a case value to be matched to the possible case identifiers within the statement block following the switch. 7.6 For example, if the integral_expression evaluated to 6,the switch would look for case 6: Each of the case within the block following switch has an integral_value, which, along with case and a following colon, becomes the identifier. For example, two of the cases might be case 9: and case 6:.The switch 5 C Programming -Topic 4 Revision 2 – Sep 2000 causes the program to jump directly to the matching identifier; in other words, the next code to be executed will be that immediately following the identifier. 7.7 In the example, that would be the code following case 6:. 7.8 If there is no matching label, the jump is to the default label. The default label is not absolutely necessary and, if it appears, may be in any position within the block, but it may appear only once. In practice, there is usually a default label, and it is typically the last one. 7.9 Sample program #include <stdio.h> void main(void) { float price = 0: char grade; printf("Enter grade of apple: “); scanf(" %c', &grade); printf("Royal '); switch (grade) { case 'P': case 'p': price += .1; printf("Super"); case 'J': case 'j': price += .05; printf("Excellent"); case 'S': case 's': price += .05; printf("Delicious"); default: price += .1; } printf("Apple. $%4.2f.\n", price); } Executions Enter grade of apple: p Royal Super Excellent Delicious Apple. $0.30. Enter grade of apple: J Royal Excellent Delicious Apple. $0.20. Executions Enter grade of apple: s Royal Delicious Apple. $0.15. Enter grade of apple: q Royal Apple. $0.10. 7.10 As we stated in earlier topics, character values such as 'P' are integral numeric values-the ASCII codes for those characters. The program would have run the same had we substituted case 80:, using the ASCII value for P, for case 'P':. 7.11 Observe the punctuation here. Notice that the integral_expression following switch is enclosed in parentheses and that there is no semicolon after the statement. All the statements within the following structure are contained within one set of braces. There need not be separate sets of braces in each branch, although there certainly could be if the structure warranted it. Each case identifier is followed by a colon, which tells C that it is a case identifier. 8.0 The break Statement 8.1 The switch statement as demonstrated above is not a very effective multibranch structure because the branches are not separated. One branch flows through all the subsequent branches including default:. The break statement can solve that problem. The break statement causes an immediate jump to the statement following a switch structure. If we put break statements at the end of each of the 6 C Programming -Topic 4 Revision 2 – Sep 2000 branches, C will execute the statements after the case, but jump to the statement after the closing brace when it encounters the break. 8.2 Sample program: #include <stdio.h> void main(void) { float price; char grade; printf('Enter grade of apple:"); scanf(" %c", &grade); printf("Royal "); switch (grade) { case 'p': case 'P': price = .3; printf("Super"); break; case 'J'; case 'j'; price = .2; printf("Excellent"); break; case 'S' case 's' price = .15; printf("Delicious"); break; default: price = .1; } printf("Apple. $%4.2f.\n", price); } Executions Enter grade of apple: p Royal Super Apple. $0.30. Enter grade of apple: J Royal Excellent Apple. $0.20. Executions Enter grade of apple: S Royal Delicious Apple. $0.15. Enter grade of apple: e Royal Apple. $0.10. The vast majority of switch structures use breaks at the end of each branch. 9.0 The conditional expression 9.1 C also gives us the conditional expression, using the operators ? and :, which allows us to set up a two-branch situation within an expression. 9.2 The general form of a conditional expression is condition ? true_expression : false_expression 9.2.1 C first evaluates the condition to true or false. If the condition is true then C will evaluate the true expression, which becomes the value of the entire conditional expression. Otherwise C will evaluate the false_expression. 9.2.2 For example, if the value of x is 150 then the value of this expression, X > 100 ? X * 1.1 : X * .9 is 165, the value of the true-expression. 7 C Programming -Topic 4 Revision 2 – Sep 2000 9.3 As an example, let us say that salespeople are paid their salary plus a commission of 10% on all sales if they sell up to and including $1000, but 12% on all sales plus a bonus of $100 if they sell over $1000. pay = salary + (sales > 1000 ? sales *.12 + 100 : sales * .1); If sales was $2000 then the value of the entire conditional expression, everything within the parentheses, would be $340 - sales x.12 + 100.-which would be added to salary and the result stored in pay. 9.4 The parentheses are important in the example above because the precedence of the conditional operators is very low, just above the assignment operators. Its associativity is right to left. 10.0 Summary 10.1 The selection structure contains two branches. Which branch the execution will take depends on a condition consisting of one or more comparisons. Comparisons are connected to relational operators or equality operators. Comparisons can be tied together with the logical operators and and or. The not operator is a unary operator that makes what was true false, and vice versa. 10.2 The if statement implements the selection structure. It may contain only one true branch, in which case the false branch is to do nothing; or it may have an else clause where the false branch is stated. To form a multibranch structure, one branch of an if else statement may contain another complete if else statement. It is so common to branch the eIse branch of the selection structure that most programmers treat that construct as a single multibranch structure. 10.3 The switch statement sets up a more limited multibranch structure by allowing the program to jump to any of a number of case identifiers. The integral expression following switch is evaluated and C searches for a corresponding value following any number of case statements. If it finds no match, it looks for a default label. Execution resumes at the appropriate label. A break statement causes the execution to transfer to the statement following the end of the switch structure. These breaks are often used to separate the switch structure into individual branches. 10.4 A conditional expression allows us to put a limited kind of selection within an expression. C evaluates the condition before the question mark and if it is true will evaluate the expression before the colon; otherwise, it will evaluate the one after. _______________ 8