Chapter 3 Part 1

Download Report

Transcript Chapter 3 Part 1

Chapter 3 Selections
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 10136097200
Motivations
If you assigned a negative value for radius in
Listing 2.1, ComputeArea.cpp, the program would
print an invalid result. If the radius is negative, you
don't want the program to compute the area. How
can you deal with this situation?
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
2
Objectives
To
declare bool type and write Boolean expressions using comparison operators (§3.2).
To implement selection control using one-way if statements (§3.3)
To program the GuessBirthDate game using one-way if statements (§3.4).
To implement selection control using two-way if statements (§3.5).
To implement selection control using nested if statements (§3.6).
To avoid common errors in if statements (§3.7).
To program using selection statements for a variety of examples (BMI, ComputeTax,
SubtractionQuiz) (§§3.8-3.10).
To generate random numbers using the rand function and set a seed using the srand
function (§3.10).
To combine conditions using logical operators (&&, ||, and !) (§3.11).
To program using selection statements with combined conditions (LeapYear, Lottery)
(§§3.12-3.13).
To implement selection control using switch statements (§3.14).
To write expressions using the conditional operator (§3.15).
To format output using the stream manipulators (§3.16).
To examine the rules governing operator precedence and operator associativity (§3.17).
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 30136097200
The bool Type and Operators
Often in a program you need to compare two
values, such as whether i is greater than j. C++
provides six relational operators (also known as
comparison operators) in Table 3.1 that can be
used to compare two values.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
4
Comparison Operators
Operator
Name
Example
Result
<
less than
1 < 2
true
<=
less than or equal to
1 <= 2
true
>
greater than
1 > 2
false
>=
greater than or equal to
1 >= 2
false
==
equal to
1 == 2
false
!=
not equal to
1 != 2
true
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
5
One-way if Statements
if (booleanExpression)
{
statement(s);
}
Boolean
Expression
if (radius >= 0)
{
area = radius * radius * PI;
cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
}
false
false
(radius >= 0)
true
true
Statement(s)
(a)
area = radius * radius * PI;
cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
(b)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
6
Note
Outer parentheses required
if ((i > 0) && (i < 10))
{
cout << "i is an " <<
"integer between 0 and 10";
}
(a)
Braces can be omitted if the block contains a single
statement
Equivalent
if ((i > 0) && (i < 10))
cout << "i is an " <<
"integer between 0 and 10";
(b)
The braces can be omitted if they enclose a single statement.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
7
Examples
Write a program that checks whether a number is even or odd. The program
prompts the user to enter an integer and displays “number is even” if it is
even and “number is odd” if it is odd.
#include <iostream>
using namespace std;
int main() {
// Prompt the user to enter an integer
int number;
cout << "Enter an integer: ";
cin >> number;
TestBoolean.cpp
if (number % 2 == 0)
cout << number << " is even.";
if (number % 2 != 0)
cout << number << " is odd.";
system("PAUSE");
return 0; }
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
8
Caution
Adding a semicolon at the end of an if clause is a
common mistake.
Empty Body
Logic Error
if (radius >= 0);
{
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
}
(a)
Equivalent
if (radius >= 0) { };
{
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
}
(b)
This mistake is hard to find, because it is not a
compilation error or a runtime error, it is a logic error.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
9
Examples
GuessBirthDate
This section uses the if statements to write an interesting game
program. The program can find your birth date. The program
prompts you to answer whether your birth date is in the following
five sets of numbers:
= 19
+
1 3 5 7
9 11 13 15
17 19 21 23
25 27 29 31
Set1
2
10
18
26
3
11
19
27
6
14
22
30
Set2
7
15
23
31
4 5 6 7
12 13 14 15
20 21 22 23
28 29 30 31
8 9 10 11
12 13 14 15
24 25 26 27
28 29 30 31
Set3
Set4
16
20
24
28
17
21
25
29
18
22
26
30
19
23
27
31
Set5
Your birth date is the sum of the first numbers in the sets where
your birth date appears.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
10
GuessBirthDate
Examples
#include <iostream>
using namespace std;
int main() {
int date = 0; // Date to be determined
char answer;
// Prompt the user for Set1
cout << "Is your birth date in Set1?" << endl;
cout << "16 17 18 19\n" <<
"20 21 22 23\n" <<
"24 25 26 27\n" <<
"28 29 30 31" << endl;
cout << "Enter N for No and Y for Yes: ";
cin >> answer;
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
11
GuessBirthDate
Examples
if (answer == 'Y')
date += 16;
// Prompt the user for Set2
cout << "\nIs your birth date in Set2?" << endl;
cout << " 8 9 10 11\n" <<
"12 13 14 15\n" <<
"24 25 26 27\n" <<
"28 29 30 31" << endl;
cout << "Enter N for No and Y for Yes: ";
cin >> answer;
if (answer == 'Y')
date += 8;
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
12
GuessBirthDate
Examples
// Prompt the user for Set3
cout << "\nIs your birth date in Set3?" << endl;
cout << " 1 3 5 7\n" <<
" 9 11 13 15\n" <<
"17 19 21 23\n" <<
"25 27 29 31" << endl;
cout << "Enter N for No and Y for Yes: ";
cin >> answer;
if (answer == 'Y')
date += 1;
// Prompt the user for Set4
cout << "\nIs your birth date in Set4?" << endl;
cout << " 2 3 6 7\n" <<
"10 11 14 15\n" <<
"18 19 22 23\n" <<
"26 27
30 31" << endl;
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
13
GuessBirthDate
Examples
cout << "Enter N for No and Y for Yes: ";
cin >> answer;
if (answer == 'Y')
date += 2;
// Prompt the user for Set5
cout << "\nIs your birth date in Set5?" << endl;
cout << " 4 5 6 7\n" <<
"12 13 14 15\n" <<
"20 21 22 23\n" <<
"28 29 30 31" << endl;
cout << "Enter N for No and Y for Yes: ";
cin >> answer;
if (answer == 'Y')
date += 4;
cout << "Your birth date is " << date << endl;
return 0; }
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
14
Logical Operators
Sometimes, the execution path is determined by a combination
of several conditions. You can use logical operators to combine
these conditions.
Operator
Name
Description
!
not
logical negation
&&
and
logical conjunction
||
or
logical disjunction
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
15
Truth Table for Operator !
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
16
Truth Table for Operator &&
p1
p2
p1 && p2
Example (assume age = 24, gender = 'F')
false
false
false
false
true
false
(age > 18) && (gender == 'F') is true, because (age
> 18) and (gender == 'F') are both true.
true
false
false
true
true
true
(age > 18) && (gender != 'F') is false, because
(gender != 'F') is false.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
17
Truth Table for Operator ||
p1
p2
p1 || p2
Example (assume age = 24, gender = 'F')
false
false
false
false
true
true
(age > 34) || (gender == 'F') is true, because (gender
== 'F') is true.
true
false
true
true
true
true
(age > 34) || (gender == 'M') is false, because (age >
34) and (gender == 'M') are both false.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
18
Example: Write a program that checks whether a number is
divisible by 2 and 3, whether a number is divisible by 2 or 3, and
whether a number is divisible by 2 or 3 but not both:
#include <iostream>
using namespace std;
int main(){
int number;
cout << "Enter an integer: ";
cin >> number;
TestBooleanOperators.cpp
if (number % 2 == 0 && number % 3 == 0)
cout << number << " is divisible by 2 and 3." << endl;
if (number % 2 == 0 || number % 3 == 0)
cout << number << " is divisible by 2 or 3." << endl;
if ((number % 2 == 0 || number % 3 == 0) &&
!(number % 2 == 0 && number % 3 == 0))
cout << number << " divisible by 2 or 3, but not both." << endl;
system("PAUSE");
with C++, Second Edition, (c) 2010 Pearson Education, Inc.
return(0); }Liang, Introduction to Programming
All rights reserved. 0136097200
19
The if...else Statement
if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}
true
Statement(s) for the true case
Boolean
Expression
false
Statement(s) for the false case
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
20
The if...else Statement
if (radius>=0)
{
area=radius * radius * PI;
cout<<“The area of the circle is:”<<area;
}
else
{
cout<<“Negative radius”;
}
if (number%2==0)
cout<<number<<“is even”;
else
cout<<number<<“is odd”;
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
21
Examples
Write a program that lets the user enter a year and checks whether it
is a leap year.
A year is a leap year if it is divisible by 4 but not by 100 or if it is
divisible by 400. So you can use the following Boolean expression
to check whether a year is a leap year:
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc.
All rights reserved. 0136097200
22
LeapYear.cpp
#include <iostream>
using namespace std;
int main(){
cout << "Enter a year: ";
int year;
cin >> year;
// Check if the year is a leap year
bool isLeapYear =
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// Display the result in a message dialog box
if (isLeapYear)
cout << year << " is a leap year.";
else
cout << year << " is a not leap year.";
system("PAUSE");
with C++, Second Edition, (c) 2010 Pearson Education, Inc.
return 0; } Liang, Introduction to Programming
All rights reserved. 0136097200
23