1 / 99

A First Book of ANSI C Fourth Edition

A First Book of ANSI C Fourth Edition. Chapter 4 Selection. 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. Introduction.

adina
Download Presentation

A First Book of ANSI C Fourth Edition

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. A First Book of ANSI CFourth Edition Chapter 4 Selection

  2. 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 A First Book of ANSI C, Fourth Edition

  3. Introduction • Flow of controlrefers 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 • Selectionisused 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 A First Book of ANSI C, Fourth Edition

  4. 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) A First Book of ANSI C, Fourth Edition

  5. Relational Expressions (continued) A First Book of ANSI C, Fourth Edition

  6. Relational Expressions (continued) A First Book of ANSI C, Fourth Edition

  7. 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 A First Book of ANSI C, Fourth Edition

  8. 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. A First Book of ANSI C, Fourth Edition

  9. For example, because the relationship 3<4 in always true, the expression has a value of 1, and because the relationship 2.0>3.3 is always false, the expression has a value of 0. A First Book of ANSI C, Fourth Edition

  10. 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 A First Book of ANSI C, Fourth Edition

  11. 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. • . A First Book of ANSI C, Fourth Edition

  12. 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 A First Book of ANSI C, Fourth Edition

  13. Comparing letters is essential in alphabetizing names or using characters to select a particular choice in decision-making situations. A First Book of ANSI C, Fourth Edition

  14. Relational Expressions (continued) A First Book of ANSI C, Fourth Edition

  15. 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. A First Book of ANSI C, Fourth Edition

  16. 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. A First Book of ANSI C, Fourth Edition

  17. 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. A First Book of ANSI C, Fourth Edition

  18. 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. A First Book of ANSI C, Fourth Edition

  19. 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 A First Book of ANSI C, Fourth Edition

  20. Expression Value Interpretation • a > b 1 True • i==j︱︱a < b︱︱complete 0 False • a/b > 5 && i<=20 1 True A First Book of ANSI C, Fourth Edition

  21. 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. A First Book of ANSI C, Fourth Edition

  22. 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. A First Book of ANSI C, Fourth Edition

  23. Table 4.6 Precedence of operators in C A First Book of ANSI C, Fourth Edition

  24. 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: A First Book of ANSI C, Fourth Edition

  25. (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 A First Book of ANSI C, Fourth Edition

  26. 4.2 The if and if-else Statements if (expression) statement1; A First Book of ANSI C, Fourth Edition

  27. 4.2 The if and if-else Statements No semicolon here One-way if statement A First Book of ANSI C, Fourth Edition

  28. Program 4.1 • #define LIMIT 3000.0 • #include <stdio.h> • 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; • } A First Book of ANSI C, Fourth Edition

  29. Compound Statements • Although only a single statement is permitted in an if statement, this statement can be a single compound statement A First Book of ANSI C, Fourth Edition

  30. Compound Statements (continued) A First Book of ANSI C, Fourth Edition

  31. 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; A First Book of ANSI C, Fourth Edition

  32. 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 A First Book of ANSI C, Fourth Edition

  33. The if-else Statement (continued) A First Book of ANSI C, Fourth Edition

  34. 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. A First Book of ANSI C, Fourth Edition

  35. The general form of the if-else statement is • if (expression)statement1; • else statement2; A First Book of ANSI C, Fourth Edition

  36. 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. A First Book of ANSI C, Fourth Edition

  37. 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. A First Book of ANSI C, Fourth Edition

  38. 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; A First Book of ANSI C, Fourth Edition

  39. 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. A First Book of ANSI C, Fourth Edition

  40. 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). A First Book of ANSI C, Fourth Edition

  41. 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. A First Book of ANSI C, Fourth Edition

  42. Program 4.2 • #include <stdio.h> • #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*/ A First Book of ANSI C, Fourth Edition

  43. 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; • } A First Book of ANSI C, Fourth Edition

  44. 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. A First Book of ANSI C, Fourth Edition

  45. 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 A First Book of ANSI C, Fourth Edition

  46. The if-else Statement (continued) A First Book of ANSI C, Fourth Edition

  47. 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. A First Book of ANSI C, Fourth Edition

  48. 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. A First Book of ANSI C, Fourth Edition

  49. Program 4.3 • #include <stdio.h> • 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); A First Book of ANSI C, Fourth Edition

  50. 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; • } A First Book of ANSI C, Fourth Edition

More Related