2 objectives you should be able to describe: relational expressions relational expressions the...

40

Upload: ferdinand-stevens

Post on 13-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements
Page 2: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

2

ObjectivesObjectives

You should be able to describe:You should be able to describe:Relational ExpressionsRelational ExpressionsThe The if-elseif-else Statement StatementNested Nested ifif Statements StatementsThe The switchswitch Statement Statement Common Programming ErrorsCommon Programming Errors

You should be able to describe:You should be able to describe:Relational ExpressionsRelational ExpressionsThe The if-elseif-else Statement StatementNested Nested ifif Statements StatementsThe The switchswitch Statement Statement Common Programming ErrorsCommon Programming Errors

Page 3: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

3

Relational ExpressionsRelational Expressions

All computers are able to compare numbersAll computers are able to compare numbers Can be used to create an intelligence-like facilityCan be used to create an intelligence-like facility

Relational ExpressionsRelational Expressions: expressions used : expressions used to compare operandsto compare operands FormatFormat: a relational operator connecting two : a relational operator connecting two

variable and/or constant operandsvariable and/or constant operands Examples of valid relational expressions:Examples of valid relational expressions:

Age > 40 length <= 50 Age > 40 length <= 50 flag == doneflag == done

All computers are able to compare numbersAll computers are able to compare numbers Can be used to create an intelligence-like facilityCan be used to create an intelligence-like facility

Relational ExpressionsRelational Expressions: expressions used : expressions used to compare operandsto compare operands FormatFormat: a relational operator connecting two : a relational operator connecting two

variable and/or constant operandsvariable and/or constant operands Examples of valid relational expressions:Examples of valid relational expressions:

Age > 40 length <= 50 Age > 40 length <= 50 flag == doneflag == done

Page 4: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

4

Relational Expressions (continued)Relational Expressions (continued)

Page 5: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

5

Relational Expressions (continued)Relational Expressions (continued)Relational ExpressionsRelational Expressions (conditions): (conditions):

Are evaluated to yield a numerical resultAre evaluated to yield a numerical result Condition that is true evaluates to 1Condition that is true evaluates to 1 Condition that is false evaluates to 0Condition that is false evaluates to 0

ExampleExample: : The relationship The relationship 2.0 > 3.32.0 > 3.3 is always is always

false, therefore the expression has a value false, therefore the expression has a value of of 00

Relational ExpressionsRelational Expressions (conditions): (conditions): Are evaluated to yield a numerical resultAre evaluated to yield a numerical result Condition that is true evaluates to 1Condition that is true evaluates to 1 Condition that is false evaluates to 0Condition that is false evaluates to 0

ExampleExample: : The relationship The relationship 2.0 > 3.32.0 > 3.3 is always is always

false, therefore the expression has a value false, therefore the expression has a value of of 00

Page 6: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

6

SelectionSelection Flow of ControlFlow of Control: the order in which a : the order in which a

program’s statements are executedprogram’s statements are executed Normal flow is sequential Normal flow is sequential

Selection and Repetition Statements allow Selection and Repetition Statements allow programmer to alter normal flowprogrammer to alter normal flow

SelectionSelection: selects a particular statement to be : selects a particular statement to be executed nextexecuted next Selection is from a well-defined setSelection is from a well-defined set

RepetitionRepetition: allows a set of statements to be : allows a set of statements to be repeatedrepeated

Flow of ControlFlow of Control: the order in which a : the order in which a program’s statements are executedprogram’s statements are executed Normal flow is sequential Normal flow is sequential

Selection and Repetition Statements allow Selection and Repetition Statements allow programmer to alter normal flowprogrammer to alter normal flow

SelectionSelection: selects a particular statement to be : selects a particular statement to be executed nextexecuted next Selection is from a well-defined setSelection is from a well-defined set

RepetitionRepetition: allows a set of statements to be : allows a set of statements to be repeatedrepeated

Page 7: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

7

Logical OperatorsLogical Operators

More complex conditions can be created More complex conditions can be created using logical operations using logical operations ANDAND, , OROR, and , and NOTNOT Represented by the symbols: Represented by the symbols: &&,&&, ||,||, !!

ANDAND Operator, Operator, &&&&:: Used with 2 simple expressionsUsed with 2 simple expressions ExampleExample: : (age > 40) && (term < 10)(age > 40) && (term < 10) Compound condition is true (has value of 1) only Compound condition is true (has value of 1) only

if if age > 40age > 40 and and term < 10term < 10

More complex conditions can be created More complex conditions can be created using logical operations using logical operations ANDAND, , OROR, and , and NOTNOT Represented by the symbols: Represented by the symbols: &&,&&, ||,||, !!

ANDAND Operator, Operator, &&&&:: Used with 2 simple expressionsUsed with 2 simple expressions ExampleExample: : (age > 40) && (term < 10)(age > 40) && (term < 10) Compound condition is true (has value of 1) only Compound condition is true (has value of 1) only

if if age > 40age > 40 and and term < 10term < 10

Page 8: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

8

Logical Operators (continued)Logical Operators (continued)

OROR Operator, Operator, ||:||: Used with 2 simple expressionsUsed with 2 simple expressions ExampleExample: : (age > 40) || (term < 10)(age > 40) || (term < 10) Compound condition is true if Compound condition is true if age > 40age > 40 or if or if term < 10term < 10 or if both conditions are true or if both conditions are true

NOTNOT Operator, Operator, !!:: Changes an expression to its opposite stateChanges an expression to its opposite state If If expressionAexpressionA is true, then is true, then !expressionA!expressionA

is falseis false

OROR Operator, Operator, ||:||: Used with 2 simple expressionsUsed with 2 simple expressions ExampleExample: : (age > 40) || (term < 10)(age > 40) || (term < 10) Compound condition is true if Compound condition is true if age > 40age > 40 or if or if term < 10term < 10 or if both conditions are true or if both conditions are true

NOTNOT Operator, Operator, !!:: Changes an expression to its opposite stateChanges an expression to its opposite state If If expressionAexpressionA is true, then is true, then !expressionA!expressionA

is falseis false

Page 9: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

9

Logical Operators (continued)Logical Operators (continued)

Page 10: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

10

A Numerical Accuracy ProblemA Numerical Accuracy Problem

Avoid testing equality of single and double-precision values and Avoid testing equality of single and double-precision values and variables using variables using ==== operator operator Tests fail because many decimals cannot be represented Tests fail because many decimals cannot be represented

accurately in binaryaccurately in binary For For realreal operands: operands:

The expressionThe expressionoperand_1 == operand_2operand_1 == operand_2

should be replaced byshould be replaced byabs(operand_1 – operand_2) < EPSILONabs(operand_1 – operand_2) < EPSILON

If this expression is true for very small If this expression is true for very small EPSILONEPSILON, then the two , then the two operands are considered equaloperands are considered equal

Avoid testing equality of single and double-precision values and Avoid testing equality of single and double-precision values and variables using variables using ==== operator operator Tests fail because many decimals cannot be represented Tests fail because many decimals cannot be represented

accurately in binaryaccurately in binary For For realreal operands: operands:

The expressionThe expressionoperand_1 == operand_2operand_1 == operand_2

should be replaced byshould be replaced byabs(operand_1 – operand_2) < EPSILONabs(operand_1 – operand_2) < EPSILON

If this expression is true for very small If this expression is true for very small EPSILONEPSILON, then the two , then the two operands are considered equaloperands are considered equal

Page 11: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

11

The if-else StatementThe if-else Statement Selects a sequence of one or more Selects a sequence of one or more

instructions based on the results of a instructions based on the results of a comparison comparison

General formGeneral form::

ifif ( (expressionexpression) ) <- no semicolon here<- no semicolon here statement1statement1;;elseelse <- no semicolon here<- no semicolon here statement2statement2;;

If the value of expression is true, If the value of expression is true, statement1statement1 is is executedexecuted

If the value is false, If the value is false, statement2statement2 is executed is executed

Selects a sequence of one or more Selects a sequence of one or more instructions based on the results of a instructions based on the results of a comparison comparison

General formGeneral form::

ifif ( (expressionexpression) ) <- no semicolon here<- no semicolon here statement1statement1;;elseelse <- no semicolon here<- no semicolon here statement2statement2;;

If the value of expression is true, If the value of expression is true, statement1statement1 is is executedexecuted

If the value is false, If the value is false, statement2statement2 is executed is executed

Page 12: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

12

The if-else Statement (continued)The if-else Statement (continued)

Page 13: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

13

Compound StatementsCompound Statements

Page 14: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

14

Compound Statements (continued)Compound Statements (continued)

Page 15: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

15

Compound Statements (continued)Compound Statements (continued)

Program 4.2 (continued):Program 4.2 (continued):Program 4.2 (continued):Program 4.2 (continued):

Page 16: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

16

The if-else Statement (continued)The if-else Statement (continued)Program 4.1 run twice with different Program 4.1 run twice with different

input datainput data Result 1:Result 1:

Please type in the taxable income: Please type in the taxable income: 1000010000Taxes are $ 200.00Taxes are $ 200.00

Result 2:Result 2:Please type in the taxable income: Please type in the taxable income: 3000030000Taxes are $ 650.00Taxes are $ 650.00

Program 4.1 run twice with different Program 4.1 run twice with different input datainput data Result 1:Result 1:

Please type in the taxable income: Please type in the taxable income: 1000010000Taxes are $ 200.00Taxes are $ 200.00

Result 2:Result 2:Please type in the taxable income: Please type in the taxable income: 3000030000Taxes are $ 650.00Taxes are $ 650.00

Page 17: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

17

Compound Statements (continued)Compound Statements (continued)

Output of Program 4.2Output of Program 4.2

Enter the temperature to be Enter the temperature to be converted: 212converted: 212

Enter an f if the temperature is in Enter an f if the temperature is in Fahrenheit or a c if the Fahrenheit or a c if the temperature is in Celsius: ftemperature is in Celsius: f

The equivalent Celsius temperature The equivalent Celsius temperature is 100.00is 100.00

Output of Program 4.2Output of Program 4.2

Enter the temperature to be Enter the temperature to be converted: 212converted: 212

Enter an f if the temperature is in Enter an f if the temperature is in Fahrenheit or a c if the Fahrenheit or a c if the temperature is in Celsius: ftemperature is in Celsius: f

The equivalent Celsius temperature The equivalent Celsius temperature is 100.00is 100.00

Page 18: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

18

Compound Statements (continued)Compound Statements (continued) boolbool:: a C++ built-in Boolean Data Type a C++ built-in Boolean Data Type

Two Boolean values: Two Boolean values: truetrue and and falsefalse Values of Values of truetrue and and falsefalse: integer values 1 : integer values 1

and 0 respectivelyand 0 respectively To see Boolean values displayed as To see Boolean values displayed as truetrue

and and falsefalse insert the manipulator insert the manipulator boolalphaboolalpha into the into the coutcout stream prior to stream prior to displaying Boolean valuesdisplaying Boolean values

Applying prefix or postfix increment Applying prefix or postfix increment (++)(++) to a to a boolbool variable sets its value to variable sets its value to truetrue

boolbool:: a C++ built-in Boolean Data Type a C++ built-in Boolean Data Type Two Boolean values: Two Boolean values: truetrue and and falsefalse

Values of Values of truetrue and and falsefalse: integer values 1 : integer values 1 and 0 respectivelyand 0 respectively

To see Boolean values displayed as To see Boolean values displayed as truetrue and and falsefalse insert the manipulator insert the manipulator boolalphaboolalpha into the into the coutcout stream prior to stream prior to displaying Boolean valuesdisplaying Boolean values

Applying prefix or postfix increment Applying prefix or postfix increment (++)(++) to a to a boolbool variable sets its value to variable sets its value to truetrue

Page 19: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

19

Block ScopeBlock ScopeBlock of CodeBlock of Code: All statements contained : All statements contained

within a compound statementwithin a compound statementAny variable declared within a block has Any variable declared within a block has

meaning only between its declaration and meaning only between its declaration and the closing braces of the blockthe closing braces of the block

Example with two blocks of codeExample with two blocks of code

Block of CodeBlock of Code: All statements contained : All statements contained within a compound statementwithin a compound statement

Any variable declared within a block has Any variable declared within a block has meaning only between its declaration and meaning only between its declaration and the closing braces of the blockthe closing braces of the block

Example with two blocks of codeExample with two blocks of code

Page 20: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

20

Block Scope (continued)Block Scope (continued){ { // start of outer block// start of outer block

int a = 25;int a = 25;int b = 17;int b = 17;cout << “The value of a is ” << a << “ and b is ” << b cout << “The value of a is ” << a << “ and b is ” << b << endl;<< endl;{ // start of inner block{ // start of inner block

double a = 46.25;double a = 46.25; int c = 10;int c = 10; cout << “a is now ” << acout << “a is now ” << a << “ b is now ” << b<< “ b is now ” << b << “ and c is ” << c << endl;<< “ and c is ” << c << endl;

}} // end of inner block // end of inner blockcout << “a is now ” << a << “ and b is ” << b << endl;cout << “a is now ” << a << “ and b is ” << b << endl;

} // end of outer block} // end of outer block

{ { // start of outer block// start of outer blockint a = 25;int a = 25;int b = 17;int b = 17;cout << “The value of a is ” << a << “ and b is ” << b cout << “The value of a is ” << a << “ and b is ” << b << endl;<< endl;{ // start of inner block{ // start of inner block

double a = 46.25;double a = 46.25; int c = 10;int c = 10; cout << “a is now ” << acout << “a is now ” << a << “ b is now ” << b<< “ b is now ” << b << “ and c is ” << c << endl;<< “ and c is ” << c << endl;

}} // end of inner block // end of inner blockcout << “a is now ” << a << “ and b is ” << b << endl;cout << “a is now ” << a << “ and b is ” << b << endl;

} // end of outer block} // end of outer block

Page 21: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

21

Block Scope (continued)Block Scope (continued)

Output of Block Scope exampleOutput of Block Scope example::

The value of a is 25 and b is 17The value of a is 25 and b is 17a is now 46.25 b is now 17 and c is a is now 46.25 b is now 17 and c is 1010

a is now 25 and b is 17a is now 25 and b is 17

Output of Block Scope exampleOutput of Block Scope example::

The value of a is 25 and b is 17The value of a is 25 and b is 17a is now 46.25 b is now 17 and c is a is now 46.25 b is now 17 and c is 1010

a is now 25 and b is 17a is now 25 and b is 17

Page 22: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

22

Block Scope (continued)Block Scope (continued)

Common programming practiceCommon programming practice: : place opening brace of a compound place opening brace of a compound statement on the same line as statement on the same line as ifif and and elseelse statements statements

if (tempType == ‘f’) {if (tempType == ‘f’) { celcius = (5.0 / 9.0) * (temp – 32);celcius = (5.0 / 9.0) * (temp – 32); cout << cout << “\nThe equivalent Celsius “\nThe equivalent Celsius

temperature is”temperature is” << celsius << endl;<< celsius << endl;

}}

Common programming practiceCommon programming practice: : place opening brace of a compound place opening brace of a compound statement on the same line as statement on the same line as ifif and and elseelse statements statements

if (tempType == ‘f’) {if (tempType == ‘f’) { celcius = (5.0 / 9.0) * (temp – 32);celcius = (5.0 / 9.0) * (temp – 32); cout << cout << “\nThe equivalent Celsius “\nThe equivalent Celsius

temperature is”temperature is” << celsius << endl;<< celsius << endl;

}}

Page 23: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

23

Block Scope (continued)Block Scope (continued)

The traditional format:The traditional format:

If (tempType == ‘f’) If (tempType == ‘f’) {{celsius = (5.0 / 9.0) * (temp – celsius = (5.0 / 9.0) * (temp – 32);32);coutcout << “\nThe equivalent Celsius << “\nThe equivalent Celsius temperature is ”temperature is ” << celsius << endl;<< celsius << endl;

}}

The traditional format:The traditional format:

If (tempType == ‘f’) If (tempType == ‘f’) {{celsius = (5.0 / 9.0) * (temp – celsius = (5.0 / 9.0) * (temp – 32);32);coutcout << “\nThe equivalent Celsius << “\nThe equivalent Celsius temperature is ”temperature is ” << celsius << endl;<< celsius << endl;

}}

Page 24: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

24

One-Way SelectionOne-Way Selection

A modification of A modification of if-elseif-else that omits that omits elseelse partpart ifif statement takes the form: statement takes the form:

ifif ( (expressionexpression))elseelse;;

Modified form called a one-way statementModified form called a one-way statement The statement following The statement following if (if (expressionexpression)) is is

executed only if the expression is true executed only if the expression is true The statement may be a compound statementThe statement may be a compound statement

A modification of A modification of if-elseif-else that omits that omits elseelse partpart ifif statement takes the form: statement takes the form:

ifif ( (expressionexpression))elseelse;;

Modified form called a one-way statementModified form called a one-way statement The statement following The statement following if (if (expressionexpression)) is is

executed only if the expression is true executed only if the expression is true The statement may be a compound statementThe statement may be a compound statement

Page 25: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

25

One-Way Selection (continued)One-Way Selection (continued)

Page 26: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

26

One-Way Selection (continued)One-Way Selection (continued)

Program 4.3 run twice with different input Program 4.3 run twice with different input datadata Result 1:Result 1:

Please type in car number and mileage: 256 Please type in car number and mileage: 256 3562.83562.8

Car 256 is over the limit.Car 256 is over the limit.End of program output.End of program output.

Result 2:Result 2:Please type in car number and mileage: 23 Please type in car number and mileage: 23 2562.82562.8

End of program output.End of program output.

Program 4.3 run twice with different input Program 4.3 run twice with different input datadata Result 1:Result 1:

Please type in car number and mileage: 256 Please type in car number and mileage: 256 3562.83562.8

Car 256 is over the limit.Car 256 is over the limit.End of program output.End of program output.

Result 2:Result 2:Please type in car number and mileage: 23 Please type in car number and mileage: 23 2562.82562.8

End of program output.End of program output.

Page 27: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

27

Problems Associated with the if-else StatementProblems Associated with the if-else Statement

Most common problemsMost common problems:: Misunderstanding what an expression isMisunderstanding what an expression is Using the assignment operator, Using the assignment operator, ==, in place of the , in place of the

relational operator, relational operator, ==== ExampleExample::

Initialize Initialize age = 18age = 18 The expression The expression (age = 30)(age = 30) sets sets ageage to to 3030

Does not compare Does not compare ageage to 30 to 30 Has a value of 30 (true)Has a value of 30 (true) Produces invalid results if used in Produces invalid results if used in if-elseif-else statementstatement

Most common problemsMost common problems:: Misunderstanding what an expression isMisunderstanding what an expression is Using the assignment operator, Using the assignment operator, ==, in place of the , in place of the

relational operator, relational operator, ==== ExampleExample::

Initialize Initialize age = 18age = 18 The expression The expression (age = 30)(age = 30) sets sets ageage to to 3030

Does not compare Does not compare ageage to 30 to 30 Has a value of 30 (true)Has a value of 30 (true) Produces invalid results if used in Produces invalid results if used in if-elseif-else statementstatement

Page 28: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

28

Problems Associated with the if-else Statement (continued)Problems Associated with the if-else Statement (continued)

Example continued:Example continued: The expression The expression (age == 30)(age == 30) compares compares ageage to to 3030 has a value of 0 (false)has a value of 0 (false)

This expression will produce a valid test in This expression will produce a valid test in an an if-elseif-else statementstatement

Example continued:Example continued: The expression The expression (age == 30)(age == 30) compares compares ageage to to 3030 has a value of 0 (false)has a value of 0 (false)

This expression will produce a valid test in This expression will produce a valid test in an an if-elseif-else statementstatement

Page 29: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

29

Nested if StatementsNested if Statements

if-elseif-else statement can contain simple statement can contain simple or compound statementsor compound statements Another Another if-elseif-else statement can be statement can be

includedincludedExample:Example:

If (hours < 9)If (hours < 9){{if (hours > 6)if (hours > 6)

cout << “snap”;cout << “snap”;}}elseelsecout << “pop”;cout << “pop”;

if-elseif-else statement can contain simple statement can contain simple or compound statementsor compound statements Another Another if-elseif-else statement can be statement can be

includedincludedExample:Example:

If (hours < 9)If (hours < 9){{if (hours > 6)if (hours > 6)

cout << “snap”;cout << “snap”;}}elseelsecout << “pop”;cout << “pop”;

Page 30: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

30

The if-else ChainThe if-else Chain

Format:Format:if (if (expression_1expression_1))statement1;statement1;

else else if (if (expression_2expression_2))statement2statement2;;

elseelsestatement3statement3;;

Chain can be extended indefinitely by making Chain can be extended indefinitely by making last statement another last statement another if-elseif-else statement statement

Format:Format:if (if (expression_1expression_1))statement1;statement1;

else else if (if (expression_2expression_2))statement2statement2;;

elseelsestatement3statement3;;

Chain can be extended indefinitely by making Chain can be extended indefinitely by making last statement another last statement another if-elseif-else statement statement

Page 31: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

31

The if-else Chain (continued)The if-else Chain (continued)

Page 32: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

32

The switch StatementThe switch Statement

Format:Format:switch (switch (expressionexpression)){{ // start of compound // start of compound statementstatementcase case value_1value_1:: <- terminated with a colon<- terminated with a colon statement1statement1;; statement2statement2;; break;break;case case value_2value_2:: <- terminated with a colon <- terminated with a colon statementmstatementm;; break;break;defaultdefault:: <- terminated with a colon <- terminated with a colon statementaastatementaa;;

}} // end of switch and // end of switch and compoundcompound

// statement// statement

Format:Format:switch (switch (expressionexpression)){{ // start of compound // start of compound statementstatementcase case value_1value_1:: <- terminated with a colon<- terminated with a colon statement1statement1;; statement2statement2;; break;break;case case value_2value_2:: <- terminated with a colon <- terminated with a colon statementmstatementm;; break;break;defaultdefault:: <- terminated with a colon <- terminated with a colon statementaastatementaa;;

}} // end of switch and // end of switch and compoundcompound

// statement// statement

Page 33: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

33

The switch Statement (continued)The switch Statement (continued)

Four new keywords usedFour new keywords used:: switchswitch, , casecase, , defaultdefault and and breakbreak

Function:Function: Expression following Expression following switchswitch is evaluated is evaluated

Must evaluate to an integer resultMust evaluate to an integer result Result compared sequentially to alternative Result compared sequentially to alternative casecase

values until a match foundvalues until a match found Statements following matched Statements following matched casecase are executed are executed When When breakbreak statement reached, statement reached, switchswitch terminates terminates If no match found, default statement block is executedIf no match found, default statement block is executed

Four new keywords usedFour new keywords used:: switchswitch, , casecase, , defaultdefault and and breakbreak

Function:Function: Expression following Expression following switchswitch is evaluated is evaluated

Must evaluate to an integer resultMust evaluate to an integer result Result compared sequentially to alternative Result compared sequentially to alternative casecase

values until a match foundvalues until a match found Statements following matched Statements following matched casecase are executed are executed When When breakbreak statement reached, statement reached, switchswitch terminates terminates If no match found, default statement block is executedIf no match found, default statement block is executed

Page 34: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

34

The switch Statement (continued)The switch Statement (continued)

Page 35: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

35

The switch Statement (continued)The switch Statement (continued)

Program 4.6 (continued):Program 4.6 (continued):Program 4.6 (continued):Program 4.6 (continued):

Page 36: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

36

The switch Statement (continued)The switch Statement (continued)

Program 4.6 results:Program 4.6 results:

Please type in two numbers: 12 3Please type in two numbers: 12 3Enter a select code:Enter a select code:

1 for addition1 for addition2 for multiplication2 for multiplication3 for division : 23 for division : 2

The product of the numbers entered is The product of the numbers entered is 3636

Program 4.6 results:Program 4.6 results:

Please type in two numbers: 12 3Please type in two numbers: 12 3Enter a select code:Enter a select code:

1 for addition1 for addition2 for multiplication2 for multiplication3 for division : 23 for division : 2

The product of the numbers entered is The product of the numbers entered is 3636

Page 37: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

37

Common Programming ErrorsCommon Programming Errors

Using the assignment operator , Using the assignment operator , ==, in , in place of the relational operator, place of the relational operator, ====

Assuming that the Assuming that the if-elseif-else statement statement is selecting an incorrect choice when is selecting an incorrect choice when the problem is really the values being the problem is really the values being testedtested

Using nested Using nested ifif statements without statements without including braces to clearly indicate the including braces to clearly indicate the desired structuredesired structure

Using the assignment operator , Using the assignment operator , ==, in , in place of the relational operator, place of the relational operator, ====

Assuming that the Assuming that the if-elseif-else statement statement is selecting an incorrect choice when is selecting an incorrect choice when the problem is really the values being the problem is really the values being testedtested

Using nested Using nested ifif statements without statements without including braces to clearly indicate the including braces to clearly indicate the desired structuredesired structure

Page 38: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

38

SummarySummary

Relational Expressions (conditions): Relational Expressions (conditions): Are used to compare operandsAre used to compare operands A condition that is true has a value of 1A condition that is true has a value of 1 A condition that is false has a value of 0A condition that is false has a value of 0

More complex conditions can be constructed More complex conditions can be constructed from relational expressions using C++’s from relational expressions using C++’s logical operators, logical operators, && (AND)&& (AND),, || (OR) || (OR), , and and ! (NOT)! (NOT)

if-elseif-else statements select between two statements select between two alternative statements based on the value of alternative statements based on the value of an expressionan expression

Relational Expressions (conditions): Relational Expressions (conditions): Are used to compare operandsAre used to compare operands A condition that is true has a value of 1A condition that is true has a value of 1 A condition that is false has a value of 0A condition that is false has a value of 0

More complex conditions can be constructed More complex conditions can be constructed from relational expressions using C++’s from relational expressions using C++’s logical operators, logical operators, && (AND)&& (AND),, || (OR) || (OR), , and and ! (NOT)! (NOT)

if-elseif-else statements select between two statements select between two alternative statements based on the value of alternative statements based on the value of an expressionan expression

Page 39: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

39

Summary (continued)Summary (continued)

if-elseif-else statements can contain other statements can contain other if-if-elseelse statements statements If braces are not used, each If braces are not used, each elseelse statement is statement is

associated with the closest unpaired associated with the closest unpaired ifif if-elseif-else Chain:Chain: a multi-way selection a multi-way selection

statementstatement Each Each elseelse statement (except for the final statement (except for the final elseelse) is ) is

another another if-elseif-else statement statement Compound Statement:Compound Statement: any number of any number of

individual statements enclosed within bracesindividual statements enclosed within braces

if-elseif-else statements can contain other statements can contain other if-if-elseelse statements statements If braces are not used, each If braces are not used, each elseelse statement is statement is

associated with the closest unpaired associated with the closest unpaired ifif if-elseif-else Chain:Chain: a multi-way selection a multi-way selection

statementstatement Each Each elseelse statement (except for the final statement (except for the final elseelse) is ) is

another another if-elseif-else statement statement Compound Statement:Compound Statement: any number of any number of

individual statements enclosed within bracesindividual statements enclosed within braces

Page 40: 2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements

40

Summary (continued)Summary (continued) Variables have meaning only within the block Variables have meaning only within the block

where they are declaredwhere they are declared Includes any inner blocksIncludes any inner blocks

switchswitch Statement: Statement: multiway selection statement multiway selection statement The value of an integer expression is compared to a The value of an integer expression is compared to a

sequence of integer or character constants or constant sequence of integer or character constants or constant expressionsexpressions

Program execution transferred to first matching caseProgram execution transferred to first matching case Execution continues until optional break statement is Execution continues until optional break statement is

encounteredencountered

Variables have meaning only within the block Variables have meaning only within the block where they are declaredwhere they are declared Includes any inner blocksIncludes any inner blocks

switchswitch Statement: Statement: multiway selection statement multiway selection statement The value of an integer expression is compared to a The value of an integer expression is compared to a

sequence of integer or character constants or constant sequence of integer or character constants or constant expressionsexpressions

Program execution transferred to first matching caseProgram execution transferred to first matching case Execution continues until optional break statement is Execution continues until optional break statement is

encounteredencountered