Beruflich Dokumente
Kultur Dokumente
Making Decisions
Table 4-1
Relational Operators
(in Order of Precedence)
Meaning
>
<
>=
<=
==
!=
Greater than
Less than
Greater than or equal
to
Less than or equal to
Equal to
Not equal to
Table 4-2
Expression
X
X
X
X
X
X
Is X
Is X
Is X
Is X
Is X
Is X
> Y
< Y
>= Y
<= Y
== Y
!= Y
greater than Y ?
less than Y ?
greater than or equal to Y ?
less than or equal to Y ?
equal to Y ?
not equal to Y ?
Table 4-3
Expression
Value
X
X
X
X
Y
False, because X
True, because X
True, because X
False, because X
True, because Y
< Y
> Y
>= Y
<= Y
!= X
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
Outcome
Z = X < Y
A = X >= Y;
B = Y != X ;
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
11
Table 4-5
Statements
Outcome
if (H o u rs > 4 0 )
O v e rT im e = 1 ;
Assigns 1 to O v e r T i m e only
when H o u r s is greater than
40
Displays the message
Invalid number only when
V a l u e is greater than 32
Multiplies P a y R a t e by 2 only
when O v e r T i m e is equal to 1
if (V a lu e > 3 2 )
c o u t < < " In v a lid n u m b e r\n " ;
if (O v e rT im e = = 1 )
P a y R a te * = 2 ;
12
13
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
16
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
18
19
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
21
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
type, use int instead.
22
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";\
}
23
24
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
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
27
28
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
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
31
32
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
34
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;
35
36
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
If (expression)
statement or block of statements;
else if (expression)
statement or block of statements;
// put as many else its as needed here
else if (expression)
statement or block of statements;
38
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;
char grade;
cout << "Enter your numeric test score and I will\n";
cout << "tell you the letter grade you earned: ";
cin >> testScore;
39
40
41
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;
char grade;
cout << "Enter your test score and I will tell you\n";
cout << "the letter grade you earned: ";
cin >> testScore;
42
43
44
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;
45
46
47
48
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;
49
50
51
52
53
54
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
<<
<<
<<
<<
<<
55
56
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
}
57
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
59
60
Program 4-16
// This program demonstrates the nested if statement.
#include <iostream.h>
void main(void)
{
char employed, recentGrad;
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? ";
cin >> recentGrad;
61
if (employed == 'Y')
{
if (recentGrad == 'Y') // Nested if
{
cout << "You qualify for the special ";
cout << "interest rate.\n";
}
}
}
62
63
64
65
Table 4-6
Operator
Meaning
Effect
& &
AND
||
OR
NOT
66
Table 4-7
Expression 1
Expression 2
True
False
False
True
False
True
False
True
Expression 1 &&
Expression 2
False (0)
False (0)
False (0)
True (1)
67
Program 4-18
// This program demonstrates the && logical operator.
#include <iostream.h>
void main(void)
{
char employed, recentGrad;
cout << "Answer the following questions\n";
cout << "with either Y for Yes or ";
cout << "N for No.\n";
cout << "Are you employed? ";
cin >> employed;
68
69
Table 4-8
Expression 1
Expression 2
Expression 1 ||
Expression 2
True
False
True (1)
False
True
True (1)
False
False
False (0)
True
True
True (1)
71
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;
72
Program continues
cout << "What is your annual income? ";
cin >> income;
cout << "How many years have you worked at "
<< "your current job? ";
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
74
Table 4-9
Expression
True
False
!(Expression)
False (0)
True (1)
75
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 "
<< "your current job? ";
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
77
78
79
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
81
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 "
<< "your current job? ";
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
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 "
<< "your current job? ";
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
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 "
<< "your current job? ";
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
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 "
<< "your current job? ";
cin >> years;
if (years > 5)
cout << "You qualify.\n";
85
86
87
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
89
90
91
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[40], secondString[40];
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
93
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[40], secondString[40];
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
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[8];
cout << "The stereo part numbers are:\n";
cout << "\tBoom Box, part number S147-29A\n";
Program continues on next slide
96
97
98
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[30], name2[30];
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
100
101
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;
102
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
104
Y = 10
Z = 20;
105
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
107
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[30], name2[30];
cout << "Enter a name (last name first): ";
cin.getline(name1, 30);
108
109
110
111
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;
112
Program continues
switch (choice)
{
case 'A':
case 'B':
case 'C':
default:
cout <<
break;
cout <<
break;
cout <<
break;
cout <<
}
}
113
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
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;
115
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
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
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";
118
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
120
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)
{
char feedGrade;
cout << "Our dog food is available in three grades:\n";
cout << "A, B, and C. Which do you want pricing for? ";
cin >> feedGrade;
121
switch(feedGrade)
{
case 'a':
case 'A':
cout <<
break;
case 'b':
case 'B':
cout <<
break;
case 'c':
case 'C':
cout <<
break;
default:
cout <<
choice.\n";
}
122