Solutions (Odd Numbered)
Solutions (Odd Numbered)
Solutions (Odd Numbered)
15. To find the price per square inch, first we need to find the area of the
pizza. Then we divide the price of the pizza by the area of the pizza.
Let radius denote the radius and area denote the area of the circle,
and price denote the price of pizza. Also, let pricePerSquareInch
denote the price per square inch.
a. Get radius
b. area = p * radius * radius
c. Get price
d. pricePerSquareInch = price / area
17. Suppose that radius denotes radius of the sphere, volume denotes
volume of the sphere, and surfaceArea denotes the surface area
of the sphere. The following algorithm computes the volume and
surface area of the sphere.
Algorithm C++ Instruction (Code)
1. Get the radius. cin >> radius;
2. Calculate the volume. volume = (4.0 / 3.0) * 3.1416 *
radius * radius * radius;
3. Calculate the surface area. surfaceArea = 4.0 * 3.1416 * radius *
radius;
19. Suppose that billingAmount denotes the total billing amount,
numOfItemsOrdered denotes the number of items ordered,
shippingAndHandlingFee denotes the shipping and handling fee,
and price denotes the price of an item. The following algorithm
computes and outputs the billing amount.
a. Enter the number of items bought.
b. Get numOfItemsOrdered
c. billingAmount = 0.0;
d. shippingAndHandlingFee = 0.0;
e. Repeat the following for each item bought.
i. Enter the price of the item
ii. Get price
iii. billingAmount = billingAmount + price;
f. if billingAmount < 200
shippingAndHandlingFee = 10 * numOfItemsOrdered;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 1 | 1371
21. Suppose x1 and x2 are the real roots of the quadratic equation.
a. Get a
b. Get b
c. Get c
d. if (b * b – 4 * a * c < 0)
Print "The equation has no real roots."
Otherwise
{
temp = b * b – 4 * a * c;
x1 = (–b + temp) / (2 * a);
x2 = (–b – temp) / (2 * a);
}
23. Suppose averageTestScore denotes the average test score,
ighestScore denotes the highest test score, testScore denotes a
h
test score, sum denotes the sum of all the test scores, count denotes
the number of students in class, and studentName denotes the name
of a student.
a. First you design an algorithm to find the average test score. To
find the average test score, first you need to count the number
of students in the class and add the test score of each student.
You then divide the sum by count to find the average test score.
The algorithm to find the average test score is as follows:
i. Set sum and count to 0.
ii. Repeat the following for each student in class.
1. Get testScore
2. Increment count and update the value of sum by a dding
the current test score to sum.
iii. Use the following formula to find the average test score.
if (count is 0)
averageTestScore = 0;
otherwise
averageTestScore = sum / count;
b. The following algorithm determines and prints the names of
all the students whose test score is below the average test score.
Repeat the following for each student in class:
i. Get studentName and testScore
ii. if (testScore is less than averageTestScore)
print studentName
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1372 | APPENDIX I: Answers to Odd-Numbered Exercises
Chapter 2
1. a. false; b. false; c. true; d. true; e. false; f. false;
g. true; h. true; i. false; j. false; k. true; l. false
3. b, e
5. The identifiers quizNo1 and quizno1 are not the same. C++ is case
sensitive. The fifth letter of quizNo1 is uppercase N while the fifth
character of quizno1 is lowercase n. So these identifiers are different.
7. a. 7
b. 5.50
c. −1.00
d. Not possible. Both the operands of the operator % must be inte-
gers. y + z is of type double. Both operands, y + z and x, of
% must be integers.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 2 | 1373
e. 13.50
f. 1
g. Not possible. Both the operands of the operator % must be inte-
gers. Because the second operand, z, is a floating-point value,
the expression is invalid.
h. 3.00
9. x = 9, y = 5, z = 3, w = -3
11. a and c are valid.
13. a. 9.0 / 5 * C + 32
b. static_cast<int>('+')
c. static_cast<int>(x + 0.5)
d. str = "C++ Programming is exciting"
e. totalInches = 12 * feet + inches
f. i++, ++i, or i = i + 1;
g. v = 4 / 3 * (3.1416 * r * r * r);
h. s = 2 * (3.1416 * r * r) + 2 * (3.1416 * r) * h;
i. a + (b – c) / d * (e * f – g * h)
j. (–b + (b * b – 4 * a * c)) / (2 * a)
15. x = 101
y = 11
z = 104
w = 159.00
t = 81.50
17. a. 1000
b. 42.50
c. 1.25
d. 11.00
e. 9
f. 88.25
g. −2.00
19. a and c are correct.
21. a. int num1;
int num2;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1374 | APPENDIX I: Answers to Odd-Numbered Exercises
int main()
{
int count, sum;
double x;
count = 1;
sum = count + PRIME;
x = 25.67; // x = 25.67;
newNum = count * 1 + 2; //newNum = count * ONE + 2;
sum++; //(x + sum)++;
sum = sum + count; //sum + count = sum;
x = x + sum * count; // x = x + sum * COUNT;
sum += 3; //sum += 3--;
cout << " count = " << count << ", sum = " << sum
<< ", PRIME = " << PRIME << endl;
return 0;
}
25. An identifier must be declared before it can be used.
27. a. x += 5;
b. x *= 2 * y
c. totalPay += currentPay;
d. z *= (x + 2);
e. y /= x + 5;
29. a b c
a = (b++) + 3; 8 3 und
c = 2 * a + (++b); 8 2 12
b = 2 * (++c) – (a++); 9 -3 11
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 2 | 1375
int main()
{
string employeeID;
string department;
int num;
double salary;
salary = num * X;
return 0;
}
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1376 | APPENDIX I: Answers to Odd-Numbered Exercises
Chapter 3
1. a. true; b. true; c. false; d. false; e. false; f. true;
g. false; h. false; i. true; j. false; k. true
3. a. int1 = 67, int2 = 48, dec1 = 56.5, dec2 = 62.72
b. int1 = 48, int2 = -1, dec1 = 0.5, dec2 = 67
c. int1 = 48, int2 = 62, dec1 = 56.5, dec2 = 67
d. int1 = 56, int2 = 67, dec1 = 0.5, dec2 = 48
e. Input failure: int1 = 56; trying to read the . (period) into int2.
5. a. Samantha 168.5 46
b. Samantha 0.5 168
c. ** 2.7 45
Input failure: Trying to read S into dec, which is a double variable.
The values of dec, num, and str are unchanged.
7. The function pow calculates xy in a program. That is, pow(x, y) = xy.
To use this function the program must include the header file cmath.
9. The manipulator scientific is used to output floating-point num-
bers in scientific format. To use this function the program must
include the header file iomanip.
11. The manipulator setw is used to output the value of an expression
in a specific number of columns. To use this function the program
must include the header file iomanip.
13. iostream
15. The function getline reads until it reaches the end of the current
line. The newline character is also read but not stored in the string
variable.
17. a. name = " Christy Miller", height = 5.4
b. name = " ", height = 5.4
19. #include <iostream>
#include <fstream>
using namespace std;
int main()
{
int num1, num2;
ifstream infile;
ofstream outfile;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 4 | 1377
infile.open("input.dat");
outfile.open("output.dat");
infile.close();
outfile.close();
return 0;
}
21. fstream
23. a. Same as before.
b. The file contains the output produced by the program.
c. The file contains the output produced by the program. The old
contents are erased.
d. The program would prepare the file and store the output in the
file.
25. a. outfile.open("sales.dat ");
b. outfile >> fixed >> showpoint >> setprecision(2);
c. revenue = numOfJuiceBottlesSold * costOfaJuiceBottle;
d. outfile >> numOfJuiceBottlesSold >> " "
>> costOfaJuiceBottle >> " " >> revenue >> endl;
e. outfile.close();
Chapter 4
1. a. false; b. false; c. false; d. false; e. true; f. false;
g. false; h. false; i. false; j. false; k. false
3. a. false; b. true; c. true; d. true;
5. a. x == z: 0
b. y != z - 9: 0
c. x - y == z + 10: 1
d. !(z < w): 1
e. w - y < x - 2 * z: 0
7. a. +--+
b. 12 / 2 != 4 + 1
c. *
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1378 | APPENDIX I: Answers to Odd-Numbered Exercises
d. C++
C++
e. low
high
9. a. ?%!!
b. a b c d
##
c. Flying Coding
11. The value of done is: 0
13. Omit the semicolon after else. The correct statement is:
if (score >= 60)
cout << "Pass" << endl;
else
cout << "Fail" << endl;
15. The correct code is:
if (numOfItemsBought > 10)
shippingCharges = 0.0;
else if (5 <= numOfItemsBought && numOfItemsBought <= 10)
shippingCharges = 3.00 * numOfItemsBought;
else if (0 < numOfItemsBought && numOfItemsBought < 5)
shippingCharges = 7.00 * numOfItemsBought;
17. 20 10
19. if (sale > 20000)
bonus = 0.10
else if (sale > 10000 && sale <= 20000)
bonus = 0.05;
else
bonus = 0.0;
21. a. The output is: Discount = 10%. The semicolon at the end
of the if statement terminates the if statement. So the cout
statement is not part of the if statement. The cout statement
will execute regardless of whether the expression in the if state-
ment evaluates to true or false.
b. The output is: Discount = 10%. The semicolon at the end
of the if statement terminates the if statement. So the cout
statement is not part of the if statement. The cout statement
will execute regardless of whether the expression in the if
statement evaluates to true or false.
23. a. (x == y) ? z = x + y : (x + y) / 2;
b. (hours >= 40.0) ? wages = 40 * 7.50 + 1.5 * 7.5 *
(hours – 40)
: wages = hours * 7.50;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 4 | 1379
int main()
{
int x, y, w, z;
z = 9;
if (z > 10)
{
x = 12;
y = 5;
w = x + y + SECRET;
}
else
{
x = 12;
y = 4;
w = x + y + SECRET;
}
return 0;
}
33. switch (classStanding)
{
case 'f':
dues = 150.00;
break;
case 's':
if (gpa >= 3.75)
dues = 75.00;
else
dues = 120.00;
break;
case 'j':
if (gpa >= 3.75)
dues = 50.00;
else
dues = 100.00;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1380 | APPENDIX I: Answers to Odd-Numbered Exercises
break;
case 'n':
if (gpa >= 3.75)
dues = 25.00;
else
dues = 75.00;
break;
default:
cout << "Invalid class standing code." << endl;
}
Chapter 5
1. a. true; b. false; c. true; d. false; e. true;
f. true; g. true; h. false ; i. false; j. true
3. 40
5. if ch > 'Z' or ch < 'A'
7. Sum = 22
9. temp = 0
11. a. 20 *
b. *
c. 41 70 111 *
d. 27 44 71 *
13. Replace the while loop statement with the following:
while (response == 'Y' || response == 'y')
Replace the cout statement
cout << num1 << " + " << num2 << " = " << (num1 - num2)
<< endl;
with the following:
cout << num1 << " + " << num2 << " = " << (num1 + num2)
<< endl;
15. 2 3 4 5 6
17. 0 3 8 15 24
19. Loop control variable: j
The initialization statement: j = 1;
Loop condition: j <= 10;
Update statement: j++
The statement that updates the value of s: s = s + j * (j – 1);
21. num = 485, y = 15
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 5 | 1381
23. a. *
b. infinite loop
c. infinite loop
d. ****
e. ******
f. ***
25. The relationship between x and y is: 3y = x
Output: x = 19683, y = 10
27. 0 - 24
25 - 49
50 - 74
75 - 99
100 - 124
125 - 149
150 - 174
175 - 200
29. a. both
b. do ... while
c. while
d. while
31. In a pretest loop, the loop condition is evaluated before executing
the body of the loop. In a posttest loop, the loop condition is evalu-
ated after executing the body of the loop. A posttest loop executes
at least once, while a pretest loop may not execute at all.
33. int num;
do
{
cout << "Enter a number less than 20 or greater than 75: ";
cin >> num;
}
while (20 <= num && num <= 75);
35. int i = 0, value = 0;
do
{
if (i % 2 == 0 && i <= 10)
value = value + i * i;
else if (i % 2 == 0 && i > 10)
value = value + i;
else
value = value - i;
i = i + 1;
}
while (i <= 20);
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1382 | APPENDIX I: Answers to Odd-Numbered Exercises
Chapter 6
1. a. false; b. true; c. true; d. true; e. false; f. false; g. true;
h. false; i. true; j. true; k. false; l. false; m. false; n. true
3. a. 18 b. 20.50 c. 87.20 d. 16.00 e. 1717.82 f. 2.80
g. 14.00 h. 11.16 i. 27.00 j. 20.00 k. 19.00 l. -5.00
m. 2.25 n. 4096.00 o. 0.01 p. 3.03
5. a and b
7. a, b, c, d, and e are valid. In f, the second argument in the function call
is missing. In g and h, the function call requires one more argument.
9. a. 2; double
b. 3; int
c. 3; string
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 6 | 1383
d. 2; char
e. The function third requires four actual parameters. The type and
the order of these parameters are: string, string, int, double
f. cout << first(2.5, 7.8) << endl;
g. cout << grade(82.50, 92.50) << endl;
h. cout << third("John", "Blair", 26, 132.5) << endl;
11. bool isWhitespace (char ch)
{
if (isspace(ch))
return true;
else
return false;
}
13. a. (i) 72 (ii) −200
b. The function computes mn, where m and n are the arguments
of the function.
15. a. 385
b. This function computes 1+4+9+16+25+36+49+64+81+100
17. double funcEx17(double x, double y)
{
return pow(x, y) + pow(y, x);
}
19. a. In a void function, a return statement is used without any value
such as return;
b. In a void function, a return statement is used to exit the
function early.
21. a. A variable declared in the heading of a function definition is
called a formal parameter. A variable or expression used in a
function call is called an actual parameter.
b. A value parameter receives a copy of the actual parameter’s
data. A reference parameter receives the address of the actual
parameter.
c. A variable declared within a function or block is called a local
variable. A variable declared outside of every function defini-
tion is called a global variable.
23. void funcEx23(int num)
{
if (num % 2 == 0)
cout << 2 * num << endl;
else
cout << 5 * num << endl;
}
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1384 | APPENDIX I: Answers to Odd-Numbered Exercises
int main()
{
int num1, num2;
__1__ num1 = 6;
_17__ return 0;
}
__5__ d = a + b;
__6__ b = a * d;
__7__ return b;
}
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 7 | 1385
_11__ val1 = x + y;
_12__ val2 = x * y;
_13__ y = val1 + val2;
_14__ cout << val1 << " " << val2 << endl;
}
If the input is 10, the output is:
96
6 4
10 24
34 4
31. void trackVar(double& x, double y, double& z)
{
z = floor(x) + ceil(y);
x = x + z;
y = y - z;
}
33. 3 5
108 0
108 5
35. stVar = 3, u = 3, x = 2
stVar = 9, u = 3, x = 3
stVar = 18, u = 3, x = 4
stVar = 36, u = 3, x = 5
37. a, b, and d are correct.
Chapter 7
1. a. true; b. false; c. true; d. false; e. false; f. true;
g. true; h. true; i. false; j. false
3. Only a and c are valid.
5. flowerType readIn()
{
string str;
flowerType flower = 0;
if (str == "Rose")
flower = ROSE;
else if (str == "Daisy")
flower = DAISY;
else if (str == "Carnation")
flower == CARNATION;
else if (str == "Freesia")
flower = FREESIA;
else if (str == "Gardenia")
flower = GARDENIA;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1386 | APPENDIX I: Answers to Odd-Numbered Exercises
return flower;
}
7. Because there is no name for an anonymous type, you cannot pass
an anonymous type as a parameter to a function and a function can-
not return an anonymous type value. Also, values used in one anon-
ymous type can be used in another anonymous type, but variables of
those types are treated differently.
9. The statement in Lines 1 and 2 should be
#include <iostream> //Line 1
Chapter 8
1. a. true; b. true; c. true; d. false; e. false; f. false;
g. false; h. false; i. true; j. false; k. false; l. false
3. a. This declaration is correct.
b. Array size must be positive. The correct answer is
int testScores[10];
c. This declaration is correct.
d. Array size must be a positive integer not a range. The correct
answer is: int list100[100];
e. gpa is an array of size 50. The expression [50] should be after
gpa. The correct statement is: double gpa[50];
f. LENGTH must be declared as integral, such as int . The correct
statement is: const int LENGTH = 26;
g. This declaration is correct.
5. 0 to 64. first = 0, middle = 32, and last = 64
7. 0.00 1.50 9.00 28.50 66.00
57.00 1.50 30.00 28.50 66.00
9. 1 2 2 4 8 32 224 6944
11. int myList[10];
for (int i = 0; i < 10; i++)
myList[i] = i;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1388 | APPENDIX I: Answers to Odd-Numbered Exercises
d.
string seasons[4] = {
"fall", "winter", "spring",
"summer"};
or
string seasons[] = {
"fall", "winter", "spring",
"summer"};
17. alpha[0] = 3, alpha [1] = 12, alpha [2] = -25, alpha [3] = 72,
alpha [4] = 0.
19. 25 0 10 60 360 600
21. a. Correct.
b. Correct.
c. Incorrect. None of the formal parameters list and sList is of
type double while the actual parameter unitPrice is of type
double. So there will be mismatch data type error.
d. Incorrect. The size of the array ids is 50, so the call should be
printList(ids, 50);
e. Correct.
23. 1 35700.00 714.00
2 96800.00 1936.00
3 55000.00 1100.00
4 72500.00 1450.00
5 87700.00 1754.00
25. list: 810 0 270 180 90
27. 1 3.50 10.70 235.31
2 7.20 6.50 294.05
3 10.50 12.00 791.68
4 9.80 10.50 646.54
5 6.50 8.00 326.73
29. No.
31. 1 0 1 1 1 0 0 1 1
33. No, because during compile time the formal parameter list has no
first and last elements.
35. a. Valid
b. Valid
c. Invalid; the assignment operator is not defined for C-strings.
d. Invalid; the relational operators are not defined for C-strings.
37. a. strcpy(myStr, "Summer Vacation");
b. cout << strlen(yourStr) << endl;
c. strcpy(myStr, yourStr);
d. compare = strcmp(myStr, yourStr);
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 9 | 1389
Chapter 9
1. a. false; b. true; c. false; d. false; e. false; f. false;
g. false; h. true; i. false; j. true; k. true
3. computerType newComputer;
newComputer.manufacturer = "Computer Corporation";
newComputer.modelType = "Desk Top";
newComputer.processorType = "Core I 7";
newComputer.ram = 12;
newComputer.hardDriveSize = 500;
newComputer.yearBuilt = 2016;
newComputer.price = 850.00;
5. if (firstHouse.style == secondHouse.style &&
firstHouse.price == secondHouse.price)
cout << "true" << endl;
else
cout << "false" << endl;
7. fruitType fruit;
fruit.name = "banana";
fruit.color = "yellow";
fruit.fat = 1;
fruit.sugar = 15;
fruit.carbohydrate = 22;
9. Assignment statement and function return value.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1390 | APPENDIX I: Answers to Odd-Numbered Exercises
cout <<
"Number of Players: "
<< sp[i].numberOfPlayers << endl;
cout << "Team Payroll: $" << sp[i].teamPayroll << endl;
cout << "Coach Salary: $" << sp[i].coachSalary << endl;
cout
<< "-----------------------------------" << endl
<< endl;
}
Chapter 10
1. a. false; b. false; c. true; d. false; e. false
3. A constructor has no type. The statements in Line 6 should be
syntaxErrors2(int = 0,
double = 0); //Line 6
Also, replace ; after private with :. Line 7 should be
private: //Line 7
5. The function set must have a return type. A constructor cannot be
constant. Replace : after } with ;. The statements in Lines 4, 6, and
12 should be as follows:
void set(string, int, double); //Line 4
syntaxErrors4() const; //Line 6
}; //Line 12
7. a. void foodType::set(string s, int c, double f, int su,
double cr, double p)
{
name = s;
if (c >= 0)
calories = c;
else
calories = 0;
if (f >= 0)
fat = f;
else
fat = 0;
if (su >= 0)
sugar = su;
else
sugar = 0;
if (cr >= 0)
carbohydrate = cr;
else
carbohydrate = 0;
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1392 | APPENDIX I: Answers to Odd-Numbered Exercises
if (p >= 0)
potassium = p;
else
potassium = 0;
}
b. void foodType::print() const
{
cout << "Name: " << name << endl;
cout << "Calories: " << calories << endl;
cout << "Fat: " << fat << endl;
cout << "Sugar: " << sugar << endl;
cout << "Carbohydrate: " << carbohydrate << endl;
cout << "potassium: " << potassium << endl;
}
c. string foodType::getName() const
{
return name;
}
{
set(s, c, f, su, cr, p);
}
f. fruit2.print();
g. foodType myFruit("Apple ", 52, 0.2, 10, 13.8, 148.0);
9. The functions print, getQuantitiesInStock, getPrice, and
getDiscount are accessors; functions set, setQuantitiesInStock,
updateQuantitiesInStock, setPrice, and setDiscount are
mutators.
11. a. 28; b. 8; c. 1; d. 9
13. a. 14
b. 3
c. The class temporary has only one constructor. Because this is
a constructor with default parameters, it can be used to initial-
ize an object without specifying any parameters. For example,
the following statement creates the object newObject and its
instance variables are initialized to "", 0, and 0, respectively.
temporary newObject;
15. The statement in Line 1 creates object1 and initializes the instance vari-
ables of this object to "", 0, and 0, that is, object1.description = "";,
object1.first = 0.0;, and object1.second = 0.0;. The state-
ment in Line 2 creates object2 and initializes the instance variables
of this object as follows: object2.description = "rectangle";,
object2.first = 3.0;, and object2.second = 5.0;. The statement in
Line 3 creates object3 and initializes the instance variables
of this object as follows: object3.description = "circle";,
object3.first = 6.5;, and object3.second = 0.0;. The state-
ment in Line 4 creates object4 and initializes the instance variables
of this object as follows: object4.description = "cylinder";,
object4.first = 6.0;, and object4.second = 3.5;.
17. There are two built-in operations for class objects: Member access
(.) and assignment (=).
19. 10:17:00
23:59:29
00:00:29
21. a. personType student("Buddy", "Arora");
b. student.print();
c. student.setName("Susan", "Gilbert");
23. A constructor is a member of a class and it executes automatically
when a class object is instantiated and a call to the constructor is
specified in the object declaration. A constructor is included in a class
so that the objects are properly initialized when they are declared.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1394 | APPENDIX I: Answers to Odd-Numbered Exercises
void myClass::printCount()
{
cout << count;
}
void myClass::incrementCount()
{
count++;
}
myClass::myClass(int a)
{
x = a;
}
e. myClass myObject1(5);
f. myClass myObject2(7);
g. The statements in Lines 1 and 2 are valid.
The statement in Line 3 should be: myClass::printCount();
The statement in Line 4 is invalid because the member function printX
is not a static member of the class, and so it cannot be called by using
the name of class.
The statement in Line 5 is invalid because count is a private static
member variable of the class.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 11 | 1395
h. 5
2
2
3
14
3
3
Chapter 11
1. a. false; b. false; c. true; d. true; e. true; f. true;
g. true; h. true; i. false; j. false; k. true
3. Some of the member variables that can be added to the class
mployeeType are as follows: department, salary, employeeCategory
e
(such as supervisor and president), and employeeID. Some of the
member functions are as follows: setInfo, setSalary, getSalary,
setDepartment, getDepartment, setCategory, getCategory, setID,
and getID.
class employeeType: public personType
{
public:
void setInfo(string, string, string, double, string, string);
void setSalary(double);
void setDepartment(string);
void setCategory(string);
void setID(string);
double getSalary() const;
string getDepartment(string) const;
string getCategory() const;
string getID() const;
private:
string department;
double salary;
string employeeCategory;
string employeeID;
};
5. a. The base class is shoe and the derived class is runningShoe.
b. This is private inheritance.
7. Private members of the object newCylinder are xCoordinate,
yCoordinate, radius, and height.
9. Omit the word class before employee. The first statement should be
class hourlyEmployee: public employee
In the third line replace :: with :. This statement should be
public:
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1396 | APPENDIX I: Answers to Odd-Numbered Exercises
#endif #endif
19. In a private inheritance, the public members of the base class
are private members of the derived class. They can be directly
accessed in the derived class. The protected members of the base
class are private members of the derived class. They can be directly
accessed by the member functions (and friend functions) of the
derived class. The private members of the base class are hidden
in the derived class. They cannot be directly accessed in the derived
class. They can be accessed by the member functions (and friend
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 11 | 1397
double base::compute(int n)
{
return n + manipulate(n, n);
}
Chapter 12
1. a. false; b. false; c. false; d. true; e. false; f. true; g. false; h. false;
i. true; j. false; k. true; l. true; m. false; n. true; o. true; p. false;
3. a. To create a pointer, in the variable declaration, operator * is
placed between the data type and the variable name. For exam-
ple the statement int *p; declares p to be a pointer of type int.
b. To dereference a pointer, in an expression, the operator * is
placed to the left of the pointer. For example, if p is a pointer
of type int, the expression cout << *p << endl; outputs the
data stored in the memory space to which p points.
5. *numPtr given the address of the memory location to which numPtr
points, while &numPtr gives the address of numPtr.
7. numPtr = #
(*numPtr)++;
9. 33.8 3.8
33.8 3.8
11. The correct code is:
double *length;
double *width;
cout << "Area: " << (*length) * (*width) << ", ";
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 12 | 1399
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1400 | APPENDIX I: Answers to Odd-Numbered Exercises
35. 5
small: --
x: 2, y = 3
*-*-*-*-*-*-*-*-*-*-*-*
17
small: --
x: 3, y = 5
noSmall--- z: 9
37. Yes.
39. a. Because employeeType is an abstract class, you cannot instan-
tiate an object of this class. Therefore, this statement is illegal.
b. This statement is legal.
c. This statement is legal.
Chapter 13
1. a. true; b. false; c. true; d. false; e. false; f. false; g. false;
h. false; i. true; j. false; k. false; l. true; m. true
3. b
5. A friend function of a class is a nonmember function of the class,
but has access to all the members (public or non-public) of the
class.
7. d; Because the left operand of << is a stream object, which is not of
the user-defined class type.
9. a. One b. Two
11. object1.operator+(object2)
13. a. bool b. bool
15. a. friend strange operator+(
const strange&,
const strange&);
b. friend bool operator==(
const strange&,
const strange&);
c. friend strange operator++(strange&, int);
17. In Line 4, the formal parameter of the function operator+ should
be of type myClass. The correct statement is
myClass operator+(const myClass& obj); //Line 4
19. In Line 3, the return type of the function operator< should be bool.
The correct statement is
friend bool operator<(const mystery& a,
const mystery& b); //Line 3
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 13 | 1401
21. In Lines 3 and 10, the return type of the function operator* should
be findErrors. In Line 3, the type of the objects a and b must be
findErrors. Also since operator* is a friend function of the class,
the name of the class and the scope resolution operator in the head-
ing of the function, in Line 10, are not needed. In Lines 13 and 14,
to access the instance variables of the object a, we need to use the
object a and the dot operator. The correct statements are as follows:
friend findErrors operator*(const findErrors& a,
const findErrors& b); //Line 3
double operator*(const findErrors& a,
const findErrors& b) //Line 10
public:
void setComplex(const double& real, const double& imag);
//set the complex number according to the parameters
//Postcondition: realPart = real; imaginaryPart = imag
private:
double realPart; //variable to store the real part
double imaginaryPart; //variable to store the imaginary part
};
temp.imaginaryPart = -temp.imaginaryPart;
return temp;
}
Chapter 14
1. a. false; b. true; c. true; d. false; e. true; f. false; g. false;
h. true; i. false; j. true; k. false; l. true; m. false;
3. The program will terminate with an error message.
5. At most one.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 14 | 1403
7. The thrown value then may not be accessible in the catch block
exception handling code.
9. The object being thrown can be either a specific object or an anony-
mous object.
11. The cout statement in Line 12 separates the catch block from the
try block. Therefore, the catch block has no associated try block
and the try block has no associated catch block. The catch block in
Line 13 has no parameters. The correct code is:
double salary = 78000; //Line 1
double raise; //Line 2
try //Line 3
{ //Line 4
cout << "Enter the raise: "; //Line 5
cin >> raise; //Line 6
cout << endl; //Line 7
int main()
{
int miles;
try
{
cout << "Enter the miles: ";
cin >> miles;
cout << endl;
if (miles < 5)
throw tornadoException();
else
throw tornadoException(miles);
}
catch (tornadoException tE)
{
cout << tE.what() << endl;
}
return 0;
}
23. A function specifies the exceptions it throws in its heading using the
throw clause.
25. (1) Do nothing; (2) Partially process the exception and throw the
same exception or a new exception; (3) Throw a new exception.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 15 | 1405
Chapter 15
1. a. true; b. true; c. false; d. false; e. false; f. false; g. true;
h. true;
3. A definition in which something is defined in terms of a smaller ver-
sion of itself.
5. Because a base case stops the recursion.
7. a. The statements from Line 3 to Line 6.
b. The statements in Lines 7 and 8.
c. It is a valid call. The value of recFunc(58) is 32.
d. It is a valid call. The value of recFunc(-24) is 24.
e. It is a valid call. The value of recFunc(0) is 0.
9. a. 8 5 2
b. 7
c. 6 3
d. -85
11. a. 4 12 28
b. 5 15 34 72 148
c. 2 8 21 47 98
d. It does not produce any output.
13. a. 0
b. 4
c. 8
d. 162
15. a. 10
b. 21
c. -23
d. 2
e. -56
17. 0 if n = 0
multiply (m,n )= m if n = 1
m 1 multiply (m,n 21) otherwise
Chapter 16
1. a. true; b. false; c. false; d. true;
e. false; f. false; g. false; h. true
if (found)
if (list[loc] == searchItem)
return loc;
else
return -1;
else
return -1;
}
5. List before the first iteration: 50, 36, 78, 40, 4, 28, 90, 62, 22
List after the first iteration: 36, 50, 40, 4, 28, 78, 62, 22, 90
List after the second iteration: 36, 40, 4, 28, 50, 62, 22, 78, 90
List after the third iteration: 36, 4, 28, 40, 50, 22, 62, 78, 90
List after the fourth iteration: 4, 28, 36, 40, 22, 50, 62, 78, 90
List after the fifth iteration: 4, 28, 36, 22, 40, 50, 62, 78, 90
List after the sixth iteration: 4, 28, 22, 36, 40, 50, 62, 78, 90
List after the seventh iteration: 4, 22, 28, 36, 40, 50, 62, 78, 90
List after the eighth iteration: 4, 22, 28, 36, 40, 50, 62, 78, 90
7. 4
9. a. 8, 12, 18, 25, 38, 45, 74, 60, 30
b. 10
11. Bubble sort: 21,121,750; selection sort: 21,121,750; insertion sort:
10,567,374
13. 26
15. a. 6 b. 7 c. 8 d. 7 e. 1 f. 3 g. 8
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 17 | 1407
17. To use a vector object in a program, the program must include the
header file vector.
19. 5 11 24 51 106 217 440
21. a. vector<int> secretList;
b. secretList.push_back(56);
secretList.push_back(28);
secretList.push_back(32);
secretList.push_back(96);
secretList.push_back(75);
c. for (unsigned int i = 0; i < secretList.size(); i++)
cout << secretList[i] << " ";
25. 0 2 6 12 20
Chapter 17
1. a. true; b. false; c. false; d. false; e. false; f. true; g. true;
h. false; i. false; j. true; k. true; l. false; m. false; n. true;
3. nullptr
5. Before deletion the link field of the third node stores the address of
the fourth node. After deletion the link field of the third node will
store the address of the next node (old) fifth node. If there was no
fifth node, after deletion the link field will store the value nullptr.
Therefore, after deleting the fourth node, the link field of the third
node is changed. So a pointer to the third node is needed.
7. a. true; b. true; c. false; d. true; e. true; f. false
9. a. p->link->info = 24;
b. q = current->link;
c. first = first->link;
d. trail = p->link;
e. p = nullptr;
f. temp->link->info = 54;
g. while (first->info != 5)
first
Copyright 2018 Cengage Learning. All Rights = first->link;
Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1408 | APPENDIX I: Answers to Odd-Numbered Exercises
p = head;
while (p != nullptr)
{
cout << p->info << " ";
p = p->link;
}
cout << endl;
The output of this code is: 43 12 72 8
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 18 | 1409
Chapter 18
1. a. true; b. false; c. false; d. true; e. false; f. true; g. false;
h. false; i. true; j. true; k. true; l. false; m. false; n. false;
3. a. 8
b. 7
c. dec = stack.top();
d. stack.pop();
5. 13
32 32 13 16 28
temp = 16
7. secretNum = 226
9. a. 16
b. -4
c. 39
d. 12
e. 15
11. a. x * y + z - t
b. x * (y + z) - w / u
c. (x - y) * (z / u) - (t + s)
d. x * (y - (z + w))
13. 1 16 27 16 5
15. If the stack is nonempty, the statement stack.top(); returns the
top element of the stack and the statement stack.pop(); removes
the top element of the stack.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
1410 | APPENDIX I: Answers to Odd-Numbered Exercises
if (stack.isEmptyStack())
{
cout << "Stack is empty." << endl;
exit(0); //terminate the program
}
temp1 = stack.top();
stack.pop();
if (stack.isEmptyStack())
{
cout << "Stack has only one element." << endl;
exit(0); //terminate the program
}
temp2 = stack.top();
stack.push(temp1);
return temp2;
}
19. a. 4
b. 21
c. ! queue.isEmptyQueue()
d. queue.addQueue("programming")
After the insertion operation the index of the last element is 5.
21. cin >> num;
while (cin)
{
switch (num % 2)
{
case 0:
stack.push(num);
break;
case 1: case -1:
if (num % 3 == 0)
queue.addQueue(num);
else
{
if (!stack.isEmptyStack())
stack.pop();
stack.push(num * num);
}
} //end switch
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Chapter 18 | 1411
while (!s.isEmptyStack())
{
elem = s.top();
s.pop();
q.addQueue(elem);
}
while (!q.isEmptyQueue())
{
elem = q.front();
q.deleteQueue();
s.push(elem);
}
}
33. template <class Type>
int queueType<Type>::queueCount()
{
return count;
}
35. The answer to this question is available at the website accompany-
ing this book.
Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203