55
Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Embed Size (px)

Citation preview

Page 1: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Chapter 4Selection Structures: if and switch Statements

Instructor:Yuksel / Demirer

Page 2: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-2

Control Structures in C

• Control structuresControl structures control the flow of execution in a program or function.

• Compound statement, written as a group of statements bracketed by { and } is used to specify a sequential flow.

• There are three kinds of execution flow:– SequenceSequence:

• the execution of the program is sequential.– SelectionSelection:

• A control structure which chooses alternative to execute.– RepetitionRepetition:

• A control structure which repeats a group of statements.

• We will focus on the selectionselection control structure in this chapter.

Page 3: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-3

Sequence

{

statement1;

statement2;

statement3;

statementn;

}

statementstatement11

statementstatement22

statementstatementnn

Entry point

Exit point

Page 4: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-4

Repetition

statementstatement11

statementstatement22

statementstatementnn

Entry point

Exit point

Page 5: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-5

Selection

statementstatement11 statementstatement22

Entry point

Exit points

selectionselection

A selection control structure chooses which alternative to executeby testing the value of key variables.

Page 6: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-6

Condition

• Condition: an expression that is either false (represented by 0) or true (usually represented by 1)

• It is a criteria.• Example: rest_heart_rate > 75• Formats:

variable relational-operator variablevariable relational-operator constantvariable equality-operator variablevariable equality-operator constant

Page 7: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-7

Conditions

• A program may choose among alternative statements by testing the value of key variables.– e.g., if( your_grade > 60 )

printf(“you are passed!”);

• ConditionCondition is an expression that is either false (represented by 0) or true (represented by 1).– e.g., “your_grade > 60” is a condition.

• Conditions may contain relationalrelational or equalityequality operatorsoperators, and have the following forms.– variable relational-operatorrelational-operator variable (or constant)– variable equality-operatorequality-operator variable (or constant)

Page 8: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-8

Operators Used in Conditions

Operator Meaning Type

< Less than Relational

> Greater than Relational

<= Less than or equal to Relational

>= Greater than or equal to Relational

== Equal to Equality

!= Not equal to Equality

Page 9: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-9

Examples of Conditions

Operator Condition Meaning

<= x <= 0 x less than or equal to 0

< Power < MAX_POW Power less than MAX_POW

== mom_or_dad == ‘M’ mom_or_dad equal to ‘M’

!= num != SENTINEL num not equal to SENTINEL

Page 10: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-10

Logical Operators

• There are three kinds of logical operatorslogical operators..– &&: and– ||: or– !: not

• Logical expressionLogical expression is an expression which uses one or more logical operators, e.g.,– (temperature > 90.0 && humidity > 0.90)– !(n <= 0 || n >= 100).

Page 11: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-11

The Truth Table of Logical Operators

Op 1 Op 2 Op 1 && Op2 Op 1 || Op2

nonzero nonzero 1 1

nonzero 0 0 1

0 nonzero 0 1

0 0 0 0

Op 1 ! Op 1

nonzero 0

0 1

Page 12: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-12

Operator Precedence• An operator’s

precedenceprecedence determines its order of evaluation.

• Unary operatorUnary operator is an operator that has only one operand.– !, +(plus sign), -(minus

sign), and &(address of)

– They are evaluated second only after function calls.

Operator Precedence

function calls highest

! + - &

* / %

+ -

< <= >= >

== !=

&&

||

= lowest

Page 13: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-13

Example

Conditions:1. x<=02. Power < MAX_POW3. x>=y4. Item> MIN_ITEM5. m_o_d == ‘M’6. num != SENTINEL

-5 1024 1024 7 1.5 -999.0 ‘M’ 999 999

x power MAX_POW y item MIN_ITEM m_o_d num SENTINEL

Page 14: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-14

Examples

• salary < MIN_SALARY || dependent > 5

• temperature > 90.0 && humidity > 0.90

• n >= 0 && n <= 100

• n <= 0 && n <= 100

• !(0 <= n && n <= 100)

Page 15: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-15

Example

• x: 3.0, y: 4.0, z: 2.0, flag: 0

• Expressions:– ! flag– x + y / z <= 3.5– ! flag || (y + z >= x – z)– ! (flag || (y + z >= x – z))

Page 16: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-16

Evaluation for !flag || (y + z >= x - z)

Evaluation tree

The result of this expression is true

Page 17: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-17

Comparing Characters

• We can also compare characters in C using the relationalrelational and equality operatorsequality operators.

Expression Value

‘9’ >= ‘0’ 1 (true)

‘a’ < ‘e’ 1 (true)

‘Z’ == ‘z’ 0 (false)

‘a’ <= ‘A’ system dependent

Page 18: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-18

Page 19: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-19

DeMorgan’s Theorem

• DeMorgan’s theoremDeMorgan’s theorem gives us a way of transforming a logical expression into its complement.– The complement of expr1 && expr2 is comp1 || comp2, where comp1 and comp2 are the complement of expr1 and expr2, respectively.

– The complement of expr1 || expr2 is comp1 && comp2.

• e.g., age > 25 && (status == ‘S’ || status ==‘D’)

is equal to

!(age <=25 || (status != ‘S’) && status != ‘D’)

Page 20: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-20

More examples

• in_range = (n > -10 && n < 10)

• is_letter = (‘A’ <= ch && ch <= ‘Z’) ||

(‘a’ <= ch && ch <= ‘z’)

• even = (n % 2 ==0)

Page 21: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-21

The if Statement• The if statement is the primary selection selection control

structure.• Syntax: if (condition) statement;

else statement;• An example of two alternatives:

if ( rest_heart_rate > 56 ) printf(“Keep up your exercise program!\n”);

else printf(“Your heart is in excellent health!\n”);

• An example of one alternative:if ( x != 0.0 )

product = product * x;

Page 22: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-22

IF() THEN {} ELSE {}

if condition{compound_statement_1 } // if condition is true

else{ compound_statement_2 } // if condition is false

Example:

if (crash_test_rating_index <= MAX_SAFE_CTRI) {printf("Car #%d: safe\n", auto_id);safe = safe + 1;

}else {

printf("Car #%d: unsafe\n", auto_id);unsafe = unsafe + 1;

}

Page 23: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-23

Flowchart

• FlowchartFlowchart is a diagram that shows the step-by-step execution of a control structure.– A diamond-shaped boxdiamond-shaped box represents a decision.– A rectangular boxrectangular box represents an assignment

statement or a process.

Page 24: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-24

FlowchartsFlowcharts of if Statements with (a) Two Alternatives and (b) One Alternative

Decision Decision

Page 25: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-25

Nested if Statements• Nested Nested ifif statement statement is an if statement with

another another ifif statement statement as its true task or false task.

• e.g.,if (road_status == ‘S’)

elseprintf(“Drive carefully!\n”);

if (temp > 0) {printf(“Wet roads ahead!\n”);

}else{printf(“Icy roads ahead!\n”);

}

Page 26: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-26

An Example for the Flowchart of Nested if Statements

Another if statement

Main if statement

Page 27: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-27

IF() THEN {} ELSE {}

• When the symbol { follows a condition or else, the C complier either executes or skips all statements through the matching }

• In the example of the previous slide, if you omit the braces enclosing the compound statements, the if statement would end after the first printf call.

• The safe = safe + 1; statement would always be executed.

• You MUST use braces if you want to execute a compound statement in an if statement.

• To be safe, you may want to always use braces, even if there is only a single statement.

Page 28: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-28

No {}?

if (rest_heart_rate > 56)

printf("Keep up your exercise program!\n");

else

printf("Your heart is in excellent health!\n");

• If there is only one statement between the {} braces, you can omit the braces.

Page 29: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-29

One Alternative?

• You can also write the if statement with a single alternative that executes only when the condition is true.

if ( a <= b )

statement_1;• Another form – seldom used, but still allowed

if ( a == b )

else

statement_2;

Page 30: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-30

Nested if Statements

• So far we have used if statements to code decisions with one or two alternatives.

• A compound statement may contain more if statements.• In this section we use nested if statements (one if statement

inside another) to code decisions with multiple alternatives.

if (x > 0)num_pos = num_pos + 1;

elseif (x < 0)

num_neg = num_neg + 1;else

num_zero = num_zero + 1;

Page 31: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-31

Multiple-Alternative Decisions• If there are many alternatives, it is better to use the

syntax of multiple-alternative decisionmultiple-alternative decision.• Syntax:if (condition1)

statement1

else if (condition2)statement2

…else if (conditionn)

statementn

elsestatemente

Page 32: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-32

An Example of Multiple-Alternative Decisions

Page 33: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-33

Short Circuit Evaluation (1)

• Short-circuit (minimal) evaluation - C stops evaluating a logical expression as soon as its value can be determined.

– if the first part of the OR expression is true then the overall condition is true, so we don’t even look at the second part.

– if the first part of the AND expression is false then the overall condition is false, so we don’t even look at the second part.

– Example: if ((a<b) && (c>d)) if (a<b) is false, (c>d) is not evaluated.

if ((e!=f) || (g<h)) if (e!=f) is true, (g<h) is not evaluated.

– This can be significant for your program performance.

Page 34: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-34

Short Circuit Evaluation (2)

if (lname == “Smith”) && (ssn == 12345678)if (ssn == 12345678) && (lname == “Smith”) • What is the difference?• AND operator

– You want to get “false” as soon as possible, since it finishes comparisons

– i.e. the “most selective” test should be placed at the beginning.• OR operator

– You want to get “true” as soon as possible, since it finishes comparisons

– i.e. the “least selective” test should be placed at the beginning and the “most selective” test at the very end.

Page 35: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-35

Multiple-Alternative Decision Form of Nested if

• Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult for you to determine the logical structure of the if statement.

• You can code the nested if as the multiple-alternative decision described below:

if ( condition_1 )statement_1

else if ( condition_2 )statement_2...

else if ( condition_n )statement_n

elsestatement_e

Page 36: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-36

Example• Given a person’s salary, we want to calculate the tax due by

adding the base tax to the product of the percentage times the excess salary over the minimum salary for that range.

Salary Range Base tax Percentage of Excess

0.00 – 14,999.99 0.00 15

15,000.00 – 29,999.99 2,250.00 18

30,000.00 – 49,999.99 5,400.00 22

50,000.00 – 79,999.99 11,000,00 27

80,000.00 – 150,000.00 21,600.00 33

Page 37: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-37

if ( salary < 0.0 )tax = -1.0;

else if ( salary < 15000.00 )tax = 0.15 * salary;

else if ( salary < 30000.00 )tax = (salary – 15000.00)*0.18 + 2250.00;

else if ( salary < 50000.00)tax = (salary – 30000.00)*0.22 + 5400.00;

else if ( salary < 80000.00)tax = (salary – 50000.00)*0.27 + 11000.00;

else if ( salary <= 150000.00)tax = (salary – 80000.00)*0.33 + 21600.00;

elsetax = -1.0;

Page 38: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-38

Order of Conditions in a Multiple-Alternative Decision• When more than one condition in a multiple-

alternative decision is true, only the task following the first true condition executes.

• Therefore, the order of the conditions can affect the outcome.

• The order of conditions can also have an effect on program efficiency.

• If we know that salary range 30,000 - 49,999 are much more likely than the others, it would be more efficient to test first for that salary range. For example,if ((salary>30,000.00) && (salary<=49,999.00))

Page 39: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-39

Nested if Statements with More Than One Variable• In most of our examples, we have used nested if

statements to test the value of a single variable.• Consequently, we have been able to write each nested if

statement as a multiple-alternative decision.• If several variables are involved in the decision, we

cannot always use a multiple-alternative decision.• The next example contains a situation in which we can

use a nested if statement as a ”filter” to select data that satisfies several different criteria.

Page 40: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-40

Example

• The Department of Defense would like a program that identifies single males between the ages of 18 and 26, inclusive.

• One way to do this is to use a nested if statement whose conditions test the next criterion only if all previous criteria tested were satisfied.

• Another way would be to combine all of the tests into a single logical expression

• In the next nested if statement, the call to printf executes only when all conditions are true.

Page 41: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-41

Example

/* Print a message if all criteria are met.*/if ( marital_status == ’S’ ) if ( gender == ’M’ ) if ( age >= 18 && age <= 26 ) printf("All criteria are met.\n");

• or we could use an equivalent statement that uses a single if with a compound condition:

/* Print a message if all criteria are met.*/if ((maritial_status == ’S’) && (gender == ’M’) && (age >= 18 && age <= 26)) printf("All criteria are met.\n");

Page 42: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-42

Common if statement errors

if crsr_or_frgt == ’C’printf("Cruiser\n");

• This error is that there are no ( ) around the condition, and this is a syntax error.

if (crsr_or_frgt == ’C’);printf("Cruiser\n");

• This error is that there is a semicolon after the condition. C will interpret this as there is nothing to do if the condition is true.

Page 43: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-43

If Statement Style

• All if statement examples in this lecture have the true statements and false statements indented. Indentation helps the reader but conveys no meaning to the compiler.

• The word else is typed without indentation on a separate line.

• This formatting of the if statement makes its meaning more apparent and is used solely to improve program readability.

Page 44: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-44

Tracing an if Statement

• A critical step in program design is to verify that an algorithm or C statement is correct before you spend extensive time coding or debugging it.

• Often a few extra minutes spent in verifying the correctness of an algorithm saves hours of coding and testing time.

• A hand trace or desk check is a careful, step-by-step simulation on paper of how the computer executes the algorithm or statement.

• The results of this simulation should show the effect of each step’s execution using data that is relatively easy to process by hand.

• Sections 4.4 and 4.5 in the text have great step-by-step examples of using if statements to solve problems.

Page 45: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-45

The switch Statement• The switch statement is used to select one of several

alternatives when the selection is based on the value of a single variablea single variable or an expressionan expression.switch (controlling expression) {case label1:

statement1

break;case label2:

statement2

break;…

case labeln:statementn

break;default:

statementd;}

If the result of this controlling expression matches label1, execute staement1 and then break this switch block.

If the result matches none of all labels, execute the default statementd.

Page 46: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-46

Switch statements

• The switch statement is a better way of writing a program when a series of if-elseif occurs.

• The switch statement selects one of several alternatives.• The switch statement is especially useful when the

selection is based on the value of a single variable or of a simple expression– This is called the controlling expression

• In C, the value of this expression may be of type int or char, but not of type double.

Page 47: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-47

An Example of a switch Statement with Type char Case Labels

class is a char variable.

Two or more cases can execute the same statement.

Page 48: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-48

Case Study (1/2)

• Write a program that prompts the user to input input the boiling pointthe boiling point in degree Celsius.

• The program should output output the substancethe substance corresponding to the boiling point listed in the table.

• The program should output the message “substance “substance unknown”unknown” when it does not match any substance.

Substance Boiling point

Water 100°C

Mercury 357°C

Copper 1187°C

Silver 2193°C

Gold 2660°C

Page 49: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-49

Case Study (2/2)

• Examples of the scenario of your program.

• You can determine the substance within a range within a range of boiling pointsof boiling points to get bonus (e.g., +5 degrees).– Please refer to pages 207-208 in the text book.

• You can apply any technique in this chapter.

Please input: 357The substance is Mercury.

Please input: 3333Substance unknown.

Please input: 359The substance is Mercury.

Page 50: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-50

Figure 4.12 Example of a switch Statement with Type char Case Labels

Page 51: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-51

Explanation of Example

• This takes the value of the variable class and compares it to each of the cases in a top down approach.

• It stops after it finds the first case that is equal to the value of the variable class.

• It then starts to execute each line of the code following the matching case till it finds a break statement or the end of the switch statement.

• If no case is equal to the value of class, then the default case is executed. – default case is optional. So if no other case is equal to the value of the

controlling expression and there is a default case, then default case is executed. If there is no default case, then the entire switch body is skipped.

Page 52: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-52

Remember !!!• The statements following a case label may be one or more C

statements, so you do not need to make multiple statements into a single compound statement using braces.

• You cannot use a string such as ”Cruiser” or ”Frigate” as a case label.– It is important to remember that type int and char values may be

used as case labels, but strings and type double values cannot be used.

• Another very common error is the omission of the break statement at the end of one alternative.– In such a situation, execution ”falls through” into the next alternative.

• Forgetting the closing brace of the switch statement body is also easy to do.

• In the book it says that forgetting the last closing brace will make all following statements occur in the default case, but actually the code will not compile on most compilers.

Page 53: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-53

Nested if versus switch

• Advantages of if:– It is more general than a switch

• It can be a range of values such as x < 100

– A switch can not compare Strings or doubles

• Advantages of switch:– A switch is more readable

• Use the switch whenever there are ten or fewer case labels

Page 54: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-54

Common Programming Errors• Consider the statement:

if (0 <= x <= 4)• This is always true!

– First it does 0 <= x, which is true or false so it evaluates to 1 for true and 0 for false

– Then it takes that value, 0 or 1, and does 1 <= 4 or 0 <= 4– Both are always true

• In order to check a range use (0 <= x && x <= 4).

• Consider the statement:if (x = 10)

• This is always true!– The = symbol assigns x the value of 10, so the conditional statement evaluates

to 10– Since 10 is nonzero this is true.– You must use == for comparison

Page 55: Chapter 4 Selection Structures: if and switch Statements Instructor: Yuksel / Demirer

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-55

More Common Errors

• Don’t forget to parenthesize the condition.• Don’t forget the { and } if they are needed• C matches each else with the closest unmatched if, so be careful

so that you get the correct pairings of if and else statements.• In switch statements, make sure the controlling expression and

case labels are of the same permitted type.• Remember to include the default case for switch statements.• Don’t for get your { and } for the switch statement.• Don’t forget your break statements!!!