Upload
catherine-howard
View
218
Download
0
Embed Size (px)
Citation preview
Chapter 7 Selection
Dept of Computer EngineeringKhon Kaen University
178110: Computer Programming (II/2546) 2
Major Concepts The if statement The if...else… statement Statement blocks Compound conditions Short-circuiting Boolean expressions Nested selection statements The switch statement
178110: Computer Programming (II/2546) 3
Introduction The programs in the previous
chapters have sequential execution Each statement in the program
executes once, and they are executed in the same order that they are listed
What if we want some statements to be executed only if some condition is true?
178110: Computer Programming (II/2546) 4
The if Statement The if statement allows conditional
execution Its syntax is
if (condition)a block of statements
condition is an integral expression a block of statements consists of one or
more executable statements The statement will be executed only if the
value of the integral expression is nonzero
178110: Computer Programming (II/2546) 5
Flow Chart of “if” Statement
condition
statement
true
false
178110: Computer Programming (II/2546) 6
An “if” Exampleint main(){
int n, d;cout << “Enter two positive integers: “;cin >> n >> d;if (n%d)
cout << n << “ is not divisible by “ << d << endl;
return 0;}
178110: Computer Programming (II/2546) 7
An “if” Example (Cont.) if (n%d)
cout << n << “ is not divisible by “ … In which condition, the above cout
statement is executed? n = 66, d = 7 n = 6, d = 3
In C++, whenever an integral expression is used as a condition, The value 0 means “false” All other values mean “true”
178110: Computer Programming (II/2546) 8
The if…else… Statement What if we want to have the cout
statement when n is divisible by n? We need to have “if …else…”
statement The if…else… statement causes one
of two alternative statements to execute depending upon whether the condition is true
178110: Computer Programming (II/2546) 9
If…else… Statement (Cont.)
Its syntax isif (condition)
statement1;else
statement2; If the value of the condition is nonzero
then statement1 will execute; otherwise statement2 will execute
178110: Computer Programming (II/2546) 10
Flow Chart of “if…else…”
condition
statement 1
true
false
statement 2
178110: Computer Programming (II/2546) 11
An “if…else…” Exampleint main(){
int n, d;cout << “Enter two positive integers: “;cin >> n >> d;if (n%d)
cout << n << “ is not divisible by “ << d << endl;
elsecout << n “ << is divisible by “ << d <<
endl;return 0;
}
178110: Computer Programming (II/2546) 12
An “if…else” Example (Cont.)
if (n%d) cout << n << “ is not divisible by “
…else
cout << n << “ is divisible by “ … In these conditions, which cout statement
is executed? n = 66, d = 7 n = 6, d = 3
In “if…else…” clause, how many statement is there? One
178110: Computer Programming (II/2546) 13
Keywords in C++ A keyword is a word that is already
defined and is reserved for a unique purpose in programs written in that language
Standard C++ now has 74 keywords Examples of C++ keywords
if else int bool float double
178110: Computer Programming (II/2546) 14
Keywords in C++ There are two kinds of keywords
Reserved words Standard identifiers
A reserved word is a keyword that serves as a structure marker, used to define the syntax of the language Examples: if else
A standard identifier is a keyword that names a specific element of the language Examples: int bool
178110: Computer Programming (II/2546) 15
Comparison Operators The six comparison operators are
x < y // x is less than yx > y // x is greater than yx <= y // x is less than or equal to yx >= y // x is greater than or equal to yx == y // x is equal to yx != y // x is not equal to y
These can be used to compare the values of expressions of any ordinal type
178110: Computer Programming (II/2546) 16
Comparison Example1 int main(){
int m, n;cout << “Enter two integers: “;cin >> m >> n;if (m < n)
cout << m << “ is the minimum “ << endl;else
cout << n << “ is the minimum “ << endl;
}
178110: Computer Programming (II/2546) 17
Comparison Example2int a = 4;float b = 3.4;char c = 'c';if (a < b)
cout << "a is less than b" << endl;else
cout << "a is greater than or equal to b" << endl;
if (a < c) cout << "a is less than c" << endl;else
cout << "a is greater than or equal to b" << endl;
178110: Computer Programming (II/2546) 18
What is Wrong?int main(){
int n;cout << “Enter an integer:”;cin >> n;if (n = 2)
cout << n << “ = 2 “ << endl;else
cout << n << “!= 2 “ << endl;} (n = 2) assigns the value 2 to n (n == 2) compares the values of n and 2
178110: Computer Programming (II/2546) 19
Different Kinds of Errors Compile-time error: syntax error, e.g.,
forgetting a semicolon at the end of the statement Caught by a compiler
Run-time error: error occurs when running the program, e.g., diving a number by zero Caught by an operating system
Logical error: error in which the program does not work as the programmer wishes, e.g., typing ‘=‘ instead of ‘==‘ when comparing two numbers Cannot be caught by anything
178110: Computer Programming (II/2546) 20
The Minimum of Three Integers
#include <iostream>Using namespace std;int main(){ // finds the minimum of three input integers:
int n1, n2, n3;cout << “Enter three integers:”;cin >> n1 >> n2 >> n3;int min=n1; // now min = n1if (n2 < min)
min = n2; // now min <= n1 and min = n2if (n3 < min)
min = n3; // now min <= n1, min <= n2, and min = n3cout << “Their minimum is “ << min << endl;return 0;
}
178110: Computer Programming (II/2546) 21
The Minimum of Three Integers (Cont.)
int min=n1; // now min = n1if (n2 < min)
min = n2; // now min <= n1 and min = n2if (n3 < min)
min = n3; // now min <= n1, min <= n2, and // min = n3
After the first if statement executes, min is the minimum of the set {n1, n2}
After the last if statement executes, min is the minimum of the set {n1, n2, n3}
178110: Computer Programming (II/2546) 22
Statement Blocks A statement block is a sequence of
statements enclosed by { } A statement block can be used anywhere
that a single statement can be used Example:{
int temp = x;x = y;y = temp;
}
178110: Computer Programming (II/2546) 23
Example: Statement Blocks
#include <iostream>using namespace std;int main(){
int x, y;cout << "Enter two integers: ";cin >> x >> y;if (x > y){
int temp=x; x = y;y = temp;
} // swap x and ycout << x << " <= " << y << endl;return 0;
}
178110: Computer Programming (II/2546) 24
Example: Statement Blocks (Cont.)
if (x > y) { int temp=x; x = y; y = temp; } // swap x and
y The three statements are within the same
statement block Temp is declared inside the block. That
makes it local to the block, i.e. it only exists during the execution of the block
If the condition is false, then does temp exist?
No
178110: Computer Programming (II/2546) 25
Using Blocks to Limit Scope
1. int n = 44;2. cout << “n = “ << n << endl;3. {4. int n = 2; cout << “n = “ << n << endl;5. }6. {7. cout << “ n = “ << n << endl;8. }9. {10. int n; cout << “n = “ << n << endl;11. }12. cout << “n = “ << n << endl; What are the values of n at line 2, line 4, line 7, line
10, and line 12?
178110: Computer Programming (II/2546) 26
Compound Conditions Conditions such as (n % d) and (x >=
y) can be combined to form compound conditions
This is done using the logical operators && (and) || (or) ! (not)
178110: Computer Programming (II/2546) 27
Compound Conditions (Cont.)
p && q evaluates to true If and only if both p and q are evaluated
to true p || q evaluates to true
If and only if either p or q is true !p evaluates to true
If and only if p evaluates to false (2 < 0) || (3 > 2) evaluates to?
true
178110: Computer Programming (II/2546) 28
Three Logic Operators
p q p && q
p || q
F F F F
F T F T
T F F T
T T T T
Let T stands for True and F stands for False
p !p
F T
T F
178110: Computer Programming (II/2546) 29
Using Compound Conditions
int main(){
int n1 = 1, n2 = 2, n3 = 3;if (n1 <= n2 && n1 <= n3)
cout << “n1 is less than n2 and n3”;if (n1 <= n2 || n2 <= n3)
cout << “n1 is not the greatest number”;if (!(n1 – 1))
cout << “n1 is ” << n1;
178110: Computer Programming (II/2546) 30
Short-Circuiting Compound conditions that use && and ||
will not even evaluate the second operand of the condition unless necessary.
Short-circuiting: can evaluate the condition without evaluating every terms
For p && q, what is the value of p that makes us not need to evaluate q? p is false
178110: Computer Programming (II/2546) 31
Short-Circuiting (Cont.) For p || q, what is the value of p that
makes us not need to evaluate q? p is true
How do we use the short-circuiting to solve the problem of dividing a number by zero? How do we prevent the program not to
evaluate n%d when d = 0?
178110: Computer Programming (II/2546) 32
Short-Circuit (Cont.)int main(){
int n, d;cout << “Enter two positive integers: “;cin >> n >> d;if ((d != 0) && (n%d == 0))
cout << “n is divisible by d” << endl;else
cout << “n is not divisible by d” << endl;return 0;
} When d is zero the expression, n%d will not be
evaluated
178110: Computer Programming (II/2546) 33
Boolean Expressions A boolean expression is a condition
that is either true or false Boolean expressions evaluate to
integer values The value 0 means “false” and every
nonzero value means “true” Since all nonzero integer values are
interpreted as meaning “true”, boolean expressions are often disguised
178110: Computer Programming (II/2546) 34
Boolean Expressions (Cont.)
For example, the statementif (n)
cout << “n is not zero”;will print “n is not zero” precisely when
n is not zero because this is when the boolean expression (n) is interpreted as “true”
Since boolean expressions have integer values, it can lead to some surprising anomalies in C++
178110: Computer Programming (II/2546) 35
Another Logical Errorint main(){
int n1, n2, n3;cout < “Enter three integers: “;cin >> n1 >> n2 >> n3;if (n1 >= n2 >= n3)
cout << “max = ” << n1;} What is the output when n1 = 0, n2 = 0, n3
=1? max = 0
178110: Computer Programming (II/2546) 36
The Source of the Logical Error
1. n1 = 0, n2 = 0, n3 = 12. if (n1 >= n2 >= n3)3. cout << “max = “ << n1; The source of this error is the fact that
boolean expressions have numeric values The expression (n1 >= n2 >= n3) is
evaluated from left to right The first part n1 >= n2 evaluates to true since
0 >= 0
178110: Computer Programming (II/2546) 37
Source of Logical Error (Cont.)
The expression (n1 >= n2 >= n3) is evaluated from left to right (n1 >= n2) “true” “true” is stored as the numeric value 1 This value is then compared to the value
of n3 which is also 1 (1 >= n3) (1 >= 1) true
The complete expression evaluates to “true” even though it is really false!
178110: Computer Programming (II/2546) 38
Nested Selection Statements
Selection statements can be used wherever any other statement can be used
Thus, a selection statement can be used within another selection statement
This is called nesting statements
178110: Computer Programming (II/2546) 39
Nesting Selection (Cont.)if (d != 0)
if (n%d == 0)cout << n << “ is divisible by “
<< d;else
cout << n << “ is not divisible by “ << d;
elsecout << “d is zero”;
178110: Computer Programming (II/2546) 40
Coding Style Code fragment 1
if (a > 0) if (b > 0) ++a; else c--; Code fragment 2
if (a > 0){
if (b > 0)++a;
elsec--;
} Which one is better? Which one is more
readable?
178110: Computer Programming (II/2546) 41
Using Nesting Selection How do we find the minimum of (n1, n2,
n3) by using “if … else” statements?if (n1 < n2)
if (n1 < n3)cout << “Their minimum is “ << n1;
elsecout << “Their minimum is “ << n3;
elseif (n2 < n3)
cout << “Their minimum is “ << n2;else
cout << “Their minimum is “ << n3;
178110: Computer Programming (II/2546) 42
Multiple Conditionsif (score >= 90)
cout << “Your grade is A” << endl;else
if (score >= 80)cout << “Your grade is B” << endl;
else if (score >= 70)
cout << “Your grade is C” << endl;
elsecout << “Your grade is D” <<
endl;
178110: Computer Programming (II/2546) 43
The else if Construct It is better to use “else if” to test a
sequence of parallel alternativesif (score >= 90)
cout << “Your grade is A” << endl;else if (score >= 80)
cout << “Your grade is B” << endl;else if (score >= 70)
cout << “Your grade is C” << endl;else
cout << “Your grade is D” << endl;
178110: Computer Programming (II/2546) 44
The switch Statement The switch statement can be used instead of the
else if construct to implement a sequence of parallel alternatives
Its syntax isswitch (expression){
case constant1:statement1;
case constant2:statement2;
…default: statement0;
}
178110: Computer Programming (II/2546) 45
The Switch Statement (Cont.)
This evaluates the expression Then looks for its value among the case
constants If the value is found among the constants
listed Then the statements in the corresponding
statementList are executed If there is a default (which is optional),
then the program branches to its statementList
178110: Computer Programming (II/2546) 46
Example1: Switch Statement
switch (score){
case 5: cout << “your score is 5” << endl; break;
case 4: cout << “your score is 4” << endl; break;
case 3:case 2:case 1:
cout << “you need to improve!” << endl; break;default:
cout << “Error: score is out of range” << endl;}
178110: Computer Programming (II/2546) 47
Example 2: Switch Statement
switch (score){
case 5: cout << “your score is 5” << endl; break;
case 4: cout << “your score is 4” << endl; break;
case 3:case 2:case 1:
cout << “you need to improve!” << endl; break;
} What is an output when score = 0?
178110: Computer Programming (II/2546) 48
Example 3: Switch Statement
switch (score){
case 5: cout << “your score is 5” << endl;
case 4: cout << “your score is 4” << endl;
case 3:case 2:case 1:
cout << “you need to improve!” << endl; } What happen when score = 5, score = 4, score =
1?
178110: Computer Programming (II/2546) 49
Conditional Expression Operator
C++ provides a special operator that often can be used in place of the “if…else” statement
It is called the conditional expression operator
It uses the ? and the : symbols in this syntax:condition ? expression1: expression2
178110: Computer Programming (II/2546) 50
Conditional Expression Operator (Cont.)
It is a ternary operator; i.e., it combines three operands to produce a value
That resulting value is either the value of expression1 or the value of expression2, depending upon the boolean value of the condition
For example, the assignment min = (x < y ? x : y);assign the minimum of x and y to min
178110: Computer Programming (II/2546) 51
Conditional Expression Operator (Cont.)
If the condition x<y is true The expression (x<y? x: y) evaluates
to x Otherwise, it evaluates to y
Conditional expression statements should be used sparingly Only when the condition and both
expressions are very simple
178110: Computer Programming (II/2546) 52
Example: Finding the Minimum
int main(){
int m, n;cout << “Enter two integers:”;cin >> m >> n;cout << (m<n? m: n)
<< “ is the minimum “ << endl;} (m<n ? m : n) evaluates to m if
m < n