SlideShare a Scribd company logo
1 of 141
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Chapter 4
Mathematical Functions, Characters, and Strings
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Motivations
Suppose you need to estimate the area enclosed by four cities,
given the GPS locations (latitude and longitude) of these cities,
as shown in the following diagram. How would you write a
program to solve this problem? You will be able to write such a
program after completing this chapter.
Orlando (28.5383355,-81.3792365)
Savannah (32.0835407,-81.0998342)
Charlotte (35.2270869,-80.8431267)
Atlanta
(33.7489954,-84.3879824)
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
ObjectivesTo solve mathematics problems by using the C++
mathematical functions (§4.2).To represent characters using the
char type (§4.3).To encode characters using ASCII code
(§4.3.1).To read a character from the keyboard (§4.3.2).To
represent special characters using the escape sequences
(§4.3.3).To cast a numeric value to a character and cast a
character to an integer (§4.3.4).To compare and test characters
(§4.3.5).To program using characters
(DisplayRandomCharacter, GuessBirthday) (§§4.4-4.5).To test
and convert characters using the C++ character functions
(§4.6).To convert a hexadecimal character to a decimal value
(HexDigit2Dec) (§4.7).To represent strings using the string type
and introduce objects and instance functions (§4.8).To use the
subscript operator for accessing and modifying characters in a
string (§4.8.1).To use the + operator to concatenate strings
(§4.8.2).To compare strings using the relational operators
(§4.8.3).To read strings from the keyboard (§4.8.4).To revise
the lottery program using strings (LotteryUsingStrings)
(§4.9).To format output using stream manipulators (§4.10).To
read and write data from/to a file (§4.11).
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Mathematical Functions
C++ provides many useful functions in the cmath header for
performing common mathematical functions.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trigonometric Functions
Function Description
sin(radians) Returns the trigonometric sine of an angle in
radians.
cos(radians) Returns the trigonometric cosine of an angle
in radians.
tan(radians) Returns the trigonometric tangent of an angle
in radians.
asin(a) Returns the angle in radians for the inverse
of sine.
acos(a) Returns the angle in radians for the inverse
of cosine.
atan(a) Returns the angle in radians for the inverse
of tangent.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Exponent Functions
x
Function Description
exp(x) Returns e raised to power of x (ex).
log(x) Returns the natural logarithm of x (ln(x) =
loge(x)).
log10(x) Returns the base 10 logarithm of x (log10(x)).
pow(a, b) Returns a raised to the power of b (ab).
sqrt(x) Returns the square root of x (�EMBED
Equation.3���) for x >= 0.
_1173422839.unknown
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Rounding Functions
Function Description
ceil(x) x is rounded up to its nearest integer. This integer is
returned
as a double value.
floor(x) x is rounded down to its nearest integer. This
integer is returned
as a double value.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
The min, max, and abs Functions
max(2, 3) returns 3 max(2.5, 3.0) returns 4.0 min(2.5, 4.6)
returns 2.5 abs(-2) returns 2abs(-2.1) returns 2.1
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Case Study: Computing Angles of a Triangle
Write a program that prompts the user to enter the x- and y-
coordinates of the three corner points in a triangle and then
displays the triangle’s angles.
ComputeAngles
Run
A
B
C
a
b
c
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
x1, y1
x2, y2
x3, y3
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Character Data Type
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
NOTE: The increment and decrement operators can also be used
on char variables to get the next or preceding character. For
example, the following statements display character b.
char ch = 'a';
cout << ++ch;
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Read Characters
To read a character from the keyboard, use
cout << "Enter a character: ";
char ch;
cin >> ch;
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Escape Sequences for Special Characters
Character Escape Sequence Name ASCII Code
b Backspace 8
t Tab 9
n Linefeed 10
f Formfeed 12
r Carriage Return 13
 Backslash 92
' Single Quote 39
" Double Quote 34
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
Lab #1
Write a program that accepts as input a character variable called
chrValue1.
If chrValue1 is ‘G’ or ‘g’ then write out to the screen “You
entered a g”, if chrValue1 is ‘T’ or ‘t’ then write out to the
screen “You entered a t”, if chrValue1 is ‘P’ or ‘p’ then write
out to the screen “You entered a p”, otherwise output “You
tricked me”.
Make sure you contain at least 3 commentsVariables are named
correctlyMake sure that you use the switch statement and do not
use any if statements.
*
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from u0000 to
u007f
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from u0000 to
u007f
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Casting between char and Numeric Types
int i = 'a';
// Same as int i = static_cast<int>('a');
char c = 97;
// Same as char c = static_cast<char>(97);
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Numeric Operators on Characters
The char type is treated as if it is an integer of the byte size. All
numeric operators can be applied to char operands. A char
operand is automatically cast into a number if the other operand
is a number or a character. For example, the following
statements
int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51
cout << "i is " << i << endl; // i is decimal 101
int j = 2 + 'a'; // (int)'a' is 97
cout << "j is " << j << endl;
cout << j << " is the ASCII code for character " <<
static_cast<char>(j) << endl;
Display
i is 101
j is 99
99 is the ASCII code for character c
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Note
It is worthwhile to note that the ASCII for lowercase letters are
consecutive integers starting from the code for 'a', then for 'b',
'c', ..., and 'z'. The same is true for the uppercase letters.
Furthermore, the ASCII code for 'a' is greater than the code for
'A'. So 'a' - 'A' is the same as 'b' - 'B'. For a lowercase letter ch,
its corresponding uppercase letter is static_cast<char>('A' + (ch
- 'a')).
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Problem: Converting a Lowercase to Uppercase
ToUppercase
Run
Write a program that prompts the user to enter a lowercase
letter and finds its corresponding uppercase letter.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Comparing and Testing Characters
Two characters can be compared using the comparison operators
just like comparing two numbers. This is done by comparing the
ASCII codes of the two characters.
'a' < 'b' is true because the ASCII code for 'a' (97) is less than
the ASCII code for 'b' (98).
'a' < 'A' is true because the ASCII code for 'a' (97) is less than
the ASCII code for 'A' (65).
'1' < '8' is true because the ASCII code for '1' (49) is less than
the ASCII code for '8' (56).
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Case Study: Generating Random Characters
Computer programs process numerical data and characters. You
have seen many examples that involve numerical data. It is also
important to understand characters and how to process them.
Every character has a unique ASCII code between 0 and 127. To
generate a random character is to generate a random integer
between 0 and 127. You learned how to generate a random
number in §3.8. Recall that you can use the srand(seed) function
to set a seed and use rand() to return a random integer. You can
use it to write a simple expression to generate random numbers
in any range. For example,
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Case Study: Generating Random Characters, cont.
DisplayRandomCharacter
rand() % 10
Returns a random integer between 0 and 9.
Returns a random integer between 50 and 99.
50 + rand() % 50
Returns a random number between a and a + b, excluding a + b.
a + rand() % b
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Case Study: Guessing Birthdays
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:
GuessBirthday
Run
16 17 18 19
20 21 22 23
24 25 26 27
28 29 30 31
Set2
Set1
8 9 10 11
12 13 14 15
24 25 26 27
28 29 30 31
Set3
1 3 5 7
9 11 13 15
17 19 21 23
25 27 29 31
Set4
2 3 6 7
10 11 14 15
18 19 22 23
26 27 30 31
Set5
4 5 6 7
12 13 14 15
20 21 22 23
28 29 30 31
+
= 19
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Character Functions
CharacterFunctions
Run
Function Description
isdigit(ch) Returns true if the specified character is a digit.
isalpha(ch) Returns true if the specified character is a letter.
isalnum(ch) Returns true if the specified character is a
letter or digit.
islower(ch) Returns true if the specified character is a
lowercase letter.
isupper(ch) Returns true if the specified character is an
uppercase letter.
isspace(ch) Returns true if the specified character is a
whitespace character.
tolower(ch) Returns the lowercase of the specified
character.
toupper(ch) Returns the uppercase of the specified
character.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Case Study: Converting a Hexadecimal Digit to a Decimal
Value
Write a program that converts a hexadecimal digit into a
decimal value.
HexDigit2Dec
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
The string Type
string s;
string message = "Programming is fun";
Function Description
Returns the number of characters in this string.
Same as length();
Returns the character at the specified index from this string.
length()
size()
at(index)
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
String Subscript Operator
For convenience, C++ provides the subscript operator for
accessing the character at a specified index in a string using the
syntax stringName[index]. You can use this syntax to retrieve
and modify the character in a string.
13
e
Indices
m
e
o
c
l
W
12
+
+
C
o
t
11
10
9
8
7
6
5
4
3
2
1
0
message
message.at(0)
message.at(13)
message.length is 14
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
String Subscript Operator
string s = "ABCD";
s[0] = 'P';
cout << s[0] << endl;
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
Lab #2
Enter a sample string that is at least 10 characters in length, no
spaces.
Output to the screen the characters at the 1st, 3rd, 5th, 7th and
9th position in the string.
Make sure you contain at least 3 commentsVariables are named
correctly
*
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Concatenating Strings
string s3 = s1 + s2;
message += " and programming is fun";
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Comparing Strings
You can use the relational operators ==, !=, <, <=, >, >= to
compare two strings. This is done by comparing their
corresponding characters on by one from left to right. For
example,
string s1 = "ABC";
string s2 = "ABE";
cout << (s1 == s2) << endl; // Displays 0 (means false)
cout << (s1 != s2) << endl; // Displays 1 (means true)
cout << (s1 > s2) << endl; // Displays 0 (means false)
cout << (s1 >= s2) << endl; // Displays 0 (means false)
cout << (s1 < s2) << endl; // Displays 1 (means true)
cout << (s1 <= s2) << endl; // Displays 1 (means true)
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Reading Strings
1 string city;
2 cout << "Enter a city: ";
3 cin >> city; // Read to array city
4 cout << "You entered " << city << endl;
1 string city;
2 cout << "Enter a city: ";
3 getline(cin, city, 'n'); // Same as getline(cin, city)
4 cout << "You entered " << city << endl;
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Example
Write a program that prompts the user to enter two cities and
displays them in alphabetical order.
OrderTwoCities
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Case Study: Revising the Lottery Program Using Strings
A problem can be solved using many different approaches. This
section rewrites the lottery program in Listing 3.7 using strings.
Using strings simplifies this program.
LotteryUsingStrings
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Formatting Console Output
Manipulator Description
setprecision(n) sets the precision of a floating-point number
fixed displays floating-point numbers in fixed-point
notation
showpoint causes a floating-point number to be displayed
with
a decimal point and trailing zeros even if it has
no fractional part
setw(width) specifies the width of a print field
left justifies the output to the left
right justifies the output to the right
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
setprecision(n) Manipulator
double number = 12.34567;
cout << setprecision(3) << number << " "
<< setprecision(4) << number << " "
<< setprecision(5) << number << " "
<< setprecision(6) << number << endl;
displays
12.3□12.35□12.346□12.3457
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
fixed Manipulator
double monthlyPayment = 345.4567;
double totalPayment = 78676.887234;
cout << fixed << setprecision(2)
<< monthlyPayment << endl
<< totalPayment << endl;
displays
345.46
78676.89
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
showpoint Manipulator
cout << setprecision(6);
cout << 1.23 << endl;
cout << showpoint << 1.23 << endl;
cout << showpoint << 123.0 << endl;
displays
1.23
1.23000
123.000
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
setw(width) Manipulator
cout << setw(8) << "C++" << setw(6) << 101 << endl;
cout << setw(8) << "Java" << setw(6) << 101 << endl;
cout << setw(8) << "HTML" << setw(6) << 101 << endl;
displays
□□□□□C++□□□101
□□□□Java□□□101
□□□□HTML□□□101
8
6
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
left and right Manipulators
cout << right;
cout << setw(8) << 1.23 << endl;
cout << setw(8) << 351.34 << endl;
displays
□□□□1.23
□□351.34
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
left and right Manipulators
cout << left;
cout << setw(8) << 1.23;
cout << setw(8) << 351.34 << endl;
displays
1.23□□□□351.34□□
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Example: Display a Table
Degrees Radians Sine Cosine Tangent
30 0.5236 0.5000 0.8660 0.5773
60 1.0472 0.8660 0.5000 1.7320
FormatDemo
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Simple File Output
To write data to a file, first declare a variable of the ofstream
type:
ofstream output;
To specify a file, invoke the open function from output object
as follows:
output.open("numbers.txt");
Optionally, you can create a file output object and open the file
in one statement like this:
ofstream output("numbers.txt");
To write data, use the stream insertion operator (<<) in the same
way that you send data to the cout object. For example,
output << 95 << " " << 56 << " " << 34 << endl;
SimpleFileOutput
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Simple File Input
To read data from a file, first declare a variable of the ifstream
type:
ifstream input;
To specify a file, invoke the open function from input as
follows:
input.open("numbers.txt");
Optionally, you can create a file output object and open the file
in one statement like this:
ifstream input("numbers.txt");
To read data, use the stream extraction operator (>>) in the
same way that you read data from the cin object. For example,
input << score1 << score2 << score3;
SimpleFileInput
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
Lab #3
Write a program that accepts as input a string variable called
strFirstName, then another string variable called strLastName,
and then string variable called strEmail.Write out to a file each,
however make sure it looks like :First Name: DavidLast Name:
WiesnerEmail Addr: [email protected]
Make sure you contain at least 3 commentsVariables are named
correctlyProgram functions as expected
*
Orlando (28.5383355,-81.3792365)
Savannah (32.0835407,-81.0998342)
Charlotte (35.2270869,-80.8431267)
Atlanta
(33.7489954,-84.3879824)
Function Description
sin(radians) Returns the trigonometric sine of an angle in
radians.
cos(radians) Returns the trigonometric cosine of an angle
in radians .
tan(radians) Returns the trigonometric tangent of an angle
in radians .
asin(a) Returns the angle in radians for the inverse of
sine .
acos(a) Returns the angle in radians for the inverse of
cosine.
atan(a) Returns the angle in radians for the inverse of
tangent .
Function Description
exp(x) Returns e raised to power of x (e
x
).
log(x) Returns the natural logarithm of x (ln(x) = log
e
(x)).
log10(x) Returns the base 10 logarithm of x (log
10
(x)).
pow(a, b) Returns a raised to the power of b (a
b
).
sqrt(x) Returns the square root of x (
x
) for x >= 0.
Function Description
ceil(x) x is rounded up to its nearest integer. This integer is
returned
as a double value.
floor(x) x is rounded down to its nearest integer. This
integer is returned
as a double value.
A
B
C
a
b
c
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
x1, y1
x2, y2
x3, y3
Character Escape Sequence Name ASCII Code
b Backspace 8
t Tab 9
n Linefeed 10
f Formfeed 12
r Carriage Return 13
 Backslash 92
' Single Quote 39
" Double Quote 34
rand()
%
10
Returns a random integer
between 0 and 9.
50
+ rand()
%
50
Returns a random integer
between 50 and 99.
a + rand()
%
b
Returns a random number between
a and a + b, excluding a + b.
Run
16 17 18
19
20 21 22 23
24 25 26 27
28 29 30 31
Set1
8 9 10 11
12 13 14 15
24 25 26 27
28 29 30 31
Set2
1 3 5 7
9 11 13 15
17
19
21 23
25 27 29 31
Set3
2 3 6 7
10 11 14 15
18
19
22 23
26 27 30 31
Set4
4 5
6 7
12 13 14 15
20 21 22 23
28 29 30 31
Set5
+
= 19
Function Description
isdigit(ch) Returns true if the specified character is a digit.
isalpha(ch) Returns true if the specified character is a
letter.
isalnum(ch) Returns true if the specified character is a letter
or digit.
islower(ch) Returns true if the specified character is a
lowercase letter.
isupper(ch) Returns true if the specified character is an
uppercase letter.
isspace(ch) Returns true if the specified character is a
whitespace character.
tolower(ch) Returns the lowercase of the specified character
.
toupper(ch) Returns the uppercase of the specified character
.
Function Description
Returns the number of characters in this string.
Same as length();
Returns the character at the specified index from this string .
length()
size()
at(index)
Indices
W
e
l
c
o
m
e
t
o
C
+
+
0
1
2
3
4
5
6
7
8
9
10
11
12
13
message
message.at(0)
message.at(13)
message.length is 14
Manipulator
Description
setprecision(n) sets the precision of a floating
-
point number
fixed
displays
floating
-
point numbers in fixed
-
point notation
showpoint causes a floating
-
point number to
be displayed with
a decimal point
and
trailing zeros even if it has
no fractional part
setw(width) specifies the width of a print field
left justifies the output to the left
right
justifies the output to the right
□□□□□C++□□□101
□□□□Java□□□101
□□□□HTML□□□101
8
6
Running head: ANNOTATED BIBLIOGRAPHY FOR
CHILDHOOD OBESITY 1
ANNOTATED BIBLIOGRAPHY FOR CHILDHOOD OBESITY
2
THIS IS LAST WEEK PAPER WITH CORRECTION. PLEASE
NOTE FOR NEXT PAPER. THANKS.
Annotated Bibliography for Childhood ObesityJonhn King
DeVry University
ENGL 14ggggggggg7
Professor bobk king
Week Four
03/26/2015
Annotated Bibliography for Childhood Obesity
In an obesity-related report, the case of a three-year-old child
who had died from obesity complications was detailed. The
child’s Body Mass Index should have been 14.5 kg, but it was
recorded to be 38 kg. The child died from heart failure, which is
one of obesity-related complications. As shocking, as it may be,
this is not an isolated incident. All over the news, cases of
children who have died from obesity- related complications are
eminent. The common cause of obesity-related deaths has been
associated with sleep apnea, a condition where the folds of fat
block airways. According to experts, it is sad and devastating to
see children chocked by their own fat as a result of eating foods
laden with sugars and fats with little or no exercise (BBC,
2014).
Such incidences incidents highlight the severity of obesity, as
an epidemic, which is primarily caused by a fast food and
sedentary-based lifestyle that lead to severe obesity-related
health complications leading to death, thus the need for
sensitizing parents, as primary care givers, on the need to
intervene and change their children’s lifestyle to control and
prevent obesity.
Annotated Bibliography
BBC. (2014). Three-year-old dies from obesity. Retrieved from
http://news.bbc.co.uk/2/hi/health/3752597.stm
This news-based article explores the incidence of a three-year-
old baby who died from heart failure, as a complication for of
obesity. Taking the obesity case further, the article explores
increased incidences of children’s deaths resulting from other
obesity- relation related complications, such as sleep apnea. The
News news article is credible and reliable because the
information put in the article is derived from experts and
credible sources, such as Health Select Committee Report that
was written comprise of by doctors from Birmingham Children's
Hospital. The article is timely because it is up- to- date in the
sense that it comprises information relating to the current state
of obesity epidemic.
My assessment: The article is of crucial importance in the paper
because it provides the anecdote that will make the readers
interested and glued to the papers. In addition, the obesity-
related deaths reported in the paper provide insight on the
severity of obesity epidemic, thus evoking in readers the need to
act on it.
Food Research and Action Center. (2014).Factors contributing
to overweight and obesity. Retrieved from
http://frac.org/initiatives/hunger-and-obesity/what-factors-
contribute-to-overweight-and-obesity/
This article discusses factors that lead to increased caloric
intake, thus contributing to obesity. These factors include fast
foods, such as increased intake of beverages that are sweetened,
snacking, taking huge portion sizes, eating less nutritious foods
and advertising of fast foods. In reference to inadequate
physical activities are increased use of media, such as video
games and television and lack of physical activities at home.
The Food Research and Action Center is an accredited
organization, thus making the information credible and reliable.
The information is timely because it relies on the most current
research.
Assessment: The article will help in providing insight on the
physical inactivity and fast foods as major contributors/causes
of obesity. This also goes for refuting that obesity occurs
naturally and lack of physical inactivity and fast foods do es not
contribute to obesity.
Larson, A. A. (2012). Childhood obesity in USA: A descriptive
snapshot of current responses disconnects, and what could hold
promise for additional mitigation. Movement & Sport Sciences,
78, 61-74. Retrieved from http://www.mov-sport-
sciences.org/articles/sm/abs/2012/04/sm120016/sm120016.html
This journal article examines the important importance of
physical activities in management of weight and as an obesity
intervention. The article also discussed the failure of schools in
providing comprehensive durations that allow for sufficient
physical activity engagement. Even though interscholastic
athletics tend to provide children with options for physical
activities, populations needing the activities, such as those at
risk of obesity or who are obese, are always underrepresented.
The article has been reviewed by a panel of experts for it to be
included in the Science & Motricité journal, thus meeting
academic standards of providing reliable and credible
information. It is timely because it was published n year 2012,
thus offering up-to-date information regarding childhood
obesity.
Assessment: In reference to the childhood obesity topic, the
information in this article provides insight on the sedentary
lifestyle (physical inactivity), as a major cause of obesity. In
addition, the fact that schools are unable to fully engage
children in physical activities supports the need for parents to
take over the role in controlling obesity by breaking the
sedentary lifestyle cycle.
Lindsay, A. C., Sussner, K. M., Kim, J., & Gortmaker, S.
(2006). The role of parents in preventing childhood obesity.
The Future of Children,16 (1), 169-186. Retrieved from
http://futureofchildren.org/futureofchildren/publications/docs/1
6_01_08.pdf
This article reviews evidence pertaining to how parents could
help children maintain and develop physical activity habits and
healthful eating, thus helping revert and prevent obesity and
overweight during childhood. Particularly, studies focusing on
child growth and nutrition details ways that parents influence
children’s development of activity-related and food- related
behaviors to examine the role of parents in curtailing children
obesity. As a journal article in The Future of Children, it is
reviewed by a panel of experts, thus making it reliable and
credible. Although not relatively current, as it was published in
year 2006, the article is still crucial in providing insight on the
strategies parent could employ to control obesity by breaking
the cycle of sedentary and fast food based lifestyle.
Assessment: The article provides insight on solution for
children’s obesity epidemic. This relates to the critical role
parents play in preventing and reverting obesity. This also goes
for the strategies they could use in controlling obesity by
breaking the cycle of sedentary and fast food based lifestyle.
Zhao, J., & Grant, S. F. A. (2011). Genetics of childhood
obesity. Journal of Obesity, (2011), 1-9.
Doi:10.1155/2011/845148. Retrieved from
http://www.hindawi.com/journals/jobe/2011/845148/cta/
This article explores the genetic factors that contribute to
obesity. The article also makes it clear that Genomegenome-
wide associations reveal a strong association of most disorders
with genomic variants. The research conducted in this article
shows that the loci that researchers had previously discovered to
contribute to obesity also contributes to childhood obesity by
increasing children’s BMI. The article is included in a journal,
Journal of Obesity, which nocomprise of a panel of experts that
review the credibility and reliability of articles. The journal
article is no, it is not timeless timeless, as it comprises the
latest research regarding the natural causes of childhood
obesity.
Assessment: This article provides insight on why some people
may refute the idea that lifestyle factors, such as fast food and
sedentary lifestyle, contribute to obesity. This is because they
are likely to believe that developing obesity is inherent in a
person’s genes.
Alphabetized (10 pts.): 10
Quality and relevance of sources (10): 10
Grammar/mechanics (20 pts.): 5
Sentences (20 pts.): 20
Word Choice (10 pts.): 7
APA format (30 pts.): 28
Total points (100 pts.): 80
I marked almost 2 dozen mechanical errors in this paper—
letters left off words, commas, subject/verb agreement,
capitalization, and other things. As I told you, I have to mark
all that stuff and you lose points each time I do. This could
have been an A if you had had it proofread carefully.
The Course Project will address a topic within one of four
course themes: education, technology, family, or health and
wellness. Each topic encompasses the potential for controversy,
which means there is more than one valid way of looking at the
issue and presenting the issue to an audience. The paper will
introduce the topic, provide background information, present a
main argument with evidence, and conclude in a way that
clearly leads a reader to take desired or recommended action.
Assignment
After thoroughly reading and researching a topic, complete the
weekly assignments addressing a topic from one of the course
themes, leading to two drafts that are revised in a final 8- to 10-
page research project.
The purpose of the assignment is to present an argument and
support it persuasively with relevant, properly attributed source
material. The primary audience for the project will be
determined in prewriting tasks. The secondary audience is an
academic audience that includes your professor and fellow
classmates.
Course assignments will help you develop your interest in a
theme and topic, engage in discussion with your professor and
classmates, and then learn to apply search strategies to retrieve
quality sources.
By the end of the course, you will submit a Course Project that
meets the requirements for scope and which includes the
following content areas.
I. Introduction
a. Attention-getting hook
b. Topic, purpose, and thesis
c. Background
d. Relevance to reader
II. Body
Logically presented, point-by-point argument with evidence
(the number of sections may differ by paper, but you should
plan to have at least three)
a. Section 1 (2–5 paragraphs)
b. Section 2 (2–5 paragraphs)
c. Section 3 (2–5 paragraphs)
d. Section 4 (2–5 paragraphs)
e. Section 5 (2–5 paragraphs)
III. Conclusion
Assignment Requirements PLEASE
[email protected]@@@@@@@@@@@@@@@@@@@@@@
@
· Original writing of 8–10 pages created during this course
· Attributed support from outside research with in-text citations
that correspond to the five required sources listed on the
References page; a minimum of one source must be included
from the Course Theme Reading List
· APA 6th edition use of Title page and running headers, in-text
and parenthetical citations, and References for all sources used
in the project
· Final draft addresses all professor and peer content and
citation revision suggestions and concerns from earlier drafts;
final draft of the Course Project is the result of revision and
represents consistent improvement over the first draft
Research Project Topics
Course Theme Reading List
Research on your topics begins with the Course Theme Reading
List, which is linked under the Textbook section of the Course
Syllabus. Be sure to click the word here to open the document.
While you are not required to read all of the resources, you
should plan to dedicate sufficient time to retrieve, preview, and
critically analyze sources on topics that are of interest to you.
The list of readings has been selected to help you narrow a
topic, and it also will help you generate search terms you can
use to continue your independent research.
Two readings are available for each of the topics listed below.
Start your research process by reviewing the Course Theme
Reading List. Note: All students will be required in their final
Course Project to include at least one source from the Course
Theme Reading List. Once you are introduced to library search
strategies, you will then search for the remaining number of
sources required for inclusion in-text and on the References
page of the final assignment. The table below lists the themes
and topics for the Course Project.
Education
Technology
Family
Health and Wellness
School Bullies
Multitasking and Technology
Sexualization of Girls
College Students and Weight Issues
No Child Left Behind Act/Race to the Top
Technology and Social Isolation
Gender Discrimination
Childhood Obesity
Grade Inflation
Perils of Social Networking
Unequal Rights in Marriage, Children
Fad Diets
College Students and Underage Drinking
Online Dating/Online Predators/Sex Offenders
Children of Divorce
Junk Food
Student Debt
Illegal Downloading of Protected Content
Domestic Violence
Sedentary Lifestyles
College Students, Cheating, and Plagiarism
Internet Censorship/Classified Information Leaks
Cyberbullying
Teenage Pregnancy
College Dropout Rates
Identity Theft
Life-Work (Im)balance/Flexible Work Schedules
Concussions in Athletes
High School Dropouts
Texting and Driving
Insurance Premiums for Smokers and Obese Employees
The full list of Course Theme Readings is linked from the
Course Syllabus. To access the readings, you will use the
library databases or the Course textbook. For help accessing the
library databases, please click on the following Accessing the
DeVry Library Database tutorial.
Grading Rubrics
Back to Top
Central Idea and Focus: The topic, purpose, and thesis are clear
and identifiable in the introduction; all ideas consistently
address the main argument without off-topic or irrelevant ideas.
Presentation of central idea or focus reflects revision and
refinement from prior drafts.
Support and development of ideas: Ideas are sufficiently
developed for each section. Fifteen points may be earned for
each of the five sections of the document. Introduction must
have attention-grabbing story, topic, purpose, credibility, and
why the topic is important; the thesis is graded above in the
central idea. Sections II, III, and IV must contain a main idea,
indicated by a topic sentence and followed by properly
attributed support from sources. Development of ideas
anticipates reader objections and responds appropriately.
Evidence is varied and effective. Uses argumentative strategies
and appeals to improve the logic and credibility of the presented
ideas. Conclusion contains memorable ideas and does not rely
on repetition of earlier content. Body of project reflects
improvement from earlier drafts or else points will be deducted
from each section accordingly.
Organization and Structure: The internal structure of a piece of
writing, the thread of central meaning. All ideas are organized
well without any missing or incomplete components.
Organization responds to feedback on earlier drafts and presents
an improved version from prior drafts. Points are deducted for
organization that has not been revised based on feedback.
Formatting, including use of APA: Correct title page, headers,
second page title, margins, alignment, spacing, font, and size (5
points). In-text citations and end-text References match and
demonstrate proficient use of APA style, errors in in-text
citations, or lack of in-text citations (10 points). References
page with a minimum of five sources correctly cited, match the
in-text citation, and use of citations demonstrates improvement
from early to final drafts (15 points). Formatting and layout:
Use of appropriate layout, including headings and effective use
of images, graphs, and charts that are effectively labeled and
integrated into the body of the report (10 points).
Grammar, Mechanics, and Style:Grammar refers to correctness
of language usage; mechanics refers to conventional correctness
in capitalization, punctuation, and spelling. Style includes word
choice, sentence variety, clarity, and conciseness. Also,
sentences vary in length and structure; ideas are clear, logical,
and concise. Style is persuasive and authentic to the topic and
purpose.
Milestones
Back to Top
PLEASE FOLLOW THE FOLLOWING SCHEDULE FOR THE
PROJECT.. THANKS
Week 1: Topic Selection (50 points)
Week 2: Source Summary (100 points)
Week 3: Research Proposal (50 points)
Week 4: Annotated Bibliography (100 points)
Week 5: First Draft (75 points) ………………………DUE THIS
WEEK 4/2/2015
Week 6: Second Draft (80 points)……………………DUE NEXT
WEEK BY 4/09/2015
Week 7: Final Draft (125 points)…………………….DUE ON
4/16/2015
Week 8: Reflective Postscript (50 points)……………DUE ON
4/23/2015
Best Practices
Back to Top
· Access the DeVry Library resources for the bulk of your
research. You can access the online library by clicking on the
Student Resources tab in Course Home.
· APA-style citations do not use footnotes or URLs (i.e., http://
or www.) for in-text citations. URLs are in the References page
as specified in the textbook or APA manual.
Use of Turnitin is part of this class. Avoid all forms of
plagiarism. Plagiarism is a serious offense and violates our
academic integrity policy. Do not use any information from
“paper mills,” or sites that offer papers on a number of topics;
these sites are among the first to be flagged as plagiarized.
Additionally, do not turn in any paper previously used in any
course, because self-plagiarism is also not allowed.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Chapter 3 Selections
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
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?
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
ObjectivesTo declare bool variables and write Boolean
expressions using relational operators (§3.2).To implement
selection control using one-way if statements (§3.3).To program
using one-way if statements (GuessBirthday) (§3.4).To
implement selection control using two-way if statements
(§3.5).To implement selection control using nested if and multi-
way if-else statements (§3.6).To avoid common errors and
pitfalls 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.9).To combine conditions using logical operators (&&, ||,
and !) (§3.10).To program using selection statements with
combined conditions (LeapYear, Lottery) (§§3.11–3.12).To
implement selection control using switch statements (§3.13).To
write expressions using the conditional operator (§3.14).To
examine the rules governing operator precedence and operator
associativity (§3.15).To debug errors (§3.16).
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
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.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Relational 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
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
One-way if Statements
if (booleanExpression)
{
statement(s);
}
if (radius >= 0)
{
area = radius * radius * PI;
cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
}
Boolean
Expression
true
Statement(s)
false
false
area = radius * radius * PI;
cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
true
(radius >= 0)
(a)
(b)
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Note
(a)
if ((i > 0) && (i < 10))
{
cout << "i is an " <<
"integer between 0 and 10";
}
if ((i > 0) && (i < 10))
cout << "i is an " <<
"integer between 0 and 10";
Equivalent
Braces can be omitted if the block contains a single statement
(b)
Outer parentheses required
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Examples
Listing 3.1 gives a program that checks whether a number is
even or odd. The program prompts the user to enter an integer
(line 9) and displays “number is even” if it is even (lines 11-12)
and “number is odd” if it is odd (lines 14-15).
TestBoolean
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Caution
Adding a semicolon at the end of an if clause is a common
mistake.
This mistake is hard to find, because it is not a compilation
error or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
(a)
if (radius >= 0);
{
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
}
if (radius >= 0) { };
{
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
}
Equivalent
Empty Body
(b)
Logic Error
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Lab #1 – Hand In
C++ Program
Write a program that accepts as input first one integer into a
variable named intValue1.
Next input a character into a variable named chrValue1.
If the intValue1 is even, then output to the screen “Integer is
even”.
If the chrValue1 is greater than ‘G’, then output to the screen
“Character is greater than G”.
Make sure you contain at least 2 comments
Variables are named correctly
The use of the if statement is done twice
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
The if...else Statement
if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}
false
Boolean
Expression
Statement(s) for the true case
true
Statement(s) for the false case
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Nested if Statements
if (i > k)
{
if (j > k)
cout << "i and j are greater than k";
}
else
cout << "i is less than or equal to k";
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Multiple Alternative if Statements
(a)
if (score >= 90.0)
cout << "Grade is A";
else
if (score >= 80.0)
cout << "Grade is B";
else
if (score >= 70.0)
cout << "Grade is C";
else
if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";
(b)
Equivalent
This is better
if (score >= 90.0)
cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace if-else statement
if (score >= 90.0)
cout << “Grade is A";
else if (score >= 80.0)
cout << “Grade is B";
else if (score >= 70.0)
cout << “Grade is C";
else if (score >= 60.0)
cout << “Grade is D";
else
cout << “Grade is F";
Suppose score is 70.0
The condition is false
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace if-else statement
if (score >= 90.0)
cout << “Grade is A";
else if (score >= 80.0)
cout << “Grade is B";
else if (score >= 70.0)
cout << “Grade is C";
else if (score >= 60.0)
cout << “Grade is D";
else
cout << “Grade is F";
Suppose score is 70.0
The condition is false
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace if-else statement
if (score >= 90.0)
cout << “Grade is A";
else if (score >= 80.0)
cout << “Grade is B";
else if (score >= 70.0)
cout << “Grade is C";
else if (score >= 60.0)
cout << “Grade is D";
else
cout << “Grade is F";
Suppose score is 70.0
The condition is true
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace if-else statement
if (score >= 90.0)
cout << “Grade is A";
else if (score >= 80.0)
cout << “Grade is B";
else if (score >= 70.0)
cout << “Grade is C";
else if (score >= 60.0)
cout << “Grade is D";
else
cout << “Grade is F";
Suppose score is 70.0
grade is C
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace if-else statement
if (score >= 90.0)
cout << “Grade is A";
else if (score >= 80.0)
cout << “Grade is B";
else if (score >= 70.0)
cout << “Grade is C";
else if (score >= 60.0)
cout << “Grade is D";
else
cout << “Grade is F";
Suppose score is 70.0
Exit the if statement
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Note
The else clause matches the most recent if clause in the same
block.
(a)
int i = 1;
int j = 2;
int k = 3;
if (i > j)
if (i > k)
cout << "A";
else
cout << "B";
(b)
Equivalent
int i = 1;
int j = 2;
int k = 3;
if (i > j)
if (i > k)
cout << "A";
else
cout << "B";
This is better with correct indentation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Note, cont.
Nothing is printed from the preceding statement. To force the
else clause to match the first if clause, you must add a pair of
braces:
int i = 1; int j = 2; int k = 3;
if (i > j)
{
if (i > k)
cout << "A";
}
else
cout << "B";
This statement prints B.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
TIP
(a)
if (number % 2 == 0)
even = true;
else
even = false;
(b)
Equivalent
This is better
bool even
= number % 2 == 0;
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
CAUTION
(a)
if (even == true)
cout <<"It is even.";
(b)
Equivalent
if (even)
cout << "It is even.";
This is better
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Common Errors in Selection Statements
Common Error 1: Forgetting Necessary Braces
(a) Wrong
if (radius >= 0)
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
if (radius >= 0)
{
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
}
(b) Correct
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Common Errors in Selection Statements
Common Error 2: Wrong Semicolon at the if Line
(a)
if (radius >= 0);
{
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
}
if (radius >= 0) { };
{
area = radius * radius * PI;
cout << "The area "
<< " is " << area;
}
Equivalent
Empty Body
(b)
Logic Error
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Common Errors in Selection Statements
Common Error 3: Mistakenly Using = for ==
if (count = 1)
cout << "count is zero" << endl;
else
cout << "count is not zero" << endl;
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Common Errors in Selection Statements
Common Error 4: Redundant Testing of Boolean Values
(a)
if (even == true)
cout <<"It is even.";
(b)
Equivalent
if (even)
cout << "It is even.";
This is better
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Problem: Body Mass Index
Body Mass Index (BMI) is a measure of health on weight. It can
be calculated by taking your weight in kilograms and dividing
by the square of your height in meters. The interpretation of
BMI for people 16 years or older is as follows:
ComputeBMI
BMI Interpretation
below 16 serious underweight
underweight
normal weight
overweight
29-35 seriously overweight
above 35 gravely overweight
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Example: Computing Taxes
The US federal personal income tax is calculated based on the
filing status and taxable income. There are four filing statuses:
single filers, married filing jointly, married filing separately,
and head of household. The tax rates for 2002 are shown in
Table 3.6.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Example: Computing Taxes, cont.
ComputeTax
if (status == 0)
{
// Compute tax for single filers
}
else if (status == 1)
{
// Compute tax for married file jointly
}
else if (status == 2)
{
// Compute tax for married file separately
}
else if (status == 3)
{
// Compute tax for head of household
}
else
{
// Display wrong status
}
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Example: A Simple Math Learning Tool
SubtractionQuiz
Run
This example creates a program for a first grader to practice
subtractions. The program randomly generates two single-digit
integers number1 and number2 with number1 >= number2 and
displays a question such as “What is 9 – 2?” to the student, as
shown in the sample output. After the student types the answer,
the program displays a message to indicate whether the answer
is correct.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
C++ Programming: From Problem Analysis to Program Design,
Fourth Edition
*
Lab #2 – Hand In
C++ Program
Write a program that accepts as input first one integer into a
variable named intValue1.
Accept a second integer from input into a variable named
intValue2.
If the intValue1 is even, then output to the screen “Value 1 is
even”, otherwise say “Value 1 is odd”.
If the intValue2 is even, then output to the screen “Value 2 is
even”, otherwise say “Value 2 is odd”.
If intValue2 is greater than intValue1, than output to the screen
“Value2 is greater than Value1” and then also output another
line saying “If part is true”, otherwise output to the screen
“Value1 is greater than Value2” and then also output another
line saying “else part is true”.
Make sure you contain at least 2 comments
Variables are named correctly
The use of the if-else statement is used 3 times.
C++ Programming: From Problem Analysis to Program Design,
Fourth Edition
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Logical Operators
Operator Name Description
! not logical negation
&& and logical conjunction
|| or logical disjunction
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Truth Table for Operator !
p !p
true false
false true
Example (assume age = 24, weight = 140)
!(age > 18) is false, because (age > 18) is true.
!( weight == 150) is true, because (weight == 150) is false.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Truth Table for Operator &&
Example (assume age = 24, weight = 140)
(age > 28) && (weight < 140) is false, because (age > 28) and
(weight < 140) are both false.
(age > 18) && (weight >= 140) is true, because both (age > 18)
and (weight >= 140) are true.
p1 p2 p1 && p2
false false false
false true false
true false false
true true true
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Truth Table for Operator ||
Example (assume age = 24, weight = 140)
(age > 34) || (weight < 140) is false, because both (age > 34)
and (weight < 140) are false.
(age > 18) || (weight >= 150) is false, because (age > 18) is true.
p1 p2 p1 || p2
false false false
false true true
true false true
true true true
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Examples
Listing 3.3 gives 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:
TestBooleanOperators
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Short-Circuit Operator
When evaluating p1 && p2, C++ first evaluates p1 and then
evaluates p2 if p1 is true; if p1 is false, it does not evaluate p2.
When evaluating p1 || p2, C++ first evaluates p1 and then
evaluates p2 if p1 is false; if p1 is true, it does not evaluate p2.
Therefore, && is referred to as the conditional or short-circuit
AND operator, and || is referred to as the conditional or short-
circuit OR operator.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
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)
LeapYear
Run
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Problem: Lottery
Randomly generates a lottery of a two-digit number, prompts
the user to enter a two-digit number, and determines whether
the user wins according to the following rule:
LotteryIf the user input matches the lottery in exact order, the
award is $10,000.If the user input matches the lottery, the award
is $3,000.If one digit in the user input matches a digit in the
lottery, the award is $1,000.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
C++ Programming: From Problem Analysis to Program Design,
Fourth Edition
*
Lab #3 – Hand In
C++ Program
Write a program that accepts as input first one integer into a
variable named intValue1.
Accept a second integer from input into a variable named
intValue2.
If the intValue1 is even, then output to the screen “Value 1 is
even”.
If intValue1 is not even, then test to see if the intValue2 is
even, then output to the screen “Value 2 is even”, otherwise say
“Both values is odd”.
Make sure you contain at least 2 comments
Variables are named correctly
The use of the if-else statement is used 3 times.
C++ Programming: From Problem Analysis to Program Design,
Fourth Edition
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
switch Statements
switch (status)
{
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: cout << "Errors: invalid status“ << endl;
}
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
switch Statement Flow Chart
status is 0
Compute tax for single filers
break
Compute tax for married file separately
break
Compute tax for married file jointly
status is 1
status is 2
break
Compute tax for married file separatly
status is 3
break
Compute tax for head of household
default
Next Statement
Default actions
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
switch Statement Rules
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The switch-expression must yield a value of char, byte, short, or
int type and must always be enclosed in parentheses.
The value1, ..., and valueN must have the same data type as the
value of the switch-expression. The resulting statements in the
case statement are executed when the value in the case
statement matches the value of the switch-expression. Note that
value1, ..., and valueN are constant expressions, meaning that
they cannot contain variables in the expression, such as 1 + x.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
switch Statement Rules
The keyword break is optional, but it should be used at the
end of each case in order to terminate the remainder of the
switch statement. If the break statement is not present, the next
case statement will be executed.
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
When the value in a case statement matches the value of the
switch-expression, the statements starting from this case are
executed until either a break statement or the end of the switch
statement is reached.
The default case, which is optional, can be used to perform
actions when none of the specified cases matches the switch-
expression.
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace switch statement
switch (day)
{
case 1: // Fall to through to the next case
case 2: // Fall to through to the next case
case 3: // Fall to through to the next case
case 4: // Fall to through to the next case
case 5: cout << "Weekday"; break;
case 0: // Fall to through to the next case
case 6: cout << "Weekend";
}
Suppose day is 3:
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace switch statement
switch (day)
{
case 1: // Fall to through to the next case
case 2: // Fall to through to the next case
case 3: // Fall to through to the next case
case 4: // Fall to through to the next case
case 5: cout << "Weekday"; break;
case 0: // Fall to through to the next case
case 6: cout << "Weekend";
}
Suppose day is 3:
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace switch statement
switch (day)
{
case 1: // Fall to through to the next case
case 2: // Fall to through to the next case
case 3: // Fall to through to the next case
case 4: // Fall to through to the next case
case 5: cout << "Weekday"; break;
case 0: // Fall to through to the next case
case 6: cout << "Weekend";
}
Suppose day is 3:
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace switch statement
switch (day)
{
case 1: // Fall to through to the next case
case 2: // Fall to through to the next case
case 3: // Fall to through to the next case
case 4: // Fall to through to the next case
case 5: cout << "Weekday"; break;
case 0: // Fall to through to the next case
case 6: cout << "Weekend";
}
Suppose day is 3:
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Trace switch statement
switch (day)
{
case 1: // Fall to through to the next case
case 2: // Fall to through to the next case
case 3: // Fall to through to the next case
case 4: // Fall to through to the next case
case 5: cout << "Weekday"; break;
case 0: // Fall to through to the next case
case 6: cout << "Weekend";
}
Suppose day is 3:
animation
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year and
displays the animal for the year.
ChineseZodiac
rabbit
tiger
ox
rat
dragon
snake
horse
sheep
monkey
rooster
dog
pig
0: monkey
1: rooster
2: dog
3: pig
4: rat
5: ox
6: tiger
7: rabbit
8: dragon
9: snake
10: horse
11: sheep
year % 12 =
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Conditional Operator
if (x > 0)
y = 1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(booleanExpression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Conditional Operator
cout << ((num % 2 == 0) ? "num is even" : "num is odd");
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
C++ Programming: From Problem Analysis to Program Design,
Fourth Edition
*
Lab #4 – Hand In
C++ Program
Write a program that accepts as input a character variable called
chrValue1.
If chrValue1 is ‘G’ or ‘g’ then write out to the screen “You
entered a g”, if chrValue1 is ‘T’ or ‘t’ then write out to the
screen “You entered a t”, if chrValue1 is ‘P’ or ‘p’ then write
out to the screen “You entered a p”, otherwise output “You
tricked me”.
Make sure you contain at least 3 comments
Variables are named correctly
Make sure that you use the switch statement and do not use any
if statements.
C++ Programming: From Problem Analysis to Program Design,
Fourth Edition
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Operator Precedence
How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Operator Precedencevar++, var--+, - (Unary plus and minus),
++var,--var(type) Casting! (Not)*, /, % (Multiplication,
division, and remainder)+, - (Binary addition and subtraction)<,
<=, >, >= (Comparison)==, !=; (Equality) && (Conditional
AND) Short-circuit AND|| (Conditional OR) Short-circuit OR=,
+=, -=, *=, /=, %= (Assignment operator)
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Enumerated Types
enum Day {MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY};
Once a type is defined, you can declare a variable of that type:
Day day;
The variable day can hold one of the values defined in the
enumerated type. For example, the following statement assigns
enumerated value MONDAY to variable day:
day = MONDAY;
Companion Website
© Copyright 2013 by Pearson Education, Inc. All Rights
Reserved.
*
Enumerated Types
As with any other type, you can declare and initialize a variable
in one statement:
Day day = MONDAY;
Furthermore, C++ allows you to declare an enumerated type and
variable in one statement. For example,
enum Day {MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY} day = MONDAY;
TestEnumeratedType
Run
Companion Website
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
Boolean
Expression
true
Statement(s)
false
(radius >= 0)
true
area = radius * radius * PI;
cout <<
"The area for the circle of "
<<
" radius "
<<
radius
<<
" is "
<< area
;
false
(
a
)
(
b
)
if
(
(i >
0
) && (i <
10
)
)
{
cout <<
"i is an "
<<
"integer between 0 and 10"
;
}
(
a)
Equivalent
(b)
if
(
(i >
0
) && (i <
10
)
)
cout <<
"i is an "
<<
"integer between 0 and 10"
;
Outer parentheses required
Braces can be omitted if the block contains a single
statement
if
(radius >=
0
)
;
{
area = radius * radius * PI;
cout <<
"The area "
<<
" is "
<<
area;
}
(a
)
Equivalent
Logic Error
if
(radius >=
0
)
{ }
;
{
area = radius * radius * PI;
cout <<
"The area "
<<
" is "
<<
area;
}
(b)
Empty Body
Boolean
Expression
false
true
Statement(s) for the false case
Statement(s) for the true case
if
(score >=
90.0
)
cout <<
"Grade is
A
"
;
else
if
(score >=
80.0
)
cout <<
"Grade is
B"
;
else
if
(score >=
70.0
)
cout <<
"Grade is
C"
;
else
if
(score >=
60.0
)
cout <<
"Grade is
D"
;
else
cout
<<
"Grade is
F"
;
(a
)
Equivalent
if
(score >=
90.0
)
cout <<
"Grade is
A
"
;
else if
(score >=
80.0
)
cout <<
"Grade is
B"
;
else if
(score >=
70.0
)
cout <<
"Grade is
C"
;
else if
(score >=
60.0
)
cout <<
"Grade is
D"
;
else
cou
t <<
"Grade is
F"
;
(b
)
This is better
int
i =
1
;
int
j =
2
;
int
k =
3
;
if
(i > j)
if
(i > k)
cout <<
"A"
;
else
cout <<
"B"
;
(a
)
Equivalent
(
b
)
int
i =
1
;
int
j =
2
;
int
k =
3
;
if
(i > j)
if
(i > k)
cout <<
"A"
;
else
cout <<
"B"
;
This i
s better
with correct
indentation
if
(number %
2
==
0
)
even =
true
;
else
even =
false
;
(a
)
Equivalent
bool
even
= number %
2
==
0
;
(
b
)
This is better
if
(even ==
true
)
cout <<
"It is even."
;
(
a
)
Equivalent
if
(even)
cout <<
"It is even."
;
(b)
This is better
if
(radius >=
0
)
area = radius * radius * PI;
cout <<
"The area "
<<
" is "
<<
area;
(a
)
Wrong
if
(radius >=
0
)
{
area = radius * radius * PI;
cout <<
"The area "
<<
" is "
<<
area;
}
(b)
Correct
Run
BMI
Interpretation
below 16
serious underweight
16
-
18
underweight
18
-
24
normal weight
24
-
29
o
verweight
29
-
3
5
seriously overweight
above 35
gravely overweight
Operator Name Description
! not logical negation
&& and logical conjunction
|| or logical disjunction
p !p
true false
false true
Example
(
assume
age = 24,
weight = 140
)
!(
age > 18
)
is
false
, because
(
age
>
18
)
is
true
.
!(
weight =
=
150
)
is
true
, because
(
weight
=
= 150
)
is
false
.
p1 p2 p1 && p2
false false false
false true false
true false false
true true true
Example
(assume age = 24,
weight = 140
)
(
age
>
2
8
) && (
weight <
140
)
is
false
, because
(age
>
2
8)
and
(
weight <
140
)
are bo
th
false
.
(age > 18) && (
weight >
=
140
)
is
true
, because
both (age > 18) and
(
weight >
=
140
)
are true
.
p1 p2 p1 || p2
false false false
false true true
true false true
true true true
Example (assume age = 24,
weight = 140
)
(age > 34) || (
weight <
140
)
is
false
, because
both
(age
> 34) and
(
weight <
140
)
are false
.
(age >
18
) ||
(
weight >= 1
5
0
)
is
false
, because
(age >
18
)
is true
.
status is 0
Compute tax for single filers
break
Compute tax for married file jointly
break
status is 1
Compute tax for married file separatly
break
status is 2
Compute tax for head of household
break
st
atus is 3
Default actions
default
Next Statement
rat
ox
tiger
rabbit
dragon
snake
horse
sheep
monkey
rooster
dog
pig
0: monkey
1: rooster
2
: dog
3
: pig
4
: rat
5
: ox
6
: tiger
7
: rabbit
8
: dragon
9
: snake
10
: horse
11: sheep
year % 12
=

More Related Content

Similar to © Copyright 2013 by Pearson Education, Inc. All Rights Res.docx

T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 

Similar to © Copyright 2013 by Pearson Education, Inc. All Rights Res.docx (20)

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
14 strings
14 strings14 strings
14 strings
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Data structure week 3
Data structure week 3Data structure week 3
Data structure week 3
 
Basics of c
Basics of cBasics of c
Basics of c
 
Tut1
Tut1Tut1
Tut1
 
C Programming
C ProgrammingC Programming
C Programming
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Strings
StringsStrings
Strings
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
 
Bsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and stringsBsc cs i pic u-4 function, storage class and array and strings
Bsc cs i pic u-4 function, storage class and array and strings
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
 
L5 array
L5 arrayL5 array
L5 array
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
 

More from LynellBull52

· · · Must be a foreign film with subtitles· Provide you wit.docx
· · · Must be a foreign film with subtitles· Provide you wit.docx· · · Must be a foreign film with subtitles· Provide you wit.docx
· · · Must be a foreign film with subtitles· Provide you wit.docx
LynellBull52
 
· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx
· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx
· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx
LynellBull52
 
· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx
· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx
· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx
LynellBull52
 
· Week 10 Assignment 2 SubmissionStudents, please view the.docx
· Week 10 Assignment 2 SubmissionStudents, please view the.docx· Week 10 Assignment 2 SubmissionStudents, please view the.docx
· Week 10 Assignment 2 SubmissionStudents, please view the.docx
LynellBull52
 
· Write in paragraph format (no lists, bullets, or numbers).· .docx
· Write in paragraph format (no lists, bullets, or numbers).· .docx· Write in paragraph format (no lists, bullets, or numbers).· .docx
· Write in paragraph format (no lists, bullets, or numbers).· .docx
LynellBull52
 
· WEEK 1 Databases and SecurityLesson· Databases and Security.docx
· WEEK 1 Databases and SecurityLesson· Databases and Security.docx· WEEK 1 Databases and SecurityLesson· Databases and Security.docx
· WEEK 1 Databases and SecurityLesson· Databases and Security.docx
LynellBull52
 
· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx
· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx
· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx
LynellBull52
 
· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx
· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx
· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx
LynellBull52
 
· Question 1· · How does internal environmental analy.docx
· Question 1· ·        How does internal environmental analy.docx· Question 1· ·        How does internal environmental analy.docx
· Question 1· · How does internal environmental analy.docx
LynellBull52
 
· Question 1Question 192 out of 2 pointsWhat file in the.docx
· Question 1Question 192 out of 2 pointsWhat file in the.docx· Question 1Question 192 out of 2 pointsWhat file in the.docx
· Question 1Question 192 out of 2 pointsWhat file in the.docx
LynellBull52
 
· Question 15 out of 5 pointsWhen psychologists discuss .docx
· Question 15 out of 5 pointsWhen psychologists discuss .docx· Question 15 out of 5 pointsWhen psychologists discuss .docx
· Question 15 out of 5 pointsWhen psychologists discuss .docx
LynellBull52
 
· Question 1 2 out of 2 pointsWhich of the following i.docx
· Question 1 2 out of 2 pointsWhich of the following i.docx· Question 1 2 out of 2 pointsWhich of the following i.docx
· Question 1 2 out of 2 pointsWhich of the following i.docx
LynellBull52
 
· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx
· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx
· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx
LynellBull52
 
· Strengths Public Recognition of OrganizationOverall Positive P.docx
· Strengths Public Recognition of OrganizationOverall Positive P.docx· Strengths Public Recognition of OrganizationOverall Positive P.docx
· Strengths Public Recognition of OrganizationOverall Positive P.docx
LynellBull52
 
· Part I Key Case SummaryThis case discusses the Union Carbid.docx
· Part I Key Case SummaryThis case discusses the Union Carbid.docx· Part I Key Case SummaryThis case discusses the Union Carbid.docx
· Part I Key Case SummaryThis case discusses the Union Carbid.docx
LynellBull52
 
· Perceptual process is a process through manager receive organize.docx
· Perceptual process is a process through manager receive organize.docx· Perceptual process is a process through manager receive organize.docx
· Perceptual process is a process through manager receive organize.docx
LynellBull52
 
· Performance Critique Assignment· During the first month of.docx
· Performance Critique Assignment· During the first month of.docx· Performance Critique Assignment· During the first month of.docx
· Performance Critique Assignment· During the first month of.docx
LynellBull52
 
· Please read the following article excerpt, and view the video cl.docx
· Please read the following article excerpt, and view the video cl.docx· Please read the following article excerpt, and view the video cl.docx
· Please read the following article excerpt, and view the video cl.docx
LynellBull52
 

More from LynellBull52 (20)

· · · Must be a foreign film with subtitles· Provide you wit.docx
· · · Must be a foreign film with subtitles· Provide you wit.docx· · · Must be a foreign film with subtitles· Provide you wit.docx
· · · Must be a foreign film with subtitles· Provide you wit.docx
 
·  Identify the stakeholders and how they were affected by Heene.docx
·  Identify the stakeholders and how they were affected by Heene.docx·  Identify the stakeholders and how they were affected by Heene.docx
·  Identify the stakeholders and how they were affected by Heene.docx
 
· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx
· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx
· · Re WEEK ONE - DISCUSSION QUESTION # 2posted by DONALD DEN.docx
 
· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx
· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx
· Week 3 AssignmentGovernment and Not-For-Profit AccountingVal.docx
 
· Week 10 Assignment 2 SubmissionStudents, please view the.docx
· Week 10 Assignment 2 SubmissionStudents, please view the.docx· Week 10 Assignment 2 SubmissionStudents, please view the.docx
· Week 10 Assignment 2 SubmissionStudents, please view the.docx
 
· Write in paragraph format (no lists, bullets, or numbers).· .docx
· Write in paragraph format (no lists, bullets, or numbers).· .docx· Write in paragraph format (no lists, bullets, or numbers).· .docx
· Write in paragraph format (no lists, bullets, or numbers).· .docx
 
· WEEK 1 Databases and SecurityLesson· Databases and Security.docx
· WEEK 1 Databases and SecurityLesson· Databases and Security.docx· WEEK 1 Databases and SecurityLesson· Databases and Security.docx
· WEEK 1 Databases and SecurityLesson· Databases and Security.docx
 
· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx
· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx
· Unit 4 Citizen RightsINTRODUCTIONIn George Orwells Animal.docx
 
· Unit Interface-User Interaction· Assignment Objectives Em.docx
· Unit  Interface-User Interaction· Assignment Objectives Em.docx· Unit  Interface-User Interaction· Assignment Objectives Em.docx
· Unit Interface-User Interaction· Assignment Objectives Em.docx
 
· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx
· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx
· The Victims’ Rights MovementWrite a 2 page paper.  Address the.docx
 
· Question 1· · How does internal environmental analy.docx
· Question 1· ·        How does internal environmental analy.docx· Question 1· ·        How does internal environmental analy.docx
· Question 1· · How does internal environmental analy.docx
 
· Question 1Question 192 out of 2 pointsWhat file in the.docx
· Question 1Question 192 out of 2 pointsWhat file in the.docx· Question 1Question 192 out of 2 pointsWhat file in the.docx
· Question 1Question 192 out of 2 pointsWhat file in the.docx
 
· Question 15 out of 5 pointsWhen psychologists discuss .docx
· Question 15 out of 5 pointsWhen psychologists discuss .docx· Question 15 out of 5 pointsWhen psychologists discuss .docx
· Question 15 out of 5 pointsWhen psychologists discuss .docx
 
· Question 1 2 out of 2 pointsWhich of the following i.docx
· Question 1 2 out of 2 pointsWhich of the following i.docx· Question 1 2 out of 2 pointsWhich of the following i.docx
· Question 1 2 out of 2 pointsWhich of the following i.docx
 
· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx
· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx
· Processed on 09-Dec-2014 901 PM CST · ID 488406360 · Word .docx
 
· Strengths Public Recognition of OrganizationOverall Positive P.docx
· Strengths Public Recognition of OrganizationOverall Positive P.docx· Strengths Public Recognition of OrganizationOverall Positive P.docx
· Strengths Public Recognition of OrganizationOverall Positive P.docx
 
· Part I Key Case SummaryThis case discusses the Union Carbid.docx
· Part I Key Case SummaryThis case discusses the Union Carbid.docx· Part I Key Case SummaryThis case discusses the Union Carbid.docx
· Part I Key Case SummaryThis case discusses the Union Carbid.docx
 
· Perceptual process is a process through manager receive organize.docx
· Perceptual process is a process through manager receive organize.docx· Perceptual process is a process through manager receive organize.docx
· Perceptual process is a process through manager receive organize.docx
 
· Performance Critique Assignment· During the first month of.docx
· Performance Critique Assignment· During the first month of.docx· Performance Critique Assignment· During the first month of.docx
· Performance Critique Assignment· During the first month of.docx
 
· Please read the following article excerpt, and view the video cl.docx
· Please read the following article excerpt, and view the video cl.docx· Please read the following article excerpt, and view the video cl.docx
· Please read the following article excerpt, and view the video cl.docx
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 

Recently uploaded (20)

AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 

© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx

  • 1. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Chapter 4 Mathematical Functions, Characters, and Strings © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Motivations Suppose you need to estimate the area enclosed by four cities, given the GPS locations (latitude and longitude) of these cities, as shown in the following diagram. How would you write a program to solve this problem? You will be able to write such a program after completing this chapter. Orlando (28.5383355,-81.3792365) Savannah (32.0835407,-81.0998342)
  • 2. Charlotte (35.2270869,-80.8431267) Atlanta (33.7489954,-84.3879824) © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * ObjectivesTo solve mathematics problems by using the C++ mathematical functions (§4.2).To represent characters using the char type (§4.3).To encode characters using ASCII code (§4.3.1).To read a character from the keyboard (§4.3.2).To represent special characters using the escape sequences (§4.3.3).To cast a numeric value to a character and cast a character to an integer (§4.3.4).To compare and test characters (§4.3.5).To program using characters (DisplayRandomCharacter, GuessBirthday) (§§4.4-4.5).To test and convert characters using the C++ character functions (§4.6).To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.7).To represent strings using the string type and introduce objects and instance functions (§4.8).To use the subscript operator for accessing and modifying characters in a string (§4.8.1).To use the + operator to concatenate strings (§4.8.2).To compare strings using the relational operators (§4.8.3).To read strings from the keyboard (§4.8.4).To revise
  • 3. the lottery program using strings (LotteryUsingStrings) (§4.9).To format output using stream manipulators (§4.10).To read and write data from/to a file (§4.11). © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Mathematical Functions C++ provides many useful functions in the cmath header for performing common mathematical functions. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trigonometric Functions Function Description
  • 4. sin(radians) Returns the trigonometric sine of an angle in radians. cos(radians) Returns the trigonometric cosine of an angle in radians. tan(radians) Returns the trigonometric tangent of an angle in radians. asin(a) Returns the angle in radians for the inverse of sine. acos(a) Returns the angle in radians for the inverse of cosine. atan(a) Returns the angle in radians for the inverse of tangent.
  • 5. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Exponent Functions x Function Description exp(x) Returns e raised to power of x (ex). log(x) Returns the natural logarithm of x (ln(x) = loge(x)). log10(x) Returns the base 10 logarithm of x (log10(x)). pow(a, b) Returns a raised to the power of b (ab). sqrt(x) Returns the square root of x (�EMBED Equation.3���) for x >= 0.
  • 6. _1173422839.unknown © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Rounding Functions Function Description ceil(x) x is rounded up to its nearest integer. This integer is returned
  • 7. as a double value. floor(x) x is rounded down to its nearest integer. This integer is returned as a double value. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * The min, max, and abs Functions max(2, 3) returns 3 max(2.5, 3.0) returns 4.0 min(2.5, 4.6) returns 2.5 abs(-2) returns 2abs(-2.1) returns 2.1
  • 8. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Case Study: Computing Angles of a Triangle Write a program that prompts the user to enter the x- and y- coordinates of the three corner points in a triangle and then displays the triangle’s angles. ComputeAngles Run A B C a
  • 9. b c A = acos((a * a - b * b - c * c) / (-2 * b * c)) B = acos((b * b - a * a - c * c) / (-2 * a * c)) C = acos((c * c - b * b - a * a) / (-2 * a * b)) x1, y1 x2, y2 x3, y3 © Copyright 2013 by Pearson Education, Inc. All Rights
  • 10. Reserved. * Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding character. For example, the following statements display character b. char ch = 'a'; cout << ++ch; © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Read Characters To read a character from the keyboard, use cout << "Enter a character: "; char ch; cin >> ch; © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Escape Sequences for Special Characters Character Escape Sequence Name ASCII Code
  • 11. b Backspace 8 t Tab 9 n Linefeed 10 f Formfeed 12 r Carriage Return 13 Backslash 92 ' Single Quote 39 " Double Quote 34
  • 12. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. Lab #1 Write a program that accepts as input a character variable called chrValue1. If chrValue1 is ‘G’ or ‘g’ then write out to the screen “You entered a g”, if chrValue1 is ‘T’ or ‘t’ then write out to the screen “You entered a t”, if chrValue1 is ‘P’ or ‘p’ then write out to the screen “You entered a p”, otherwise output “You tricked me”. Make sure you contain at least 3 commentsVariables are named correctlyMake sure that you use the switch statement and do not use any if statements. * © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from u0000 to u007f
  • 13. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from u0000 to u007f © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Casting between char and Numeric Types int i = 'a'; // Same as int i = static_cast<int>('a'); char c = 97; // Same as char c = static_cast<char>(97); © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Numeric Operators on Characters The char type is treated as if it is an integer of the byte size. All numeric operators can be applied to char operands. A char operand is automatically cast into a number if the other operand is a number or a character. For example, the following statements
  • 14. int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 cout << "i is " << i << endl; // i is decimal 101 int j = 2 + 'a'; // (int)'a' is 97 cout << "j is " << j << endl; cout << j << " is the ASCII code for character " << static_cast<char>(j) << endl; Display i is 101 j is 99 99 is the ASCII code for character c © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Note It is worthwhile to note that the ASCII for lowercase letters are consecutive integers starting from the code for 'a', then for 'b', 'c', ..., and 'z'. The same is true for the uppercase letters. Furthermore, the ASCII code for 'a' is greater than the code for 'A'. So 'a' - 'A' is the same as 'b' - 'B'. For a lowercase letter ch, its corresponding uppercase letter is static_cast<char>('A' + (ch - 'a')). © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Problem: Converting a Lowercase to Uppercase ToUppercase Run
  • 15. Write a program that prompts the user to enter a lowercase letter and finds its corresponding uppercase letter. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Comparing and Testing Characters Two characters can be compared using the comparison operators just like comparing two numbers. This is done by comparing the ASCII codes of the two characters. 'a' < 'b' is true because the ASCII code for 'a' (97) is less than the ASCII code for 'b' (98). 'a' < 'A' is true because the ASCII code for 'a' (97) is less than the ASCII code for 'A' (65). '1' < '8' is true because the ASCII code for '1' (49) is less than the ASCII code for '8' (56). © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Case Study: Generating Random Characters Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. Every character has a unique ASCII code between 0 and 127. To generate a random character is to generate a random integer between 0 and 127. You learned how to generate a random number in §3.8. Recall that you can use the srand(seed) function
  • 16. to set a seed and use rand() to return a random integer. You can use it to write a simple expression to generate random numbers in any range. For example, © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Case Study: Generating Random Characters, cont. DisplayRandomCharacter rand() % 10 Returns a random integer between 0 and 9. Returns a random integer between 50 and 99. 50 + rand() % 50
  • 17. Returns a random number between a and a + b, excluding a + b. a + rand() % b © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Case Study: Guessing Birthdays 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: GuessBirthday Run
  • 18. 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Set2 Set1 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31
  • 19. Set3 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 Set4 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31
  • 20. Set5 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31 + = 19 © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Character Functions CharacterFunctions
  • 21. Run Function Description isdigit(ch) Returns true if the specified character is a digit. isalpha(ch) Returns true if the specified character is a letter. isalnum(ch) Returns true if the specified character is a letter or digit. islower(ch) Returns true if the specified character is a lowercase letter. isupper(ch) Returns true if the specified character is an uppercase letter. isspace(ch) Returns true if the specified character is a whitespace character. tolower(ch) Returns the lowercase of the specified character.
  • 22. toupper(ch) Returns the uppercase of the specified character. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Case Study: Converting a Hexadecimal Digit to a Decimal Value Write a program that converts a hexadecimal digit into a decimal value. HexDigit2Dec Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved.
  • 23. * The string Type string s; string message = "Programming is fun"; Function Description Returns the number of characters in this string. Same as length(); Returns the character at the specified index from this string.
  • 24. length() size() at(index) © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * String Subscript Operator For convenience, C++ provides the subscript operator for accessing the character at a specified index in a string using the syntax stringName[index]. You can use this syntax to retrieve and modify the character in a string.
  • 30. message.at(13) message.length is 14 © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * String Subscript Operator string s = "ABCD"; s[0] = 'P'; cout << s[0] << endl; © Copyright 2013 by Pearson Education, Inc. All Rights Reserved.
  • 31. Lab #2 Enter a sample string that is at least 10 characters in length, no spaces. Output to the screen the characters at the 1st, 3rd, 5th, 7th and 9th position in the string. Make sure you contain at least 3 commentsVariables are named correctly * © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Concatenating Strings string s3 = s1 + s2; message += " and programming is fun"; © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Comparing Strings You can use the relational operators ==, !=, <, <=, >, >= to compare two strings. This is done by comparing their corresponding characters on by one from left to right. For example,
  • 32. string s1 = "ABC"; string s2 = "ABE"; cout << (s1 == s2) << endl; // Displays 0 (means false) cout << (s1 != s2) << endl; // Displays 1 (means true) cout << (s1 > s2) << endl; // Displays 0 (means false) cout << (s1 >= s2) << endl; // Displays 0 (means false) cout << (s1 < s2) << endl; // Displays 1 (means true) cout << (s1 <= s2) << endl; // Displays 1 (means true) © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Reading Strings 1 string city; 2 cout << "Enter a city: "; 3 cin >> city; // Read to array city 4 cout << "You entered " << city << endl; 1 string city; 2 cout << "Enter a city: "; 3 getline(cin, city, 'n'); // Same as getline(cin, city) 4 cout << "You entered " << city << endl; © Copyright 2013 by Pearson Education, Inc. All Rights
  • 33. Reserved. * Example Write a program that prompts the user to enter two cities and displays them in alphabetical order. OrderTwoCities Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Case Study: Revising the Lottery Program Using Strings A problem can be solved using many different approaches. This section rewrites the lottery program in Listing 3.7 using strings. Using strings simplifies this program. LotteryUsingStrings Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. *
  • 34. Formatting Console Output Manipulator Description setprecision(n) sets the precision of a floating-point number fixed displays floating-point numbers in fixed-point notation showpoint causes a floating-point number to be displayed with a decimal point and trailing zeros even if it has no fractional part setw(width) specifies the width of a print field left justifies the output to the left
  • 35. right justifies the output to the right © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * setprecision(n) Manipulator double number = 12.34567; cout << setprecision(3) << number << " " << setprecision(4) << number << " " << setprecision(5) << number << " " << setprecision(6) << number << endl; displays 12.3□12.35□12.346□12.3457 © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. *
  • 36. fixed Manipulator double monthlyPayment = 345.4567; double totalPayment = 78676.887234; cout << fixed << setprecision(2) << monthlyPayment << endl << totalPayment << endl; displays 345.46 78676.89 © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * showpoint Manipulator cout << setprecision(6); cout << 1.23 << endl; cout << showpoint << 1.23 << endl; cout << showpoint << 123.0 << endl; displays 1.23 1.23000 123.000 © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. *
  • 37. setw(width) Manipulator cout << setw(8) << "C++" << setw(6) << 101 << endl; cout << setw(8) << "Java" << setw(6) << 101 << endl; cout << setw(8) << "HTML" << setw(6) << 101 << endl; displays □□□□□C++□□□101 □□□□Java□□□101 □□□□HTML□□□101 8 6 © Copyright 2013 by Pearson Education, Inc. All Rights
  • 38. Reserved. * left and right Manipulators cout << right; cout << setw(8) << 1.23 << endl; cout << setw(8) << 351.34 << endl; displays □□□□1.23 □□351.34 © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * left and right Manipulators cout << left; cout << setw(8) << 1.23; cout << setw(8) << 351.34 << endl; displays 1.23□□□□351.34□□ © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Example: Display a Table Degrees Radians Sine Cosine Tangent
  • 39. 30 0.5236 0.5000 0.8660 0.5773 60 1.0472 0.8660 0.5000 1.7320 FormatDemo Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Simple File Output To write data to a file, first declare a variable of the ofstream type: ofstream output; To specify a file, invoke the open function from output object as follows: output.open("numbers.txt"); Optionally, you can create a file output object and open the file in one statement like this: ofstream output("numbers.txt"); To write data, use the stream insertion operator (<<) in the same way that you send data to the cout object. For example, output << 95 << " " << 56 << " " << 34 << endl; SimpleFileOutput Run
  • 40. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Simple File Input To read data from a file, first declare a variable of the ifstream type: ifstream input; To specify a file, invoke the open function from input as follows: input.open("numbers.txt"); Optionally, you can create a file output object and open the file in one statement like this: ifstream input("numbers.txt"); To read data, use the stream extraction operator (>>) in the same way that you read data from the cin object. For example, input << score1 << score2 << score3; SimpleFileInput Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. Lab #3 Write a program that accepts as input a string variable called strFirstName, then another string variable called strLastName, and then string variable called strEmail.Write out to a file each, however make sure it looks like :First Name: DavidLast Name: WiesnerEmail Addr: [email protected] Make sure you contain at least 3 commentsVariables are named
  • 41. correctlyProgram functions as expected * Orlando (28.5383355,-81.3792365) Savannah (32.0835407,-81.0998342) Charlotte (35.2270869,-80.8431267) Atlanta (33.7489954,-84.3879824) Function Description sin(radians) Returns the trigonometric sine of an angle in radians. cos(radians) Returns the trigonometric cosine of an angle in radians . tan(radians) Returns the trigonometric tangent of an angle in radians . asin(a) Returns the angle in radians for the inverse of sine . acos(a) Returns the angle in radians for the inverse of cosine. atan(a) Returns the angle in radians for the inverse of tangent . Function Description exp(x) Returns e raised to power of x (e x ). log(x) Returns the natural logarithm of x (ln(x) = log e (x)). log10(x) Returns the base 10 logarithm of x (log 10 (x)).
  • 42. pow(a, b) Returns a raised to the power of b (a b ). sqrt(x) Returns the square root of x ( x ) for x >= 0. Function Description ceil(x) x is rounded up to its nearest integer. This integer is returned as a double value. floor(x) x is rounded down to its nearest integer. This integer is returned as a double value. A B C a b c A = acos((a * a - b * b - c * c) / (-2 * b * c)) B = acos((b * b - a * a - c * c) / (-2 * a * c)) C = acos((c * c - b * b - a * a) / (-2 * a * b)) x1, y1 x2, y2 x3, y3 Character Escape Sequence Name ASCII Code b Backspace 8 t Tab 9
  • 43. n Linefeed 10 f Formfeed 12 r Carriage Return 13 Backslash 92 ' Single Quote 39 " Double Quote 34 rand() % 10 Returns a random integer between 0 and 9. 50 + rand() % 50 Returns a random integer between 50 and 99. a + rand() % b
  • 44. Returns a random number between a and a + b, excluding a + b. Run 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Set1 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31 Set2 1 3 5 7 9 11 13 15 17 19 21 23
  • 45. 25 27 29 31 Set3 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31 Set4 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31 Set5 + = 19 Function Description
  • 46. isdigit(ch) Returns true if the specified character is a digit. isalpha(ch) Returns true if the specified character is a letter. isalnum(ch) Returns true if the specified character is a letter or digit. islower(ch) Returns true if the specified character is a lowercase letter. isupper(ch) Returns true if the specified character is an uppercase letter. isspace(ch) Returns true if the specified character is a whitespace character. tolower(ch) Returns the lowercase of the specified character . toupper(ch) Returns the uppercase of the specified character . Function Description Returns the number of characters in this string. Same as length(); Returns the character at the specified index from this string . length() size() at(index) Indices W e
  • 49. 12 13 message message.at(0) message.at(13) message.length is 14 Manipulator Description setprecision(n) sets the precision of a floating - point number fixed displays floating -
  • 50. point numbers in fixed - point notation showpoint causes a floating - point number to be displayed with a decimal point and trailing zeros even if it has no fractional part setw(width) specifies the width of a print field left justifies the output to the left right justifies the output to the right □□□□□C++□□□101 □□□□Java□□□101 □□□□HTML□□□101 8
  • 51. 6 Running head: ANNOTATED BIBLIOGRAPHY FOR CHILDHOOD OBESITY 1 ANNOTATED BIBLIOGRAPHY FOR CHILDHOOD OBESITY 2 THIS IS LAST WEEK PAPER WITH CORRECTION. PLEASE NOTE FOR NEXT PAPER. THANKS. Annotated Bibliography for Childhood ObesityJonhn King DeVry University ENGL 14ggggggggg7 Professor bobk king Week Four 03/26/2015 Annotated Bibliography for Childhood Obesity In an obesity-related report, the case of a three-year-old child who had died from obesity complications was detailed. The child’s Body Mass Index should have been 14.5 kg, but it was recorded to be 38 kg. The child died from heart failure, which is one of obesity-related complications. As shocking, as it may be, this is not an isolated incident. All over the news, cases of children who have died from obesity- related complications are eminent. The common cause of obesity-related deaths has been associated with sleep apnea, a condition where the folds of fat block airways. According to experts, it is sad and devastating to see children chocked by their own fat as a result of eating foods laden with sugars and fats with little or no exercise (BBC, 2014). Such incidences incidents highlight the severity of obesity, as an epidemic, which is primarily caused by a fast food and sedentary-based lifestyle that lead to severe obesity-related health complications leading to death, thus the need for sensitizing parents, as primary care givers, on the need to
  • 52. intervene and change their children’s lifestyle to control and prevent obesity. Annotated Bibliography BBC. (2014). Three-year-old dies from obesity. Retrieved from http://news.bbc.co.uk/2/hi/health/3752597.stm This news-based article explores the incidence of a three-year- old baby who died from heart failure, as a complication for of obesity. Taking the obesity case further, the article explores increased incidences of children’s deaths resulting from other obesity- relation related complications, such as sleep apnea. The News news article is credible and reliable because the information put in the article is derived from experts and credible sources, such as Health Select Committee Report that was written comprise of by doctors from Birmingham Children's Hospital. The article is timely because it is up- to- date in the sense that it comprises information relating to the current state of obesity epidemic. My assessment: The article is of crucial importance in the paper because it provides the anecdote that will make the readers interested and glued to the papers. In addition, the obesity- related deaths reported in the paper provide insight on the severity of obesity epidemic, thus evoking in readers the need to act on it. Food Research and Action Center. (2014).Factors contributing to overweight and obesity. Retrieved from http://frac.org/initiatives/hunger-and-obesity/what-factors- contribute-to-overweight-and-obesity/ This article discusses factors that lead to increased caloric intake, thus contributing to obesity. These factors include fast foods, such as increased intake of beverages that are sweetened, snacking, taking huge portion sizes, eating less nutritious foods and advertising of fast foods. In reference to inadequate physical activities are increased use of media, such as video games and television and lack of physical activities at home. The Food Research and Action Center is an accredited organization, thus making the information credible and reliable.
  • 53. The information is timely because it relies on the most current research. Assessment: The article will help in providing insight on the physical inactivity and fast foods as major contributors/causes of obesity. This also goes for refuting that obesity occurs naturally and lack of physical inactivity and fast foods do es not contribute to obesity. Larson, A. A. (2012). Childhood obesity in USA: A descriptive snapshot of current responses disconnects, and what could hold promise for additional mitigation. Movement & Sport Sciences, 78, 61-74. Retrieved from http://www.mov-sport- sciences.org/articles/sm/abs/2012/04/sm120016/sm120016.html This journal article examines the important importance of physical activities in management of weight and as an obesity intervention. The article also discussed the failure of schools in providing comprehensive durations that allow for sufficient physical activity engagement. Even though interscholastic athletics tend to provide children with options for physical activities, populations needing the activities, such as those at risk of obesity or who are obese, are always underrepresented. The article has been reviewed by a panel of experts for it to be included in the Science & Motricité journal, thus meeting academic standards of providing reliable and credible information. It is timely because it was published n year 2012, thus offering up-to-date information regarding childhood obesity. Assessment: In reference to the childhood obesity topic, the information in this article provides insight on the sedentary lifestyle (physical inactivity), as a major cause of obesity. In addition, the fact that schools are unable to fully engage children in physical activities supports the need for parents to take over the role in controlling obesity by breaking the sedentary lifestyle cycle. Lindsay, A. C., Sussner, K. M., Kim, J., & Gortmaker, S. (2006). The role of parents in preventing childhood obesity. The Future of Children,16 (1), 169-186. Retrieved from
  • 54. http://futureofchildren.org/futureofchildren/publications/docs/1 6_01_08.pdf This article reviews evidence pertaining to how parents could help children maintain and develop physical activity habits and healthful eating, thus helping revert and prevent obesity and overweight during childhood. Particularly, studies focusing on child growth and nutrition details ways that parents influence children’s development of activity-related and food- related behaviors to examine the role of parents in curtailing children obesity. As a journal article in The Future of Children, it is reviewed by a panel of experts, thus making it reliable and credible. Although not relatively current, as it was published in year 2006, the article is still crucial in providing insight on the strategies parent could employ to control obesity by breaking the cycle of sedentary and fast food based lifestyle. Assessment: The article provides insight on solution for children’s obesity epidemic. This relates to the critical role parents play in preventing and reverting obesity. This also goes for the strategies they could use in controlling obesity by breaking the cycle of sedentary and fast food based lifestyle. Zhao, J., & Grant, S. F. A. (2011). Genetics of childhood obesity. Journal of Obesity, (2011), 1-9. Doi:10.1155/2011/845148. Retrieved from http://www.hindawi.com/journals/jobe/2011/845148/cta/ This article explores the genetic factors that contribute to obesity. The article also makes it clear that Genomegenome- wide associations reveal a strong association of most disorders with genomic variants. The research conducted in this article shows that the loci that researchers had previously discovered to contribute to obesity also contributes to childhood obesity by increasing children’s BMI. The article is included in a journal, Journal of Obesity, which nocomprise of a panel of experts that review the credibility and reliability of articles. The journal article is no, it is not timeless timeless, as it comprises the latest research regarding the natural causes of childhood obesity.
  • 55. Assessment: This article provides insight on why some people may refute the idea that lifestyle factors, such as fast food and sedentary lifestyle, contribute to obesity. This is because they are likely to believe that developing obesity is inherent in a person’s genes. Alphabetized (10 pts.): 10 Quality and relevance of sources (10): 10 Grammar/mechanics (20 pts.): 5 Sentences (20 pts.): 20 Word Choice (10 pts.): 7 APA format (30 pts.): 28 Total points (100 pts.): 80 I marked almost 2 dozen mechanical errors in this paper— letters left off words, commas, subject/verb agreement, capitalization, and other things. As I told you, I have to mark all that stuff and you lose points each time I do. This could have been an A if you had had it proofread carefully. The Course Project will address a topic within one of four course themes: education, technology, family, or health and wellness. Each topic encompasses the potential for controversy, which means there is more than one valid way of looking at the issue and presenting the issue to an audience. The paper will introduce the topic, provide background information, present a main argument with evidence, and conclude in a way that clearly leads a reader to take desired or recommended action. Assignment After thoroughly reading and researching a topic, complete the weekly assignments addressing a topic from one of the course themes, leading to two drafts that are revised in a final 8- to 10- page research project. The purpose of the assignment is to present an argument and support it persuasively with relevant, properly attributed source
  • 56. material. The primary audience for the project will be determined in prewriting tasks. The secondary audience is an academic audience that includes your professor and fellow classmates. Course assignments will help you develop your interest in a theme and topic, engage in discussion with your professor and classmates, and then learn to apply search strategies to retrieve quality sources. By the end of the course, you will submit a Course Project that meets the requirements for scope and which includes the following content areas. I. Introduction a. Attention-getting hook b. Topic, purpose, and thesis c. Background d. Relevance to reader II. Body Logically presented, point-by-point argument with evidence (the number of sections may differ by paper, but you should plan to have at least three) a. Section 1 (2–5 paragraphs) b. Section 2 (2–5 paragraphs) c. Section 3 (2–5 paragraphs) d. Section 4 (2–5 paragraphs) e. Section 5 (2–5 paragraphs) III. Conclusion Assignment Requirements PLEASE [email protected]@@@@@@@@@@@@@@@@@@@@@@ @ · Original writing of 8–10 pages created during this course · Attributed support from outside research with in-text citations that correspond to the five required sources listed on the References page; a minimum of one source must be included from the Course Theme Reading List
  • 57. · APA 6th edition use of Title page and running headers, in-text and parenthetical citations, and References for all sources used in the project · Final draft addresses all professor and peer content and citation revision suggestions and concerns from earlier drafts; final draft of the Course Project is the result of revision and represents consistent improvement over the first draft Research Project Topics Course Theme Reading List Research on your topics begins with the Course Theme Reading List, which is linked under the Textbook section of the Course Syllabus. Be sure to click the word here to open the document. While you are not required to read all of the resources, you should plan to dedicate sufficient time to retrieve, preview, and critically analyze sources on topics that are of interest to you. The list of readings has been selected to help you narrow a topic, and it also will help you generate search terms you can use to continue your independent research. Two readings are available for each of the topics listed below. Start your research process by reviewing the Course Theme Reading List. Note: All students will be required in their final Course Project to include at least one source from the Course Theme Reading List. Once you are introduced to library search strategies, you will then search for the remaining number of sources required for inclusion in-text and on the References page of the final assignment. The table below lists the themes and topics for the Course Project. Education Technology Family Health and Wellness School Bullies Multitasking and Technology Sexualization of Girls College Students and Weight Issues No Child Left Behind Act/Race to the Top
  • 58. Technology and Social Isolation Gender Discrimination Childhood Obesity Grade Inflation Perils of Social Networking Unequal Rights in Marriage, Children Fad Diets College Students and Underage Drinking Online Dating/Online Predators/Sex Offenders Children of Divorce Junk Food Student Debt Illegal Downloading of Protected Content Domestic Violence Sedentary Lifestyles College Students, Cheating, and Plagiarism Internet Censorship/Classified Information Leaks Cyberbullying Teenage Pregnancy College Dropout Rates Identity Theft Life-Work (Im)balance/Flexible Work Schedules Concussions in Athletes High School Dropouts Texting and Driving Insurance Premiums for Smokers and Obese Employees The full list of Course Theme Readings is linked from the Course Syllabus. To access the readings, you will use the library databases or the Course textbook. For help accessing the library databases, please click on the following Accessing the DeVry Library Database tutorial. Grading Rubrics Back to Top
  • 59. Central Idea and Focus: The topic, purpose, and thesis are clear and identifiable in the introduction; all ideas consistently address the main argument without off-topic or irrelevant ideas. Presentation of central idea or focus reflects revision and refinement from prior drafts. Support and development of ideas: Ideas are sufficiently developed for each section. Fifteen points may be earned for each of the five sections of the document. Introduction must have attention-grabbing story, topic, purpose, credibility, and why the topic is important; the thesis is graded above in the central idea. Sections II, III, and IV must contain a main idea, indicated by a topic sentence and followed by properly attributed support from sources. Development of ideas anticipates reader objections and responds appropriately. Evidence is varied and effective. Uses argumentative strategies and appeals to improve the logic and credibility of the presented ideas. Conclusion contains memorable ideas and does not rely on repetition of earlier content. Body of project reflects improvement from earlier drafts or else points will be deducted from each section accordingly. Organization and Structure: The internal structure of a piece of writing, the thread of central meaning. All ideas are organized well without any missing or incomplete components. Organization responds to feedback on earlier drafts and presents an improved version from prior drafts. Points are deducted for organization that has not been revised based on feedback. Formatting, including use of APA: Correct title page, headers, second page title, margins, alignment, spacing, font, and size (5 points). In-text citations and end-text References match and demonstrate proficient use of APA style, errors in in-text citations, or lack of in-text citations (10 points). References page with a minimum of five sources correctly cited, match the in-text citation, and use of citations demonstrates improvement from early to final drafts (15 points). Formatting and layout: Use of appropriate layout, including headings and effective use
  • 60. of images, graphs, and charts that are effectively labeled and integrated into the body of the report (10 points). Grammar, Mechanics, and Style:Grammar refers to correctness of language usage; mechanics refers to conventional correctness in capitalization, punctuation, and spelling. Style includes word choice, sentence variety, clarity, and conciseness. Also, sentences vary in length and structure; ideas are clear, logical, and concise. Style is persuasive and authentic to the topic and purpose. Milestones Back to Top PLEASE FOLLOW THE FOLLOWING SCHEDULE FOR THE PROJECT.. THANKS Week 1: Topic Selection (50 points) Week 2: Source Summary (100 points) Week 3: Research Proposal (50 points) Week 4: Annotated Bibliography (100 points) Week 5: First Draft (75 points) ………………………DUE THIS WEEK 4/2/2015 Week 6: Second Draft (80 points)……………………DUE NEXT WEEK BY 4/09/2015 Week 7: Final Draft (125 points)…………………….DUE ON 4/16/2015 Week 8: Reflective Postscript (50 points)……………DUE ON 4/23/2015 Best Practices Back to Top · Access the DeVry Library resources for the bulk of your research. You can access the online library by clicking on the Student Resources tab in Course Home. · APA-style citations do not use footnotes or URLs (i.e., http:// or www.) for in-text citations. URLs are in the References page as specified in the textbook or APA manual. Use of Turnitin is part of this class. Avoid all forms of
  • 61. plagiarism. Plagiarism is a serious offense and violates our academic integrity policy. Do not use any information from “paper mills,” or sites that offer papers on a number of topics; these sites are among the first to be flagged as plagiarized. Additionally, do not turn in any paper previously used in any course, because self-plagiarism is also not allowed. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Chapter 3 Selections © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * 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?
  • 62. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * ObjectivesTo declare bool variables and write Boolean expressions using relational operators (§3.2).To implement selection control using one-way if statements (§3.3).To program using one-way if statements (GuessBirthday) (§3.4).To implement selection control using two-way if statements (§3.5).To implement selection control using nested if and multi- way if-else statements (§3.6).To avoid common errors and pitfalls 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.9).To combine conditions using logical operators (&&, ||, and !) (§3.10).To program using selection statements with combined conditions (LeapYear, Lottery) (§§3.11–3.12).To implement selection control using switch statements (§3.13).To write expressions using the conditional operator (§3.14).To examine the rules governing operator precedence and operator associativity (§3.15).To debug errors (§3.16). © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * 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.
  • 63. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Relational 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
  • 64. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * One-way if Statements if (booleanExpression) { statement(s); } if (radius >= 0) { area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius << " is " << area; } Boolean Expression true
  • 65. Statement(s) false false area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius << " is " << area; true (radius >= 0) (a)
  • 66. (b) © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Note (a) if ((i > 0) && (i < 10)) { cout << "i is an " << "integer between 0 and 10";
  • 67. } if ((i > 0) && (i < 10)) cout << "i is an " << "integer between 0 and 10"; Equivalent Braces can be omitted if the block contains a single statement (b) Outer parentheses required © Copyright 2013 by Pearson Education, Inc. All Rights
  • 68. Reserved. * Examples Listing 3.1 gives a program that checks whether a number is even or odd. The program prompts the user to enter an integer (line 9) and displays “number is even” if it is even (lines 11-12) and “number is odd” if it is odd (lines 14-15). TestBoolean Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Caution Adding a semicolon at the end of an if clause is a common mistake. This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. (a) if (radius >= 0);
  • 69. { area = radius * radius * PI; cout << "The area " << " is " << area; } if (radius >= 0) { }; { area = radius * radius * PI; cout << "The area " << " is " << area; }
  • 70. Equivalent Empty Body (b) Logic Error © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Lab #1 – Hand In C++ Program Write a program that accepts as input first one integer into a variable named intValue1. Next input a character into a variable named chrValue1. If the intValue1 is even, then output to the screen “Integer is even”. If the chrValue1 is greater than ‘G’, then output to the screen
  • 71. “Character is greater than G”. Make sure you contain at least 2 comments Variables are named correctly The use of the if statement is done twice © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * The if...else Statement if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } false Boolean
  • 72. Expression Statement(s) for the true case true Statement(s) for the false case © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Nested if Statements if (i > k) { if (j > k) cout << "i and j are greater than k"; } else cout << "i is less than or equal to k";
  • 73. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Multiple Alternative if Statements (a) if (score >= 90.0) cout << "Grade is A"; else if (score >= 80.0) cout << "Grade is B"; else if (score >= 70.0) cout << "Grade is C";
  • 74. else if (score >= 60.0) cout << "Grade is D"; else cout << "Grade is F"; (b) Equivalent This is better if (score >= 90.0)
  • 75. cout << "Grade is A"; else if (score >= 80.0) cout << "Grade is B"; else if (score >= 70.0) cout << "Grade is C"; else if (score >= 60.0) cout << "Grade is D"; else cout << "Grade is F";
  • 76. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace if-else statement if (score >= 90.0) cout << “Grade is A"; else if (score >= 80.0) cout << “Grade is B"; else if (score >= 70.0) cout << “Grade is C"; else if (score >= 60.0) cout << “Grade is D"; else cout << “Grade is F"; Suppose score is 70.0 The condition is false animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace if-else statement if (score >= 90.0) cout << “Grade is A"; else if (score >= 80.0) cout << “Grade is B"; else if (score >= 70.0) cout << “Grade is C"; else if (score >= 60.0) cout << “Grade is D";
  • 77. else cout << “Grade is F"; Suppose score is 70.0 The condition is false animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace if-else statement if (score >= 90.0) cout << “Grade is A"; else if (score >= 80.0) cout << “Grade is B"; else if (score >= 70.0) cout << “Grade is C"; else if (score >= 60.0) cout << “Grade is D"; else cout << “Grade is F"; Suppose score is 70.0 The condition is true animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace if-else statement
  • 78. if (score >= 90.0) cout << “Grade is A"; else if (score >= 80.0) cout << “Grade is B"; else if (score >= 70.0) cout << “Grade is C"; else if (score >= 60.0) cout << “Grade is D"; else cout << “Grade is F"; Suppose score is 70.0 grade is C animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace if-else statement if (score >= 90.0) cout << “Grade is A"; else if (score >= 80.0) cout << “Grade is B"; else if (score >= 70.0) cout << “Grade is C"; else if (score >= 60.0) cout << “Grade is D"; else cout << “Grade is F"; Suppose score is 70.0
  • 79. Exit the if statement animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Note The else clause matches the most recent if clause in the same block. (a) int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) cout << "A";
  • 80. else cout << "B"; (b) Equivalent int i = 1; int j = 2; int k = 3; if (i > j) if (i > k)
  • 81. cout << "A"; else cout << "B"; This is better with correct indentation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k)
  • 82. cout << "A"; } else cout << "B"; This statement prints B. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * TIP (a) if (number % 2 == 0) even = true; else even = false;
  • 83. (b) Equivalent This is better bool even = number % 2 == 0; © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * CAUTION
  • 84. (a) if (even == true) cout <<"It is even."; (b) Equivalent if (even) cout << "It is even.";
  • 85. This is better © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Common Errors in Selection Statements Common Error 1: Forgetting Necessary Braces (a) Wrong if (radius >= 0) area = radius * radius * PI; cout << "The area "
  • 86. << " is " << area; if (radius >= 0) { area = radius * radius * PI; cout << "The area " << " is " << area; } (b) Correct
  • 87. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Common Errors in Selection Statements Common Error 2: Wrong Semicolon at the if Line (a) if (radius >= 0); { area = radius * radius * PI; cout << "The area " << " is " << area;
  • 88. } if (radius >= 0) { }; { area = radius * radius * PI; cout << "The area " << " is " << area; } Equivalent Empty Body (b)
  • 89. Logic Error © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Common Errors in Selection Statements Common Error 3: Mistakenly Using = for == if (count = 1) cout << "count is zero" << endl; else cout << "count is not zero" << endl; © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Common Errors in Selection Statements
  • 90. Common Error 4: Redundant Testing of Boolean Values (a) if (even == true) cout <<"It is even."; (b) Equivalent if (even)
  • 91. cout << "It is even."; This is better © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Problem: Body Mass Index Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows: ComputeBMI
  • 92. BMI Interpretation below 16 serious underweight underweight normal weight overweight 29-35 seriously overweight above 35 gravely overweight © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Example: Computing Taxes
  • 93. The US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2002 are shown in Table 3.6. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Example: Computing Taxes, cont. ComputeTax if (status == 0) { // Compute tax for single filers } else if (status == 1) { // Compute tax for married file jointly } else if (status == 2) { // Compute tax for married file separately } else if (status == 3) { // Compute tax for head of household } else { // Display wrong status }
  • 94. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Example: A Simple Math Learning Tool SubtractionQuiz Run This example creates a program for a first grader to practice subtractions. The program randomly generates two single-digit integers number1 and number2 with number1 >= number2 and displays a question such as “What is 9 – 2?” to the student, as shown in the sample output. After the student types the answer, the program displays a message to indicate whether the answer is correct. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. C++ Programming: From Problem Analysis to Program Design, Fourth Edition * Lab #2 – Hand In C++ Program Write a program that accepts as input first one integer into a variable named intValue1. Accept a second integer from input into a variable named intValue2. If the intValue1 is even, then output to the screen “Value 1 is even”, otherwise say “Value 1 is odd”.
  • 95. If the intValue2 is even, then output to the screen “Value 2 is even”, otherwise say “Value 2 is odd”. If intValue2 is greater than intValue1, than output to the screen “Value2 is greater than Value1” and then also output another line saying “If part is true”, otherwise output to the screen “Value1 is greater than Value2” and then also output another line saying “else part is true”. Make sure you contain at least 2 comments Variables are named correctly The use of the if-else statement is used 3 times. C++ Programming: From Problem Analysis to Program Design, Fourth Edition © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Logical Operators Operator Name Description ! not logical negation
  • 96. && and logical conjunction || or logical disjunction © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Truth Table for Operator !
  • 97. p !p true false false true Example (assume age = 24, weight = 140) !(age > 18) is false, because (age > 18) is true. !( weight == 150) is true, because (weight == 150) is false. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Truth Table for Operator &&
  • 98. Example (assume age = 24, weight = 140) (age > 28) && (weight < 140) is false, because (age > 28) and (weight < 140) are both false. (age > 18) && (weight >= 140) is true, because both (age > 18) and (weight >= 140) are true. p1 p2 p1 && p2 false false false false true false true false false true true true
  • 99. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Truth Table for Operator || Example (assume age = 24, weight = 140) (age > 34) || (weight < 140) is false, because both (age > 34) and (weight < 140) are false. (age > 18) || (weight >= 150) is false, because (age > 18) is true. p1 p2 p1 || p2 false false false
  • 100. false true true true false true true true true © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Examples Listing 3.3 gives 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: TestBooleanOperators Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Short-Circuit Operator
  • 101. When evaluating p1 && p2, C++ first evaluates p1 and then evaluates p2 if p1 is true; if p1 is false, it does not evaluate p2. When evaluating p1 || p2, C++ first evaluates p1 and then evaluates p2 if p1 is false; if p1 is true, it does not evaluate p2. Therefore, && is referred to as the conditional or short-circuit AND operator, and || is referred to as the conditional or short- circuit OR operator. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * 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) LeapYear Run © Copyright 2013 by Pearson Education, Inc. All Rights Reserved.
  • 102. * Problem: Lottery Randomly generates a lottery of a two-digit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule: LotteryIf the user input matches the lottery in exact order, the award is $10,000.If the user input matches the lottery, the award is $3,000.If one digit in the user input matches a digit in the lottery, the award is $1,000. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. C++ Programming: From Problem Analysis to Program Design, Fourth Edition * Lab #3 – Hand In C++ Program Write a program that accepts as input first one integer into a variable named intValue1. Accept a second integer from input into a variable named intValue2. If the intValue1 is even, then output to the screen “Value 1 is even”. If intValue1 is not even, then test to see if the intValue2 is even, then output to the screen “Value 2 is even”, otherwise say “Both values is odd”. Make sure you contain at least 2 comments
  • 103. Variables are named correctly The use of the if-else statement is used 3 times. C++ Programming: From Problem Analysis to Program Design, Fourth Edition © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: cout << "Errors: invalid status“ << endl; } © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * switch Statement Flow Chart status is 0
  • 104. Compute tax for single filers break Compute tax for married file separately break Compute tax for married file jointly status is 1 status is 2 break Compute tax for married file separatly
  • 105. status is 3 break Compute tax for head of household default Next Statement Default actions © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break;
  • 106. case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; …
  • 107. case valueN: statement(s)N; break; default: statement(s)-for-default; } When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch- expression. © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace switch statement switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; } Suppose day is 3: animation © Copyright 2013 by Pearson Education, Inc. All Rights
  • 108. Reserved. * Trace switch statement switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; } Suppose day is 3: animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace switch statement switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; }
  • 109. Suppose day is 3: animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace switch statement switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; } Suppose day is 3: animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Trace switch statement switch (day) { case 1: // Fall to through to the next case case 2: // Fall to through to the next case
  • 110. case 3: // Fall to through to the next case case 4: // Fall to through to the next case case 5: cout << "Weekday"; break; case 0: // Fall to through to the next case case 6: cout << "Weekend"; } Suppose day is 3: animation © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Problem: Chinese Zodiac Write a program that prompts the user to enter a year and displays the animal for the year. ChineseZodiac rabbit tiger ox
  • 112. 0: monkey 1: rooster 2: dog 3: pig 4: rat 5: ox 6: tiger 7: rabbit 8: dragon 9: snake 10: horse 11: sheep
  • 113. year % 12 = © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; (booleanExpression) ? expression1 : expression2 Ternary operator Binary operator Unary operator © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. *
  • 114. Conditional Operator cout << ((num % 2 == 0) ? "num is even" : "num is odd"); © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Conditional Operator, cont. (booleanExp) ? exp1 : exp2 © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. C++ Programming: From Problem Analysis to Program Design, Fourth Edition * Lab #4 – Hand In C++ Program Write a program that accepts as input a character variable called chrValue1. If chrValue1 is ‘G’ or ‘g’ then write out to the screen “You entered a g”, if chrValue1 is ‘T’ or ‘t’ then write out to the screen “You entered a t”, if chrValue1 is ‘P’ or ‘p’ then write out to the screen “You entered a p”, otherwise output “You tricked me”. Make sure you contain at least 3 comments Variables are named correctly Make sure that you use the switch statement and do not use any if statements. C++ Programming: From Problem Analysis to Program Design,
  • 115. Fourth Edition © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Operator Precedence How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1? © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Operator Precedencevar++, var--+, - (Unary plus and minus), ++var,--var(type) Casting! (Not)*, /, % (Multiplication, division, and remainder)+, - (Binary addition and subtraction)<, <=, >, >= (Comparison)==, !=; (Equality) && (Conditional AND) Short-circuit AND|| (Conditional OR) Short-circuit OR=, +=, -=, *=, /=, %= (Assignment operator) © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Enumerated Types enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}; Once a type is defined, you can declare a variable of that type: Day day; The variable day can hold one of the values defined in the
  • 116. enumerated type. For example, the following statement assigns enumerated value MONDAY to variable day: day = MONDAY; Companion Website © Copyright 2013 by Pearson Education, Inc. All Rights Reserved. * Enumerated Types As with any other type, you can declare and initialize a variable in one statement: Day day = MONDAY; Furthermore, C++ allows you to declare an enumerated type and variable in one statement. For example, enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY} day = MONDAY; TestEnumeratedType Run Companion Website Operator Name Example Result
  • 117. < 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 Boolean Expression true Statement(s) false (radius >= 0) true area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius <<
  • 118. " is " << area ; false ( a ) ( b ) if ( (i > 0 ) && (i < 10 ) ) { cout << "i is an " << "integer between 0 and 10"
  • 119. ; } ( a) Equivalent (b) if ( (i > 0 ) && (i < 10 ) ) cout << "i is an " << "integer between 0 and 10" ; Outer parentheses required Braces can be omitted if the block contains a single
  • 120. statement if (radius >= 0 ) ; { area = radius * radius * PI; cout << "The area " << " is " << area; } (a ) Equivalent Logic Error
  • 121. if (radius >= 0 ) { } ; { area = radius * radius * PI; cout << "The area " << " is " << area; } (b) Empty Body Boolean Expression
  • 122. false true Statement(s) for the false case Statement(s) for the true case if (score >= 90.0 ) cout << "Grade is A " ; else if (score >= 80.0 ) cout << "Grade is B" ; else
  • 123. if (score >= 70.0 ) cout << "Grade is C" ; else if (score >= 60.0 ) cout << "Grade is D" ; else cout << "Grade is F"
  • 124. ; (a ) Equivalent if (score >= 90.0 ) cout << "Grade is A " ; else if (score >= 80.0 ) cout << "Grade is B" ; else if (score >=
  • 125. 70.0 ) cout << "Grade is C" ; else if (score >= 60.0 ) cout << "Grade is D" ; else cou t << "Grade is F" ; (b )
  • 126. This is better int i = 1 ; int j = 2 ; int k = 3 ; if (i > j) if (i > k) cout << "A" ; else
  • 128. if (i > k) cout << "A" ; else cout << "B" ; This i s better with correct indentation if (number % 2 == 0
  • 130. ) This is better if (even == true ) cout << "It is even." ; ( a ) Equivalent if (even) cout << "It is even." ;
  • 131. (b) This is better if (radius >= 0 ) area = radius * radius * PI; cout << "The area " << " is " << area; (a ) Wrong if (radius >= 0 )
  • 132. { area = radius * radius * PI; cout << "The area " << " is " << area; } (b) Correct Run BMI Interpretation below 16 serious underweight
  • 133. 16 - 18 underweight 18 - 24 normal weight 24 - 29 o verweight 29 - 3 5 seriously overweight above 35 gravely overweight Operator Name Description ! not logical negation
  • 134. && and logical conjunction || or logical disjunction p !p true false false true Example ( assume age = 24, weight = 140 ) !( age > 18 ) is false , because ( age > 18 ) is true . !( weight =
  • 135. = 150 ) is true , because ( weight = = 150 ) is false . p1 p2 p1 && p2 false false false false true false true false false true true true Example (assume age = 24, weight = 140 ) ( age
  • 136. > 2 8 ) && ( weight < 140 ) is false , because (age > 2 8) and ( weight < 140 ) are bo th false . (age > 18) && ( weight > = 140 )
  • 137. is true , because both (age > 18) and ( weight > = 140 ) are true . p1 p2 p1 || p2 false false false false true true true false true true true true Example (assume age = 24, weight = 140 ) (age > 34) || ( weight < 140
  • 138. ) is false , because both (age > 34) and ( weight < 140 ) are false . (age > 18 ) || ( weight >= 1 5 0 ) is false , because (age > 18 )
  • 139. is true . status is 0 Compute tax for single filers break Compute tax for married file jointly break status is 1 Compute tax for married file separatly break status is 2 Compute tax for head of household break st atus is 3 Default actions default Next Statement
  • 141. 5 : ox 6 : tiger 7 : rabbit 8 : dragon 9 : snake 10 : horse 11: sheep year % 12 =