Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )

Similar presentations


Presentation on theme: "Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )"— Presentation transcript:

1 Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )

2 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. There are three kinds of execution flow: –Sequence –Sequence: the execution of the program is sequential. –Selection –Selection: A control structure which chooses alternative to execute. –Repetition –Repetition: A control structure which repeats a group of statements. selectionWe will focus on the selection control structure in this chapter.

3 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-3 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. relationalequality operatorsConditions may contain relational or equality operators, and have the following forms. relational-operator –variable relational-operator variable (or constant) equality-operator –variable equality-operator variable (or constant)

4 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-4 Operators Used in Conditions OperatorMeaningType <Less thanRelational >Greater thanRelational <=Less than or equal toRelational >=Greater than or equal toRelational ==Equal toEquality !=Not equal toEquality

5 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-5 Examples of Conditions OperatorConditionMeaning <=x <= 0x less than or equal to 0 < Power < MAX_POWPower less than MAX_POW == mom_or_dad == ‘M’ mom_or_dad equal to ‘M’ != num != SETINELnum not equal to SETINEL

6 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-6 Logical Operators logical operators.There are three kinds of logical 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 = 100).

7 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-7 The Truth Table of Logical Operators Op 1Op 2 Op 1 && Op2Op 1 || Op2 nonzero 11 001 0 01 0000 Op 1 ! Op 1 nonzero0 01

8 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-8 Operator Precedence precedenceAn operator’s precedence 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. OperatorPrecedence function callshighest ! + - & * / % + - = > == != && || = lowest

9 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-9 Evaluation for !flag || (y + z >= x - z) Evaluation tree The result of this expression is true

10 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-10 Comparing Characters relationalequality operatorsWe can also compare characters in C using the relational and equality operators. ExpressionValue ‘9’ >= ‘0’1 (true) ‘a’ < ‘e’1 (true) ‘Z’ == ‘z’0 (false) ‘a’ <= ‘A’system dependent

11 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-11 DeMorgan’s Theorem DeMorgan’s theoremDeMorgan’s theorem gives us a way of transforming a logical expression into its complement. –The complement of expr 1 && expr 2 is comp 1 || comp 2, where comp 1 and comp 2 are the complement of expr 1 and expr 2, respectively. –The complement of expr 1 || expr 2 is comp 1 && comp 2. e.g., age > 25 && (status == ‘S’ || status ==‘D’) is equal to !(age <=25 || (status != ‘S’) && status != ‘D’)

12 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-12 The if Statement selectionThe if statement is the primary 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;

13 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-13 Flowchart FlowchartFlowchart is a diagram that shows the step-by- step execution of a control structure. diamond-shaped box –A diamond-shaped box represents a decision. rectangular box –A rectangular box represents an assignment statement or a process.

14 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-14 Flowcharts Flowcharts of if Statements with (a) Two Alternatives and (b) One Alternative Decision

15 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-15 Nested if Statements Nested if statement another if statementNested if statement is an if statement with another if statement as its true task or false task. e.g., if (road_status == ‘S’) else printf(“Drive carefully!\n”); if (temp > 0) { printf(“Wet roads ahead!\n”); } else { printf(“Icy roads ahead!\n”); }

16 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-16 An Example for the Flowchart of Nested if Statements Another if statement Main if statement

17 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-17 Multiple-Alternative Decisions multiple-alternative decisionIf there are many alternatives, it is better to use the syntax of multiple-alternative decision. Syntax: if (condition 1 ) statement 1 else if (condition 2 ) statement 2 … else if (condition n ) statement n else statement e

18 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-18 An Example of Multiple-Alternative Decisions

19 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-19 The switch Statement a single variablean expressionThe switch statement is used to select one of several alternatives when the selection is based on the value of a single variable or an expression. switch (controlling expression) { case label 1 : statement 1 break ; case label 2 : statement 2 break ; … case label n : statement n break ; default: statement d ; } If the result of this controlling expression matches label 1, execute staement 1 and then break this switch block. If the result matches none of all labels, execute the default statement d.

20 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-20 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.

21 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-21 Homework #3 (1/2) input the boiling pointWrite a program that prompts the user to input the boiling point in degree Celsius. output the substanceThe program should output the substance corresponding to the boiling point listed in the table. “substance unknown”The program should output the message “substance unknown” when it does not match any substance. SubstanceBoiling point Water100°C Mercury357°C Copper1187°C Silver2193°C Gold2660°C

22 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.4-22 Homework #3 (2/2) Examples of the scenario of your program. within a range of boiling pointsYou can determine the substance within a range of 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: 357 The substance is Mercury. Please input: 3333 Substance unknown. Please input: 359 The substance is Mercury.


Download ppt "Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )"

Similar presentations


Ads by Google