Transcript Chapter 4. Making Decisions

Chapter 4.
Making Decisions
1
Starting Out with C++, 3rd Edition
4.1 Relational Operators
• Relational operators allow you to compare
numeric values and determine if one is
greater than, less than, equal to, or not equal
to another.
2
Starting Out with C++, 3rd Edition
Table 4-1
R elational O perators
(in O rder of Precedence)
M eaning
>
<
>=
<=
==
!=
G reater than
L ess than
G reater than or equal
to
L ess than or equal to
E qual to
N ot equal to
3
Starting Out with C++, 3rd Edition
Table 4-2
E x p ressio n
W h a t th e E x p ression M ea n s
X
X
X
X
X
X
Is
Is
Is
Is
Is
Is
>Y
<Y
>= Y
<= Y
== Y
!= Y
X
X
X
X
X
X
g reater than Y ?
less th an Y ?
g reater than o r eq ual to Y ?
less th an or equ al to Y ?
equ al to Y ?
n o t eq ual to Y ?
4
Starting Out with C++, 3rd Edition
The Value of a Relationship
• Relational expressions are also know as a Boolean
expression
• Warning! The equality operator is two equal signs
together
==
5
Starting Out with C++, 3rd Edition
Table 4-3
E x p ressio n
V a lu e
X<Y
F alse, b ecau se X is n o t less th an Y .
X>Y
T ru e, b ecau se X is g reater th an Y .
X >= Y
T ru e, b ecau se X is g reater th an o r eq u al to Y .
X <= Y
F alse, b ecau se X is n o t less th an o r eq u al to Y .
Y != X
T ru e, b ecau se Y is n o t eq u al to X .
6
Starting Out with C++, 3rd Edition
Program 4-1
// This program displays the values of true and false
// states.
#include <iostream.h>
void main(void)
{
int trueValue, falseValue, x = 5, y = 10;
trueValue = X < Y;
falseValue = Y == X;
cout << "True is " << trueValue << endl;
cout << "False is " << falseValue << endl;
}
Program Output
True is 1
False is 0
7
Starting Out with C++, 3rd Edition
Table 4-4 (Assume x is 10, y is 7, a and b are ints)
S tatem en t
O u tcom e
Z=X<Y
Z is assigned 0 because X is n ot less than Y .
cout < < (X > Y );
D isplays 1 because X is greater than Y .
A = X >= Y;
A is assigned 1 because X is greater th an or
equal to Y .
cout < < (X < =
Y );
D isplays 0 because X is not less than or
equal to Y .
B = Y != X ;
B is assigned 1 because Y is n ot equ al to X .
8
Starting Out with C++, 3rd Edition
4.2 The if Statement
• The if statement can cause other statements
to execute only under certain conditions.
9
Starting Out with C++, 3rd Edition
Program 4-2
// This program averages 3 test scores
#include <iostream.h>
void main(void)
{
int score1, score2, score3;
float average;
cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout.precision(1);
cout.setf(ios::showpoint | ios::fixed);
cout << "Your average is " << average << endl;
if (average > 95)
cout << "Congratulations! That's a high score!\n";
}
10
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter 3 test scores and I will average them: 80 90 70 [Enter]
Program Output with Other Example Input
Enter 3 test scores and I will average them: 100 100 100 [Enter]
Congratulations! That's a high score!
11
Starting Out with C++, 3rd Edition
Table 4-5
S ta te m e n ts
O u tc o m e
if (H o u rs > 4 0 )
O v erT im e = 1 ;
A ssig n s 1 to O v erT im e o n ly
w h e n H o u rs is g re a te r th a n
40
if (V alu e > 3 2 )
co u t < < "In v alid n u m b er\n ";
D isp la y s th e m e ssa g e
“ In v a lid n u m b e r ” o n ly w h e n
V alu e is g re a te r th a n 3 2
if (O v erT im e = = 1 )
P ay R ate * = 2 ;
M u ltip lie s P ay R ate b y 2 o n ly
w h e n O v erT im e is e q u a l to 1
12
Starting Out with C++, 3rd Edition
Be Careful With Semicolons
if (expression)
statement;
• Notice that the semicolon comes after the
statement that gets executed if the
expression is true; the semicolon does NOT
13
Starting Out with C++, 3rd Edition
Program 4-3
// This program demonstrates how a misplaced semicolon
// prematurely terminates an if statement.
#include <iostream.h>
void main(void)
{
int x = 0, y = 10;
cout << “x is " << x << " and y is " << y << endl;
if (x > y); // misplaced semicolon!
cout << “x is greater than y\n"; // Always executed
}
Program Output
X is 0 and Y is 10
X is greater than Y
14
Starting Out with C++, 3rd Edition
Programming Style and the if Statement
• The conditionally executed statement
should appear on the line after the if
statement.
• The conditionally executed statement
should be indented one “level” from the if
statement.
• Note: Each time you press the tab key, you
are indenting one level.
15
Starting Out with C++, 3rd Edition
Comparing Floating Point Numbers
• Round-off errors can cause problems when
comparing floating point numbers with the
equality operator (==)
16
Starting Out with C++, 3rd Edition
Program 4-4
// This program demonstrates how floating point round-off
// errors can make equality comparisons unreliable.
#include <iostream.h>
void main(void)
{
float result;
result = 6.0 * 0.666666;
if (result == 4.0)
cout << "It's true!";
else
cout << "It's false!";
// Round-off error
}
Program Output
It's false!
17
Starting Out with C++, 3rd Edition
And Now Back to Truth
• When a relational expression is true, it has the
value 1.
• When a relational expression is false it has the
value 0.
• An expression that has the value 0 is considered
false by the if statement.
• An expression that has any value other than 0 is
considered true by the if statement.
18
Starting Out with C++, 3rd Edition
Not All Operators Are “Equal”
• Consider the following statement:
if (x = 2)
// caution here!
cout << “It is True!”;
• This statement does not determine if x is equal to
2, it assigns x the value 2, therefore, this
expression will always be true because the value
of the expression is 2, a non-zero value
19
Starting Out with C++, 3rd Edition
Program 4-5
// This program averages 3 test scores. The if statement uses
// the = operator, but the == operator was intended.
#include <iostream.h>
void main(void)
{
int score1, score2, score3;
float average;
cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout.precision(1);
cout.setf(ios::showpoint | ios::fixed);
cout << "Your average is " << average << endl;
if (average = 100) // Wrong
cout << "Congratulations! That's a high score!\n";
}
20
Starting Out with C++, 3rd Edition
Program 4-5 Output With Example Input
Program Output with Example Input
Enter your 3 test scores and I will average them: 80 90 70[Enter]
Congratulations! That’s a perfect score!
21
Starting Out with C++, 3rd Edition
4.3 Flags
• A flag is a variable, usually a boolean or an
integer, that signals when a condition exists.
• If your compiler does not support the bool data
22
Starting Out with C++, 3rd Edition
Program 4-6
// This program averages 3 test scores. It uses the variable highScore as a flag.
#include <iostream.h>
void main(void)
{
int score1, score2, score3;
float average;
bool highScore = false;
cout << "Enter your 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
if (average > 95)
highScore = true; // Set the flag variable
cout.precision(1);
cout.setf(ios::showpoint | ios::fixed);
cout << "Your average is " << average << endl;
if (highScore)
cout << "Congratulations! That's a high score!\n";\
}
Program Output with Example Input
Enter your 3 test scores and I will average them: 100 100 100 [Enter]
Congratulations! That's a high score!
23
Starting Out with C++, 3rd Edition
4.4 Expanding the if Statement
• The if statement can conditionally
execute a block of statement enclosed in
braces.
if (expression)
{
statement;
statement;
// Place as many statements here as necessary.
}
24
Starting Out with C++, 3rd Edition
Program 4-7
// This program averages 3 test scores.
// It uses the variable highScore as a flag.
#include <iostream.h>
void main(void)
{
int score1, score2, score3;
float average;
bool highScore = false;
cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
if (average > 95)
highScore = true;
// Set the flag variable
Program continues on next slide…
25
Starting Out with C++, 3rd Edition
Program continued from previous slide
cout.precision(1);
cout.setf(ios::showpoint | ios::fixed);
cout << "Your average is " << average << endl;
if (highScore)
{
cout << "Congratulations!\n";
cout << "That's a high score.\n";
cout << "You deserve a pat on the back!\n";
}
}
26
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter your 3 test scores and I will average them: 100 100 100
[Enter]
Congratulations!
That's a high score.
You deserve a pat on the back!
Program Output with Different Example Input
Enter your 3 test scores and I will average them: 80 90 70
[Enter]
27
Starting Out with C++, 3rd Edition
Don’t Forget the Braces!
• If you intend to execute a block of
statements with an if statement, don’t forget
the braces.
• Without the braces, the if statement only
executes the very next statement.
28
Starting Out with C++, 3rd Edition
Program 4-8
// This program averages 3 test scores.
// It uses the variable highScore as a flag.
#include <iostream.h>
void main(void)
{
int score1, score2, score3;
float average;
bool highScore = false;
cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
if (average > 95)
highScore = true;
// Set the flag variable
Program continues on next slide…
29
Starting Out with C++, 3rd Edition
Program continued from previous slide
cout.precision(1);
cout.setf(ios::showpoint | ios::fixed);
cout << "Your average is " << average << endl;
// The following if statement is
// missing its braces!
if (highScore)
cout << "Congratulations!\n";
cout << "That's a high score.\n";
cout << "You deserve a pat on the back!\n";
}
30
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter your 3 test scores and I will average them: 100 100 100[Enter]
Congratulations!
That’s a high score.
You deserve a pat on the back!
Program Output with Different Example Input
Enter your 3 test scores and I will average them: 80 90 70[Enter]
Congratulations!
That’s a high score.
You deserve a pat on the back!
31
Starting Out with C++, 3rd Edition
4.5 The if/else Statement
• The if/else statement will execute one group of
statements if the expression is true, or another
group of statements if the expression is false.
if (expression)
statement or block of statements;
else
statement or block of statements;
32
Starting Out with C++, 3rd Edition
Program 4-9
// This program uses the modulus operator to determine
// if a number is odd or even. If the number is evenly divided
// by 2, it is an even number. A remainder indicates it is odd.
#include <iostream.h>
void main(void)
{
int number;
cout << "Enter an integer and I will tell you if it\n";
cout << "is odd or even. ";
cin >> number;
if (number % 2 == 0)
cout << number << " is even.\n";
else
cout << number << " is odd.\n";
}
33
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter an integer and I will tell you if it
is odd or even. 17 [Enter]
17 is odd.
34
Starting Out with C++, 3rd Edition
Program 4-10
// This program asks the user for two numbers, num1 and num2.
// num1 is divided by num2 and the result is displayed.
// Before the division operation, however, num2 is tested
// for the value 0. If it contains 0, the division does not
// take place.
#include <iostream.h>
void main(void)
{
float num1, num2, quotient;
cout << "Enter a number: ";
cin >> num1;
cout << "Enter another number: ";
cin >> num2;
Program continues on next slide…
35
Starting Out with C++, 3rd Edition
Program continued from previous slide.
if (num2 == 0)
{
cout << "Division by zero is not possible.\n";
cout << "Please run the program again and enter\n";
cout << "a number besides zero.\n";
}
else
{
quotient = num1 / num2;
cout << "The quotient of " << num1 << " divided by ";
cout
<< num2 << " is " << quotient << ".\n";
}
}
36
Starting Out with C++, 3rd Edition
Program Output
(When the user enters 0 for num2)
Enter a number: 10 [Enter]
Enter another number: 0 [Enter]
Division by zero is not possible.
Please run the program again and enter
a number besides zero.
37
Starting Out with C++, 3rd Edition
4.6 The if/else if Construct
The if/else if statement is a chain of if statements. The perform their
tests, one after the other, until one of them is found to be true.
If (expression)
statement or block of statements;
else if (expression)
statement or block of statements;
// put as many else it’s as needed here
else if (expression)
statement or block of statements;
38
Starting Out with C++, 3rd Edition
Program 4-11
// This program uses an if/else if statement to assign a
// letter grade (A, B, C, D, or F) to a numeric test score.
#include <iostream.h>
void main(void)
{
int testScore;
cout << "Enter your numeric test score and I will\n";
cout << "tell you the letter grade you earned: ";
cin >> testScore;
Program continues on next slide…
39
Starting Out with C++, 3rd Edition
Program continued from previous slide.
if (testScore < 60)
else if (testScore < 70)
else if (testScore < 80)
else if (testScore < 90)
else if (testScore <= 100)
}
40
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter your test score and I will
tell you the letter grade you earned: 88 [Enter]
41
Starting Out with C++, 3rd Edition
Program 4-12
// This program uses independent if/else statements to assign a
// letter grade (A, B, C, D, or F) to a numeric test score.
// Do you think it will work?
#include <iostream.h>
void main(void)
{
int testScore;
cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;
Program continues on next slide…
42
Starting Out with C++, 3rd Edition
Program continued from previous slide.
if (testScore < 60)
if (testScore < 70)
if (testScore < 80)
if (testScore < 90)
if (testScore <= 100)
}
43
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter your test score and I will tell you
the letter grade you earned: 40 [Enter]
44
Starting Out with C++, 3rd Edition
Program 4-13
//This program uses an if/else if statement to
//assign a letter grade ( A, B, C, D, or F )
//to a numeric test score.
#include<iostream.h>
void main(void)
{
int testScore;
cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;
if (testScore < 60)
{
cout << "instructor.\n";
}
else if (testScore < 70)
{
cout << "This is below average. You should get ";
cout << "tutoring.\n";
}
Program continues on next slide…
45
Starting Out with C++, 3rd Edition
Program continued from previous slide.
else if (testScore < 80)
{
cout << "This is average.\n";
}
else if(testScore < 90)
{
cout << "This is an above average grade.\n";
}
else if (testScore <= 100)
{
cout << "This is a superior grade. Good work!\n";
}
}
46
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter your test score and I will tell you
the letter grade you earned: 94 [Enter]
This is a superior grade. Good work!
47
Starting Out with C++, 3rd Edition
4.7 Using a Trailing else
• A trailing else, placed at the end of an
if/else if statement, provides default action
when none of the if’s have true expressions
48
Starting Out with C++, 3rd Edition
Program 4-14
// This program uses an if/else if statement to assign a
// letter grade (A, B, C, D, or F) to a numeric test score.
// A trailing else has been added to catch test scores > 100.
#include <iostream.h>
void main(void)
{
int testScore;
cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;
Program continues on next slide…
49
Starting Out with C++, 3rd Edition
Program continued from previous slide.
if (testScore < 60)
{
cout << "instructor.\n";
}
else if (testScore < 70)
{
cout << "This is below average. You should get ";
cout << "tutoring.\n";
}
50
Starting Out with C++, 3rd Edition
Program continued from previous slide.
else if (testScore < 80)
{
cout << "This is average.\n";
}
else if (testScore < 90)
{
cout << "This is an above average grade.\n";
}
51
Starting Out with C++, 3rd Edition
Program continued from previous slide.
else if (testScore <= 100)
{
cout << "This is a superior grade. Good work!\n";
}
else // Default action
{
cout << testScore << " is an invalid score.\n";
cout << "Please enter scores no greater than 100.\n";
}
}
52
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter your test score and I will tell you
the letter grade you earned: 104 [Enter]
104 is an invalid score.
Please enter scores no greater than 100.
53
Starting Out with C++, 3rd Edition
4.8 Focus on Software Engineering:
• You can use the if/else if statement to create
program allows the user to determine the
course of action by selecting it from a list of
actions.
54
Starting Out with C++, 3rd Edition
Program 4-15
// This program displays a menu and asks the user to make a
// selection. An if/else if statement determines which item
// the user has chosen.
#include <iostream.h>
void main(void)
{
int choice, months;
float charges;
cout
cout
cout
cout
cout
<<
<<
<<
<<
<<
"2. Child Membership\n";
"3. Senior Citizen Membership\n";
"4. Quit the Program\n\n";
Program continues on next slide…
55
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cout << "Enter your choice: ";
cin >> choice;
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
if (choice == 1)
{
cout << "\nFor how many months? ";
cin >> months;
charges = months * 40.00;
cout << "The total charges are \$" << charges << endl;
}
56
Starting Out with C++, 3rd Edition
Program continued from previous slide.
else if (choice == 2)
{
cout << "\nFor how
cin >> months;
charges = months *
cout << "The total
}
else if (choice == 3)
{
cout << "\nFor how
cin >> months;
charges = months *
cout << "The total
}
many months? ";
20.00;
charges are \$" << charges << endl;
many months? ";
30.00;
charges are \$" << charges << endl;
57
Starting Out with C++, 3rd Edition
Program continued from previous slide.
else if (choice != 4)
{
cout << "The valid choices are 1 through 4. Run the\n";
cout << "program again and select one of those.\n";
}
}
58
Starting Out with C++, 3rd Edition
Program Output with Example Input
2. Child Membership
3. Senior Citizen Membership
4. Quit the Program
For how many months? 6 [Enter]
The total charges are \$180.00
59
Starting Out with C++, 3rd Edition
4.9 Focus on Software Engineering:
Nested if Statements
• A nested if statement is an if statement in
the conditionally-executed code of another
if statement.
60
Starting Out with C++, 3rd Edition
Program 4-16
// This program demonstrates the nested if statement.
#include <iostream.h>
void main(void)
{
cout << "Answer the following questions\n";
cout << "with either Y for Yes or ";
cout << "N for No.\n";
cout << "Are you employed? ";
cin >> employed;
cout << "Have you graduated from college ";
cout << "in the past two years? ";
Program continues on next slide…
61
Starting Out with C++, 3rd Edition
Program continued from previous slide.
if (employed == 'Y')
{
if (recentGrad == 'Y') // Nested if
{
cout << "You qualify for the special ";
cout << "interest rate.\n";
}
}
}
62
Starting Out with C++, 3rd Edition
Program Output with Example Input
with either Y for Yes or N for No.
Are you employed? Y[Enter]
Have you graduated from college in the past two
years? Y[Enter]
You qualify for the special interest rate.
63
Starting Out with C++, 3rd Edition
Program Output with Other Example Input
with either Y for Yes or N for No.
Are you employed? Y[Enter]
Have you graduated from college in the past two
years? N[Enter]
64
Starting Out with C++, 3rd Edition
4.10 Logical Operators
• Logical operators connect two or more
relational expressions into one, or reverse
the logic of an expression.
65
Starting Out with C++, 3rd Edition
Table 4-6
O p erator
M ean in g
E ffect
&&
AND
C onnects tw o expressions into one. B oth
expressions m ust be true for the overall
expression to be true.
||
OR
C onnects tw o expressions into one. O ne or
both expressions m ust be true for the overall
expression to be true. It is only necessary for
one to be true, and it does not m atter w hich.
!
NOT
T he ! operator reverses the “truth ” of an
expression. It m ak es a true expression false,
and a false expression true.
66
Starting Out with C++, 3rd Edition
Table 4-7
E xp ression 1
E xp ression 2
E xp ression 1 & &
E xp ression 2
T rue
F alse
F alse
T rue
F alse
F alse (0)
T rue
F alse
T rue
F alse (0)
F alse (0)
T rue (1)
67
Starting Out with C++, 3rd Edition
Program 4-18
// This program demonstrates the && logical operator.
#include <iostream.h>
void main(void)
{
cout << "Answer the following questions\n";
cout << "with either Y for Yes or ";
cout << "N for No.\n";
cout << "Are you employed? ";
cin >> employed;
Program continues on next slide…
68
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cout << "Have you graduated from college ";
cout << "in the past two years? ";
if (employed == 'Y‘ && recentGrad == 'Y') // && Operator
{
cout << "You qualify for the special ";
cout << "interest rate.\n";
}
else
{
cout << "You must be employed and have \n";
cout << "graduated from college in the\n";
cout << "past two years to qualify.\n";
}
}
69
Starting Out with C++, 3rd Edition
Program Output with Example Input
with either Y for Yes or
N for No.
Are you employed? Y[Enter]
Have you graduated from college in the past two
years? N[Enter]
You must be employed and have
past two years to qualify.
70
Starting Out with C++, 3rd Edition
Table 4-8
E xp ression 1
E xp ression 2
E xp ression 1 ||
E xp ression 2
T rue
F alse
T rue (1)
F alse
T rue
T rue (1)
F alse
F alse
F alse (0)
T rue
T rue
T rue (1)
71
Starting Out with C++, 3rd Edition
Program 4-19
//
//
//
//
//
This program asks the user for their annual income and
the number of years they have been employed at their current
job. The || operator is used in a if statement that
determines if the income is at least \$35,000 or their time
on the job is more than 5 years.
#include <iostream.h>
void main(void)
{
float income;
int years;
Program continues on next slide…
72
Starting Out with C++, 3rd Edition
Program continues
cout << "What is your annual income? ";
cin >> income;
cout << "How many years have you worked at "
cin >> years;
if (income >= 35000 || years > 5) // Use || logical operator
cout << "You qualify.\n";
else
{
cout << "You must earn at least \$35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
}
73
Starting Out with C++, 3rd Edition
Program Output with Example Input
What is your annual income? 40000 [Enter]
How many years have you worked at your current job? 2
[Enter]
You qualify.
Program Output with Example Input
What is your annual income? 20000 [Enter]
How many years have you worked at your current job? 7
[Enter]
You qualify.
74
Starting Out with C++, 3rd Edition
Table 4-9
E xpression
!(E xpression)
T rue
False (0)
False
T rue (1)
75
Starting Out with C++, 3rd Edition
Program 4-20
//This program asks the user for his annual income and
//the number of years he has been employed at his current job.
//The ! operator reverses the logic of the expression in the if/else statement.
#include <iostream.h>
void main(void)
{
float income;
int years;
cout << "What is your annual income? ";
cin >> income;
cout << "How many years have you worked at "
cin >> years;
if (!(income >= 35000 || years > 5)) // Uses the ! Logical operator
{
cout << "You must earn at least \$35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
else
cout << "You qualify.\n";
}
76
Starting Out with C++, 3rd Edition
Precedence of Logical Operators
!
&&
||
77
Starting Out with C++, 3rd Edition
4.11 Checking Numeric Ranges With
Logical Operators
• Logical operators are effective for
determining if a number is in or out of
a range.
78
Starting Out with C++, 3rd Edition
4.12 Focus on Software Engineering:
Validating User Input
• As long as the user of a program enters
bad input, the program will produce
bad output. Program should be written
79
Starting Out with C++, 3rd Edition
Examples of validation:
• Numbers are check to ensure they are within a
range of possible values.
• Values are check for their “reasonableness”.
• Items selected from a menu or other set of choices
are check to ensure they are available options.
• Variables are check for values that might cause
problems, such as division by zero.
80
Starting Out with C++, 3rd Edition
and Scope
• The scope of a variable is limited to the block in
which is is declared.
• Variables declared inside a set of braces have local
scope or block scope.
81
Starting Out with C++, 3rd Edition
Program 4-22A
//This program demonstrates late variable declaration
#include <iostream.h>
void main(void)
{
cout << "What is your annual income? ";
float income; // variable declaration
cin >> income;
cout << "How many years have you worked at "
int years;
// variable declaration
cin >> years;
if (income >= 35000 || years > 5)
cout << "You qualify.\n";
else
{
cout << "You must earn at least \$35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
}
82
Starting Out with C++, 3rd Edition
Program 4-22B
//This program demonstrates late variable declaration
#include <iostream.h>
void main(void)
{
cout << "What is your annual income? ";
float income; // variable declaration
cin >> income;
cout << "How many years have you worked at "
int years;
// variable declaration
cin >> years;
if (income >= 35000 || years > 5)
cout << "You qualify.\n";
else
{
cout << "You must earn at least \$35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
}
83
Starting Out with C++, 3rd Edition
Program 4-22C
//This program demonstrates late variable declaration
#include <iostream.h>
void main(void)
{
cout << "What is your annual income? ";
float income;
cin >> income;
int years;
cout << "How many years have you worked at "
cin >> years;
if (income >= 35000 || years > 5)
cout << "You qualify.\n";
else
{
cout << "You must earn at least \$35,000 or have\n";
cout << "been employed for more than 5 years.\n";
}
}
84
Starting Out with C++, 3rd Edition
Program 4-23
// This program demonstrates a variable declared in an inner block.
#include <iostream.h>
void main(void)
{
cout << "What is your annual income? ";
float income;
// variable declaration
cin >> income;
if (income >= 35000)
{
int years; // variable declaration
cout << "How many years have you worked at "
cin >> years;
if (years > 5)
cout << "You qualify.\n";
Program continues on next slide…
85
Starting Out with C++, 3rd Edition
Program continued from previous slide.
else
{
cout << "You must have been employed for\n";
cout << "more than 5 years to qualify.\n";
}
}
else
{
cout << "You must earn at least \$35,000 to\n";
cout << "qualify.\n";
}
}
86
Starting Out with C++, 3rd Edition
Variables With the Same Name
• When a block is nested inside another block, a
variable declared in the inner block may have the
same name as a variable declared in the outer
block. The variable in the inner block takes
precedence over the variable in the outer block.
87
Starting Out with C++, 3rd Edition
Program 4-24
// This program uses two variables with the name Number.
#include <iostream.h>
void main(void)
{
int number;
cout << "Enter a number greater than 0: ";
cin >> number;
if (number > 0)
{
int number;
Program continues on next slide…
88
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cout << "Now enter another number: ";
cin >> number;
cout << "The second number you entered was ";
cout << number << endl;
}
cout << "Your first number was " << number << endl;
}
89
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter a number greater than 0: 2 [Enter]
Now enter another number: 7[Enter]
The second number you entered was 7
90
Starting Out with C++, 3rd Edition
4.14 Comparing Strings
• Use the strcmp library function to
compare C-strings.
91
Starting Out with C++, 3rd Edition
Program 4-25
// This program illustrates that you cannot compare strings
// with relational operators. Although it appears to test the
// strings for equality, that is NOT what happens.
#include <iostream.h>
void main(void)
{
char firstString, secondString;
cout << "Enter a string: ";
cin.getline(firstString, 40);
cout << "Enter another string: ";
cin.getline(secondString, 40);
if (firstString == secondString)
cout << "You entered the same string twice.\n";
else
cout << "The strings are not the same.\n";
}
92
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter a string: Alfonso [Enter]
Enter another string: Alfonso [Enter]
The strings are not the same.
93
Starting Out with C++, 3rd Edition
The strcmp Function
strcmp(string1, string2);
// include cstring to use
// this function
• If the two strings are identical, strcmp returns 0.
• If string1 < string 2, strcmp returns a negative
number.
• If string1 > string 2, strcmp returns a positive
number.
94
Starting Out with C++, 3rd Edition
Program 4-26
// This program correctly tests two strings for equality, with
// the strcmp function
#include <iostream.h>
#include <string.h>
void main(void)
{
char firstString, secondString;
cout << "Enter a string: ";
cin.getline(firstString, 40);
cout << "Enter another string: ";
cin.getline(secondString, 40);
if (strcmp(firstString, secondString) == 0)
cout << "You entered the same string twice.\n";
else
cout << "The strings are not the same.\n";
}
95
Starting Out with C++, 3rd Edition
Program 4-27
// This program uses strcmp to compare the sting entered
// by the user with the valid stereo part numbers.
#include <iostream.h>
#include <string.h>
void main(void)
{
const float aprice = 249.0, Bprice = 299.0;
char partNum;
cout << "The stereo part numbers are:\n";
cout << "\tBoom Box, part number S147-29A\n";
Program continues on next slide…
96
Starting Out with C++, 3rd Edition
Program continued from previous slide
cout << "\tShelf Model, part number S147-29B\n";
cout << "Enter the part number of the stereo you\n";
cout << "wish to purchase: ";
cin.width(9);
// So they won't enter more than 8 char's
cin >> partNum;
cout.setf(ios::fixed || ios::showpoint);
cout.precision(2);
if (strcmp(partNum, "S147-29A") == 0) // use of strcmp
cout << "The price is \$" << aprice << endl;
else if (strcmp(partNum, "S147-29B") == 0)
cout << "The price is \$" << Bprice << endl;
else
cout << partNum << " is not a valid part number.\n";
}
97
Starting Out with C++, 3rd Edition
Program Output with Example Input
The stereo part numbers are:
Boom Box, part number S14729A
Shelf Model, part number S147-29B
Enter the part number of the stereo you
wish to purchase: S147-29B [Enter]
The price is \$299.00
98
Starting Out with C++, 3rd Edition
Program 4-28
// This program uses the return value of strcmp to
// alphabetically sort two strings entered by the user.
#include <iostream.h>
#include <string.h>
void main(void)
{
char name1, name2;
cout << "Enter a name (last name first): ";
cin.getline(name1, 30);
cout << "Enter another name: ";
cin.getline(name2, 30);
Program continues on next slide…
99
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cout << "Here are the names sorted alphabetically:\n";
if (strcmp(name1, name2) < 0)
cout << name1 << endl << name2 << endl;
else if (strcmp(name1, name2) > 0)
cout << name2 << endl << name1 << endl;
else
cout << "You entered the same name twice!\n";
}
100
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter a name (last name first): Smith, Richard [Enter]
Enter another name: Jones, John [Enter]
Here are the names sorted alphabetically
Jones, John
Smith, Richard
101
Starting Out with C++, 3rd Edition
Program 4-29
//This program uses strcmp to compare the string entered
//by the user with the valid stereo part numbers.
#include<iostream.h>
#include<string>
using namespace std;
void main(void)
{
const float aprice = 249.0, bprice = 299.0;
string partNum;
cout << "The stereo part numbers are:\n";
cout << "Boom box, part number S147-29A\n";
cout << "Shelf model, part number S147-29B\n";
cout << "Enter the part number of the stereo you\n";
cout << "wish to purchase: ";
cin >> partNum;
Program continues on next slide…
102
Starting Out with C++, 3rd Edition
Program continued from previous slide
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
if (partNum == "S147-29A")
cout << "The price is \$" << aprice << endl;
else if (partNum == "S147-29B")
cout << "The price is \$" << bprice << endl;
else
cout << partNum << " is not a valid part number.";
}
103
Starting Out with C++, 3rd Edition
Program Output with Example Input
The stereo part numbers are:
Boom box, part number S147-29A
Shelf model, part number S147-29B
Enter the part number of the stereo you
wish to purchase: S147-29A
The price is \$249.00
104
Starting Out with C++, 3rd Edition
4.15 The Conditional Operator
• You can use the conditional operator to
create short expressions that work like
if/else statements
expression ? result if true : result if false;
X<0
?
Y = 10
:
Z = 20;
105
Starting Out with C++, 3rd Edition
Program 4-30
// This program calculates a consultant's charges at \$50 per hour,
// for a minimum of 5 hours. The ?: operator adjusts hours to 5 if less
// than 5 hours were worked.
#include <iostream.h>
void main(void)
{
const float payRate = 50.0;
float hours, charges;
cout << "How many hours were worked? ";
cin >> hours;
hours = hours < 5 ? 5 : hours;
charges = payRate * hours;
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The charges are \$" << charges << endl;
}
106
Starting Out with C++, 3rd Edition
Program Output with Example Input
How many hours were worked? 10 [Enter]
The charges are \$500.00
Program Output with Example Input
How many hours were worked? 2 [Enter]
The charges are \$250.00
107
Starting Out with C++, 3rd Edition
Program 4-31
// This program uses the return value of strcmp to alphabetically
// sort two strings entered by the user.
#include <iostream.h>
#include <string.h>
void main(void)
{
char name1, name2;
cout << "Enter a name (last name first): ";
cin.getline(name1, 30);
Program continues on next slide…
108
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cout << "Enter another name: ";
cin.getline(name2, 30);
cout << "Here are the names sorted alphabetically:\n";
cout << (strcmp(name1, name2) <= 0 ? name1 : name2) << endl;
cout << (strcmp(name1, name2) > 0 ? name1 : name2) << endl;
}
109
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter a name (last name first): Smith, Richard [Enter]
Enter another name: Jones, John [Enter]
Here are the names sorted alphabetically
Jones, John
Smith, Richard
110
Starting Out with C++, 3rd Edition
4.16 The switch Statement
• The switch statement lets the value of a
variable or expression determine where the
program will branch to.
111
Starting Out with C++, 3rd Edition
Program 4-32
// The switch statement in this program tells the user
// something he or she already knows: what they just entered!
#include <iostream.h>
void main(void)
{
char choice;
cout << "Enter A, B, or C: ";
cin >> choice;
Program continues on next slide…
112
Starting Out with C++, 3rd Edition
Program continues
switch (choice)
{
case 'A':
case 'B':
case 'C':
default:
cout <<
break;
cout <<
break;
cout <<
break;
cout <<
"You entered A.\n";
"You entered B.\n";
"You entered C.\n";
"You did not enter A, B, or C!\n";
}
}
113
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter A, B, or C: B [Enter]
You entered B.
Program Output with Different Example Input
Enter a A, B, or C: F [Enter]
You did not enter A, B, or C!
114
Starting Out with C++, 3rd Edition
Program 4-33
// The switch statement in this program tells the user
// something he or she already knows: what they just
// entered!
#include <iostream.h>
void main(void)
{
char choice;
cout << "Enter A, B, or C: ";
cin >> choice;
Program continues on next slide…
115
Starting Out with C++, 3rd Edition
Program continued from previous slide.
switch (choice)
{
case 'A':
case 'B':
case 'C':
default:
}
cout
cout
cout
cout
<<
<<
<<
<<
"You
"You
"You
"You
entered
entered
entered
did not
A.\n";
B.\n";
C.\n";
enter A, B, or C!\n";
}
116
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter a A, B, or C: A [Enter]
You entered A.
You entered B.
You entered C.
You did not enter A, B, or C!
Program Output with Example Input
Enter a A, B, or C: C [Enter]
You entered C.
You did not enter A, B, or C!
117
Starting Out with C++, 3rd Edition
Program 4-34
// This program is carefully constructed to use the
// "fallthrough" feature of the switch statement.
#include <iostream.h>
void main(void)
{
int modelNum;
cout << "Our TVs come in three models:\n";
cout << "The 100, 200, and 300. Which do you want? ";
cin >> modelNum;
cout << "That model has the following features:\n";
Program continues on next slide…
118
Starting Out with C++, 3rd Edition
Program continues
switch (modelNum)
{
case 300: cout <<
case 200: cout <<
case 100: cout <<
break;
default: cout <<
cout <<
}
"\tPicture-in-a-picture.\n";
"\tStereo sound.\n";
"\tRemote control.\n";
"You can only choose the 100,";
"200, or 300.\n";
}
119
Starting Out with C++, 3rd Edition
Program Output with Example Input
Our TVs come in three models:
The 100, 200, and 300. Which do you want? 100 [Enter]
That model has the following features:
Remote control.
Program Output with Example Input
Our TVs come in three models:
The 100, 200, and 300. Which do you want? 200 [Enter]
That model has the following features:
Stereo sound.
Remote control.
120
Starting Out with C++, 3rd Edition
Program 4-35
// The switch statement in this program uses the "fallthrough"
// feature to catch both upper and lowercase letters entered
// by the user.
#include <iostream.h>
void main(void)
{
cout << "Our dog food is available in three grades:\n";
cout << "A, B, and C. Which do you want pricing for? ";
Program continues on next slide…
121
Starting Out with C++, 3rd Edition
Program continued from previous slide.
{
case 'a':
case 'A':
cout <<
break;
case 'b':
case 'B':
cout <<
break;
case 'c':
case 'C':
cout <<
break;
default:
cout <<
choice.\n";
}
"30 cents per pound.\n";
"20 cents per pound.\n";
"15 cents per pound.\n";
"That is an invalid
}
122
Starting Out with C++, 3rd Edition