a first book of ansi c fourth edition chapter 4 selection

99
A First Book of ANSI C Fourth Edition Chapter 4 Selection

Upload: tamsin-hubbard

Post on 26-Dec-2015

254 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI CFourth Edition

Chapter 4

Selection

Page 2: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 3: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 3

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

Page 4: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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)

Page 5: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 5

Relational Expressions (continued)

Page 6: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 6

Relational Expressions (continued)

Page 7: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 8: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 9: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 10: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 11: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

• .

Page 12: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 13: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 14: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 14

Relational Expressions (continued)

Page 15: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 16: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 17: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 18: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 19: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 20: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 21: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 22: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 23: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 23

Table 4.6 Precedence of operators in C

Page 24: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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:

Page 25: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 26: A First Book of ANSI C Fourth Edition Chapter 4 Selection

4.2 The if and if-else Statements

if (expression)

statement1;

A First Book of ANSI C, Fourth Edition 26

Page 27: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 27

4.2 The if and if-else Statements

No semicolon here One-way if statement

Page 28: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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;• }

Page 29: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 30: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 30

Compound Statements (continued)

Page 31: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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;

Page 32: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 32

The if-else Statement

• The most commonly used if-else statement isif (expression)

statement1;

else

statement2;

– If the value of expression is 0 statement2, the statement after the reserved word else, is executed

Page 33: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 33

The if-else Statement (continued)

Page 34: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 35: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 35

• The general form of the if-else statement is

• if (expression) statement1;

• else statement2;

Page 36: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 37: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 38: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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;

Page 39: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 40: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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).

Page 41: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 42: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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*/

Page 43: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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;• }

Page 44: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 45: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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

Page 46: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 46

The if-else Statement (continued)

Page 47: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 48: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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.

Page 49: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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);

Page 50: A First Book of ANSI C Fourth Edition Chapter 4 Selection

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;• }

Page 51: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 51

• 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.

Page 52: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 52

• 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

Page 53: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 53

The if-else Statement (continued)

Page 54: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 54

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

Page 55: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 55

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 .

Page 56: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 56

• 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

Page 57: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 57

The if-else Chain (continued)

Page 58: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 58

The if-else Chain (continued)

• if-else chain:

if (expression1) statement1;else if (expression2) statement2;else statement3;

Page 59: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 59

• 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 :

Page 60: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 60

Marital Status Input Code

Married M

Single S

Divorced D

Widowed W

Page 61: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 61

Program 4.4• #include <stdio.h>• 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 .”);

Page 62: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 62

• 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 ;

• }

Page 63: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 63

The if-else Chain (continued)

Page 64: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 64

Monthly Sales Income

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)

Page 65: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 65

Program 4.5

• #include <stdio.h>

• 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 ;

Page 66: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 66

• 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

Page 67: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 67

The if-else Chain (continued)

Page 68: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 68

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 .

Page 69: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 69

The switch Statement

Terminated with a colon

default is optional

If the break statement was omitted, the following case would be executed

Page 70: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 70

The switch Statement (continued)

Page 71: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 71

• 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 .

Page 72: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 72

• 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 .

Page 73: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 73

• 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 .

Page 74: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 74

• 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 .

Page 75: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 75

• 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 .

Page 76: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 76

• 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 .

Page 77: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 77

• 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 .

Page 78: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 78

• switch(score)

• { case 5: printf(“Very good!”);

• case 4: printf(“Good!”);

• case 3: printf(“Pass!”);

• case 2: printf(“Fail!”);

• default : printf(“data error!”);

• }

Page 79: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 79

• 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);• }

Page 80: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 80

• 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 :

Page 81: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 81

• 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”) ;

• }

Page 82: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 82

• 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 .

Page 83: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 83

• 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 .

Page 84: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 84

• 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 .

Page 85: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 85

Program 4.6• #include <stdio.h>• 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 );•

Page 86: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 86

• 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 */

Page 87: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 87

• 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

Page 88: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 88

• 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

Page 89: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 89

• 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 .

Page 90: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 90

• 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 .

Page 91: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 91

• 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 :

Page 92: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 92

• 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 */

Page 93: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 93

The switch Statement (continued)

Page 94: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 94

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.

Page 95: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 95

Case Study: Data Validation (continued)

Page 96: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 96

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

Page 97: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 97

Common Compiler Errors

Page 98: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 98

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 formif (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

Page 99: A First Book of ANSI C Fourth Edition Chapter 4 Selection

A First Book of ANSI C, Fourth Edition 99

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