A First Book of C++A First Book of C++
Chapter 4Chapter 4
SelectionSelection
∗ In this chapter, you will learn about:
∗ Relational Expressions
∗ The if-else Statement
∗ Nested if Statements
∗ The switch Statement
∗ Common Programming Errors
A First Book of C++ 4th Edition 2
ObjectivesObjectives
∗ All computers are able to compare numbers
∗ Can be used to create an intelligence-like facility
∗ Relational expressions: expressions used to compare
operands
∗ Format: a relational operator connecting two variables
and/or constant operands
∗ Examples of valid relational expressions:
Age > 40 length <= 50 flag == done
A First Book of C++ 4th Edition 3
Relational ExpressionsRelational Expressions
Relational
operator
operand1 operand2
Relational Expressions (cont'd.)Relational Expressions (cont'd.)
A First Book of C++ 4th Edition 4
∗ Relational expressions (conditions):
∗ Are evaluated to yield/produce a numerical result
∗ Condition that is true evaluates to 1
∗ Condition that is false evaluates to 0
∗ Example:
∗ The relationship 2.0 > 3.3 is always false; therefore,
the expression has a value of 0
A First Book of C++ 4th Edition 5
Relational Expressions (cont'd.)Relational Expressions (cont'd.)
∗ More complex conditions can be created using logical
operators AND, OR, and NOT
∗ Represented by the symbols: &&, ||, !
∗ AND operator, &&:
∗ Used with two simple expressions
∗ Example: (age > 40) && (term < 10)
∗ Compound condition is true (has value of 1) only if age >
40 and term < 10
∗ Both expressions must be true
A First Book of C++ 4th Edition 6
Logical OperatorsLogical Operators
∗ OR operator, ||:
∗ Used with two simple expressions
∗ Example: (age > 40) || (term < 10)
∗ Compound condition is true if age > 40 or if term < 10
or if both conditions are true
∗ Both expressions true OR one of them is true
∗ NOT operator, !:
∗ Changes an expression to its opposite state
∗ If expression is true, then !expression is false
A First Book of C++ 4th Edition 7
Logical Operators (cont'd.)Logical Operators (cont'd.)
Logical Operators (cont'd.)Logical Operators (cont'd.)
A First Book of C++ 4th Edition 8
∗ Avoid testing equality of single- and double-precision
values and variables using == operator
∗ Tests fail because many decimals cannot be represented
accurately in binary
∗ For real operands:
∗ The expression operand_1 == operand_2
should be replaced by:
abs(operand_1 – operand_2) < EPSILON
∗ If this expression is true for very small EPSILON, then the
two operands are considered equal
A First Book of C++ 4th Edition 9
A Numerical Accuracy ProblemA Numerical Accuracy Problem
∗ Selects between two statements based on the results
of a comparison
∗ General form:
if (expression) true
statement1;
else false
statement2;
∗If the value of expression is true, statement1 is
executed
∗If the value is false, statement2 is executed
A First Book of C++ 4th Edition 10
TheThe if-elseif-else StatementStatement
A First Book of C++ 4th Edition 11
//expression
//statement 1
//statement 2
∗ Program 4.1 run twice with different input data
∗ Result 1:
Please type in the taxable income: 10000
Taxes are $ 200.00
∗ Result 2:
Please type in the taxable income: 30000
Taxes are $ 650.00
A First Book of C++ 4th Edition 12
TheThe if-elseif-else Statement (cont'd.)Statement (cont'd.)
∗ Sequence of single statements between braces
A First Book of C++ 4th Edition 13
Compound StatementsCompound Statements
//put braces if statement is more than 1
A First Book of C++ 4th Edition 14
//more than 1 statements,
use braces
//more than 1 statements,
use braces
∗ Output 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
A First Book of C++ 4th Edition 15
Compound Statements (cont'd.)Compound Statements (cont'd.)
∗ Block of code: all statements contained within a
compound statement
∗ Any variable declared within a block has meaning only
between its declaration and the closing braces of the
block
∗ Example with two blocks of code
A First Book of C++ 4th Edition 16
Block ScopeBlock Scope
{ // start of outer block
int a = 25;
int b = 17;
cout << “The value of a is ” << a << “ and b is ” << b
<< endl;
{ // start of inner block
double a = 46.25; //new data type & value for a
int c = 10;
cout << “ a is now ” << a //takes the new value
<< “ b is now ” << b
<< “ and c is ” << c << endl;
} // end of inner block
cout << “a is now ” << a << “ and b is ” << b << endl;
} // end of outer block
A First Book of C++ 4th Edition 17
Block Scope (cont'd.)Block Scope (cont'd.)
∗ Output of block scope example:
The value of a is 25 and b is 17
a is now 46.25 b is now 17 and c is 10
a is now 25 and b is 17
A First Book of C++ 4th Edition 18
Block Scope (cont'd.)Block Scope (cont'd.)
∗ A modification of if-else that omits else part
∗ if statement takes the form:
if (expression)
statement;
∗ Modified form called a one-way statement
∗ The statement following if (expression) is
executed only if the expression is true
∗ The statement may be a compound statement
A First Book of C++ 4th Edition 19
One-Way SelectionOne-Way Selection
// “if” with no “else” statement
One-Way Selection (cont'd.)One-Way Selection (cont'd.)
A First Book of C++ 4th Edition 20
//Multiple inputs in a single line, input separated by
space //(not advisable) without additional cout <<
system("pause");
This statement is executed
only if miles > LIMIT
//constant value do not change throughout the program
∗ Program 4.3 run twice with different input data
∗ Result 1:
Please type in car number and mileage: 256
3562.8
Car 256 is over the limit.
End of program output.
∗ Result 2:
Please type in car number and mileage: 23
2562.8
End of program output.
A First Book of C++ 4th Edition 21
One-Way Selection (cont'd.)One-Way Selection (cont'd.)
∗ Most common problems:
∗ Misunderstanding what an expression is
∗ Using the assignment operator, =, in place of the relational
operator, ==
∗ Example:
∗ Initialize int age = 18;
∗ The expression if (age = 40) sets age to the new value 40
∗ Does not compare age to 40 (but assigns the value 40 to age)
∗ Has a value of 40 (true)
∗ Produces invalid results if used in if-else statement
∗ Correct expression should be if (age == 40)
A First Book of C++ 4th Edition 22
Problems Associated with theProblems Associated with the if-if-
elseelse StatementStatement
∗ Example (cont'd.):
∗ The expression if(age == 40) compares age to 40
∗ Has a value of 0 (false), since age is initialized with value 18
∗ This expression will produce a valid test in an if-else
statement
A First Book of C++ 4th Edition 23
Problems Associated with theProblems Associated with the if-if-
elseelse Statement (cont'd.)Statement (cont'd.)
∗ if-else statement can contain simple or
compound/nested if statements
∗ Another if-else statement can be included
∗ Example:
if (hours < 9)
{
if (distance > 500)
cout << “snap”;
}
else
cout << “pop”;
A First Book of C++ 4th Edition 24
NestedNested ifif StatementsStatements
If within an if
statement
∗ Format:
if (expression_1)
statement1;
else if (expression_2)
statement2;
else
statement3;
∗ Chain can be extended indefinitely by making last
statement another if-else statement
A First Book of C++ 4th Edition 25
TheThe if-elseif-else ChainChain
A First Book of C++ 4th Edition 26
∗ Four new keywords used:
∗ switch, case, default, and break
∗ Function of switch:
∗ Expression following switch is evaluated
∗ Must evaluate to an integer result
∗ Results compared sequentially to alternative case values until
a match found
∗ Statements following matched case are executed
∗ When break statement reached, switch terminates
∗ If no match found, default statement block is executed
A First Book of C++ 4th Edition 27
TheThe switchswitch StatementStatement
∗ Format:
switch (expression)
{ // start of compound statement
case value_1: // terminated with a colon
statement1;
statement2;
break;
case value_2: // terminated with a colon
statement3;
break;
default: // terminated with a colon
statement4;
} // end of switch and compound statement
A First Book of C++ 4th Edition 28
TheThe switchswitch Statement (cont'd.)Statement (cont'd.)
A First Book of C++ 4th Edition 29
∗ Program 4.6 results:
Please type in two numbers: 12 3
Enter a select code:
1 for addition
2 for multiplication
3 for division : 2
The product of the numbers entered is 36
A First Book of C++ 4th Edition 30
TheThe switchswitch Statement (cont'd.)Statement (cont'd.)
∗ Using the assignment operator, =, in place of the
relational operator, ==
∗ Assuming that the if-else statement is selecting
an incorrect choice when the problem is really the
values being tested
∗ Using nested if statements without including braces
to clearly indicate the desired structure
A First Book of C++ 4th Edition 31
Common Programming ErrorsCommon Programming Errors
∗ Relational expressions (conditions):
∗ Are used to compare operands
∗ A condition that is true has a value of 1
∗ A condition that is false has a value of 0
∗ More complex conditions can be constructed from
relational expressions using C++’s logical operators,
&& (AND), || (OR), and ! (NOT)
∗ if-else statements select between two alternative
statements based on the value of an expression
A First Book of C++ 4th Edition 32
Summary
∗ if-else statements can contain other if-else
statements
∗ If braces are not used, each else statement is
associated with the closest unpaired if
∗ if-else chain: a multi-way selection statement
∗ Each else statement (except for the final else) is
another if-else statement
∗ Compound statement: any number of individual
statements enclosed within braces
A First Book of C++ 4th Edition 33
Summary (cont'd.)Summary (cont'd.)
∗ Variables have meaning only within the block where they
are declared
∗ Includes any inner blocks (use additional { } for inner blocks)
∗ switch statement: multiway selection statement
∗ The value of an integer expression is compared to a sequence
of integer or character constants or constant expressions
∗ Program execution transferred to first matching case
∗ Execution continues until optional break statement is
encountered
A First Book of C++ 4th Edition 34
Summary (cont'd.)Summary (cont'd.)
∗ A comprehensive set of test runs would reveal all possible
program errors
∗ Ensuring that a program works correctly for any combination
of input and computed data
∗ This goal is usually impossible
∗ Except for extremely simple programs
∗ At a minimum, test data should include:
∗ Suitable values for input data
∗ Illegal input values that the program should reject
∗ Limiting values that are checked in the program
A First Book of C++ 4th Edition 35
Chapter Supplement: A Closer LookChapter Supplement: A Closer Look
at Testingat Testing

Csc1100 lecture04 ch04

  • 1.
    A First Bookof C++A First Book of C++ Chapter 4Chapter 4 SelectionSelection
  • 2.
    ∗ In thischapter, you will learn about: ∗ Relational Expressions ∗ The if-else Statement ∗ Nested if Statements ∗ The switch Statement ∗ Common Programming Errors A First Book of C++ 4th Edition 2 ObjectivesObjectives
  • 3.
    ∗ All computersare able to compare numbers ∗ Can be used to create an intelligence-like facility ∗ Relational expressions: expressions used to compare operands ∗ Format: a relational operator connecting two variables and/or constant operands ∗ Examples of valid relational expressions: Age > 40 length <= 50 flag == done A First Book of C++ 4th Edition 3 Relational ExpressionsRelational Expressions Relational operator operand1 operand2
  • 4.
    Relational Expressions (cont'd.)RelationalExpressions (cont'd.) A First Book of C++ 4th Edition 4
  • 5.
    ∗ Relational expressions(conditions): ∗ Are evaluated to yield/produce a numerical result ∗ Condition that is true evaluates to 1 ∗ Condition that is false evaluates to 0 ∗ Example: ∗ The relationship 2.0 > 3.3 is always false; therefore, the expression has a value of 0 A First Book of C++ 4th Edition 5 Relational Expressions (cont'd.)Relational Expressions (cont'd.)
  • 6.
    ∗ More complexconditions can be created using logical operators AND, OR, and NOT ∗ Represented by the symbols: &&, ||, ! ∗ AND operator, &&: ∗ Used with two simple expressions ∗ Example: (age > 40) && (term < 10) ∗ Compound condition is true (has value of 1) only if age > 40 and term < 10 ∗ Both expressions must be true A First Book of C++ 4th Edition 6 Logical OperatorsLogical Operators
  • 7.
    ∗ OR operator,||: ∗ Used with two simple expressions ∗ Example: (age > 40) || (term < 10) ∗ Compound condition is true if age > 40 or if term < 10 or if both conditions are true ∗ Both expressions true OR one of them is true ∗ NOT operator, !: ∗ Changes an expression to its opposite state ∗ If expression is true, then !expression is false A First Book of C++ 4th Edition 7 Logical Operators (cont'd.)Logical Operators (cont'd.)
  • 8.
    Logical Operators (cont'd.)LogicalOperators (cont'd.) A First Book of C++ 4th Edition 8
  • 9.
    ∗ Avoid testingequality of single- and double-precision values and variables using == operator ∗ Tests fail because many decimals cannot be represented accurately in binary ∗ For real operands: ∗ The expression operand_1 == operand_2 should be replaced by: abs(operand_1 – operand_2) < EPSILON ∗ If this expression is true for very small EPSILON, then the two operands are considered equal A First Book of C++ 4th Edition 9 A Numerical Accuracy ProblemA Numerical Accuracy Problem
  • 10.
    ∗ Selects betweentwo statements based on the results of a comparison ∗ General form: if (expression) true statement1; else false statement2; ∗If the value of expression is true, statement1 is executed ∗If the value is false, statement2 is executed A First Book of C++ 4th Edition 10 TheThe if-elseif-else StatementStatement
  • 11.
    A First Bookof C++ 4th Edition 11 //expression //statement 1 //statement 2
  • 12.
    ∗ Program 4.1run twice with different input data ∗ Result 1: Please type in the taxable income: 10000 Taxes are $ 200.00 ∗ Result 2: Please type in the taxable income: 30000 Taxes are $ 650.00 A First Book of C++ 4th Edition 12 TheThe if-elseif-else Statement (cont'd.)Statement (cont'd.)
  • 13.
    ∗ Sequence ofsingle statements between braces A First Book of C++ 4th Edition 13 Compound StatementsCompound Statements //put braces if statement is more than 1
  • 14.
    A First Bookof C++ 4th Edition 14 //more than 1 statements, use braces //more than 1 statements, use braces
  • 15.
    ∗ Output ofProgram 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 A First Book of C++ 4th Edition 15 Compound Statements (cont'd.)Compound Statements (cont'd.)
  • 16.
    ∗ Block ofcode: all statements contained within a compound statement ∗ Any variable declared within a block has meaning only between its declaration and the closing braces of the block ∗ Example with two blocks of code A First Book of C++ 4th Edition 16 Block ScopeBlock Scope
  • 17.
    { // startof outer block int a = 25; int b = 17; cout << “The value of a is ” << a << “ and b is ” << b << endl; { // start of inner block double a = 46.25; //new data type & value for a int c = 10; cout << “ a is now ” << a //takes the new value << “ b is now ” << b << “ and c is ” << c << endl; } // end of inner block cout << “a is now ” << a << “ and b is ” << b << endl; } // end of outer block A First Book of C++ 4th Edition 17 Block Scope (cont'd.)Block Scope (cont'd.)
  • 18.
    ∗ Output ofblock scope example: The value of a is 25 and b is 17 a is now 46.25 b is now 17 and c is 10 a is now 25 and b is 17 A First Book of C++ 4th Edition 18 Block Scope (cont'd.)Block Scope (cont'd.)
  • 19.
    ∗ A modificationof if-else that omits else part ∗ if statement takes the form: if (expression) statement; ∗ Modified form called a one-way statement ∗ The statement following if (expression) is executed only if the expression is true ∗ The statement may be a compound statement A First Book of C++ 4th Edition 19 One-Way SelectionOne-Way Selection // “if” with no “else” statement
  • 20.
    One-Way Selection (cont'd.)One-WaySelection (cont'd.) A First Book of C++ 4th Edition 20 //Multiple inputs in a single line, input separated by space //(not advisable) without additional cout << system("pause"); This statement is executed only if miles > LIMIT //constant value do not change throughout the program
  • 21.
    ∗ Program 4.3run twice with different input data ∗ Result 1: Please type in car number and mileage: 256 3562.8 Car 256 is over the limit. End of program output. ∗ Result 2: Please type in car number and mileage: 23 2562.8 End of program output. A First Book of C++ 4th Edition 21 One-Way Selection (cont'd.)One-Way Selection (cont'd.)
  • 22.
    ∗ Most commonproblems: ∗ Misunderstanding what an expression is ∗ Using the assignment operator, =, in place of the relational operator, == ∗ Example: ∗ Initialize int age = 18; ∗ The expression if (age = 40) sets age to the new value 40 ∗ Does not compare age to 40 (but assigns the value 40 to age) ∗ Has a value of 40 (true) ∗ Produces invalid results if used in if-else statement ∗ Correct expression should be if (age == 40) A First Book of C++ 4th Edition 22 Problems Associated with theProblems Associated with the if-if- elseelse StatementStatement
  • 23.
    ∗ Example (cont'd.): ∗The expression if(age == 40) compares age to 40 ∗ Has a value of 0 (false), since age is initialized with value 18 ∗ This expression will produce a valid test in an if-else statement A First Book of C++ 4th Edition 23 Problems Associated with theProblems Associated with the if-if- elseelse Statement (cont'd.)Statement (cont'd.)
  • 24.
    ∗ if-else statementcan contain simple or compound/nested if statements ∗ Another if-else statement can be included ∗ Example: if (hours < 9) { if (distance > 500) cout << “snap”; } else cout << “pop”; A First Book of C++ 4th Edition 24 NestedNested ifif StatementsStatements If within an if statement
  • 25.
    ∗ Format: if (expression_1) statement1; elseif (expression_2) statement2; else statement3; ∗ Chain can be extended indefinitely by making last statement another if-else statement A First Book of C++ 4th Edition 25 TheThe if-elseif-else ChainChain
  • 26.
    A First Bookof C++ 4th Edition 26
  • 27.
    ∗ Four newkeywords used: ∗ switch, case, default, and break ∗ Function of switch: ∗ Expression following switch is evaluated ∗ Must evaluate to an integer result ∗ Results compared sequentially to alternative case values until a match found ∗ Statements following matched case are executed ∗ When break statement reached, switch terminates ∗ If no match found, default statement block is executed A First Book of C++ 4th Edition 27 TheThe switchswitch StatementStatement
  • 28.
    ∗ Format: switch (expression) {// start of compound statement case value_1: // terminated with a colon statement1; statement2; break; case value_2: // terminated with a colon statement3; break; default: // terminated with a colon statement4; } // end of switch and compound statement A First Book of C++ 4th Edition 28 TheThe switchswitch Statement (cont'd.)Statement (cont'd.)
  • 29.
    A First Bookof C++ 4th Edition 29
  • 30.
    ∗ Program 4.6results: Please type in two numbers: 12 3 Enter a select code: 1 for addition 2 for multiplication 3 for division : 2 The product of the numbers entered is 36 A First Book of C++ 4th Edition 30 TheThe switchswitch Statement (cont'd.)Statement (cont'd.)
  • 31.
    ∗ Using theassignment operator, =, in place of the relational operator, == ∗ Assuming that the if-else statement is selecting an incorrect choice when the problem is really the values being tested ∗ Using nested if statements without including braces to clearly indicate the desired structure A First Book of C++ 4th Edition 31 Common Programming ErrorsCommon Programming Errors
  • 32.
    ∗ Relational expressions(conditions): ∗ Are used to compare operands ∗ A condition that is true has a value of 1 ∗ A condition that is false has a value of 0 ∗ More complex conditions can be constructed from relational expressions using C++’s logical operators, && (AND), || (OR), and ! (NOT) ∗ if-else statements select between two alternative statements based on the value of an expression A First Book of C++ 4th Edition 32 Summary
  • 33.
    ∗ if-else statementscan contain other if-else statements ∗ If braces are not used, each else statement is associated with the closest unpaired if ∗ if-else chain: a multi-way selection statement ∗ Each else statement (except for the final else) is another if-else statement ∗ Compound statement: any number of individual statements enclosed within braces A First Book of C++ 4th Edition 33 Summary (cont'd.)Summary (cont'd.)
  • 34.
    ∗ Variables havemeaning only within the block where they are declared ∗ Includes any inner blocks (use additional { } for inner blocks) ∗ switch statement: multiway selection statement ∗ The value of an integer expression is compared to a sequence of integer or character constants or constant expressions ∗ Program execution transferred to first matching case ∗ Execution continues until optional break statement is encountered A First Book of C++ 4th Edition 34 Summary (cont'd.)Summary (cont'd.)
  • 35.
    ∗ A comprehensiveset of test runs would reveal all possible program errors ∗ Ensuring that a program works correctly for any combination of input and computed data ∗ This goal is usually impossible ∗ Except for extremely simple programs ∗ At a minimum, test data should include: ∗ Suitable values for input data ∗ Illegal input values that the program should reject ∗ Limiting values that are checked in the program A First Book of C++ 4th Edition 35 Chapter Supplement: A Closer LookChapter Supplement: A Closer Look at Testingat Testing