100% found this document useful (64 votes)
2K views

C++ Programming From Problem Analysis To Program Design 8th Edition Malik Solutions Manual 1

This document provides the summary of Chapter 1 from the textbook "C++ Programming From Problem Analysis to Program Design 8th Edition" by Malik. It includes sample problems and solutions from the chapter on topics like algorithms, flowcharts, programming process, and basic C++ concepts. It also provides links to purchase the test bank and solution manual for the textbook online.

Uploaded by

kathrin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (64 votes)
2K views

C++ Programming From Problem Analysis To Program Design 8th Edition Malik Solutions Manual 1

This document provides the summary of Chapter 1 from the textbook "C++ Programming From Problem Analysis to Program Design 8th Edition" by Malik. It includes sample problems and solutions from the chapter on topics like algorithms, flowcharts, programming process, and basic C++ concepts. It also provides links to purchase the test bank and solution manual for the textbook online.

Uploaded by

kathrin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

C++ Programming From Problem

Analysis to Program Design 8th


Edition Malik
Full download at link:

Test Bank: https://testbankpack.com/p/test-bank-for-c-


programming-from-problem-analysis-to-program-design-8th-
edition-by-malik-isbn-9781337102087/

Solution Manual: https://testbankpack.com/p/solution-manual-for-


c-programming-from-problem-analysis-to-program-design-8th-
edition-by-malik-isbn-9781337102087/

Chapter 1
1. a. true; b. false; c. false; d. true; e. false; f. true; g. true; h. true; i. false; j. false; k. true; l. true; m. true;
n. true; o. true; p. false; q. true; r. true; s. true
2. CPU.
3. Base 2 or binary.
4. The equivalent machine language program of a high-level language program.
5. In linking, an object program is combined with other programs in the library, used in the program, to
create the executable code.
6. Loader
7. #
8. Preprocessor
9. Programming is a process of problem solving.
10. A step-by-step problem-solving process in which a solution is arrived at in a finite amount of time.
11. (1) Analyze and outline the problem and its solution requirements, and design an algorithm to solve the
problem. (2) Implement the algorithm in a programming language, such as C++, and verify that the
algorithm works. (3) Maintain the program by using and modifying it if the problem domain changes.
12. (1) Thoroughly understand the problem. (2) Understand the problem requirements. (3) If the problem is
complex, divide the problem into subproblems and repeat Steps 1 and 2.
13. To find the weighted average of the four test scores, first you need to know each test score and its
weight. Next, you multiply each test score with its weight, and then add these numbers to get the
average. Therefore,

1
1. Get testScore1, weightTestScore1
2. Get testScore2, weightTestScore2
3. Get testScore3, weightTestScore3
4. Get testScore4, weightTestScore4
5. weightedAverage = testScore1 * weightTestScore1 +
testScore2 * weightTestScore2 +
testScore3 * weightTestScore3 +
testScore4 * weightTestScore4;
14. a. Get quarters
b. Get dimes
c. Get nickels
d. Get pennies
e. changeInPennies = quarters * 25 + dimes * 10 + nickels * 5
+ pennies

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 = π * radius * radius
c. Get price
d. pricePerSquareInch = price / area

16. To determine the least selling price of a car, we need to know the listing price of the car. The algorithm
is as follows:

a. Get listingPrice
b. Calculate the least selling price leastSellingPrice using the formula:
leastSellingPrice = listingPrice × 0.85) + 500

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)

2
1 1. Get the radius. cin >> radius;

2 2. Calculate the volume. volume = (4.0 / 3.0) * 3.1416 * radius * radius *

radius;

3 3. Calculate the surface surfaceArea = 4.0 * 3.1416 * radius * radius;

area.

18. Suppose that billingAmount denotes the total billing amount, movingCost denotes moving cost,
area denotes the area of the yard that needs to be moved, numOfAppl denotes the number of
fertilizing applications, and numOfTrees denotes the number of trees to be planted. The following
algorithm computes and outputs the billing amount.

a. Enter the area of the yard.


b. Get area
c. Enter the number of fertilizing applications.
d. Get numOfAppl
e. Enter the number of trees to be planted.
f. Get numOfTrees
g. Calculate the billingAmount using the formula:
billingAmount = (area / 5000) * 35.00 + numOfAppl * 30.00
+ numOfTrees * 50.00

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;

3
g. billingAmount = billingAmount + shippingAndHandlingFee
i. Print billingAmount

20. Suppose amountWithdrawn denotes the amount to be withdrawn, serviceCharge denotes the
service charges, if any, and accountBalance denotes the total money in the account.
You can now write the algorithm as follows:
a. Get amountWithdrawn.
b. if amountWithdrawn > 500
Print "The maximum amount that can be drawn is $500"
otherwise (if accountBalance <= 0)
Print "Account balance is <= 0. You cannot withdraw any money."
otherwise
{
if (amountWithdrawn > accountBalance)
{
Print "Insufficient balance. If you withdraw, services charges
will be $25.00. Select Yes/No."

if (Yes)
{
if (amountWithdrawn > 300)
serviceCharge = (amountWithdrawn – 300) * 0.04;
otherwise
serviceCharge = 0;

accountBalance = accountBalance – amountWithdrawn


- serviceCharge – 25;
Print "Collect your money. "
}
}
}
otherwise
{
if (amountWithdrawn > 300)
serviceCharge = (amountWithdrawn – 300) * 0.04;
otherwise
serviceCharge = 0;

accountBalance = accountBalance – amountWithdrawn


- serviceCharge;
Print "Collect your money."
}

21. Suppose x1 and x2 are the real roots of the quadratic equation.
a. Get a
b. Get b

4
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);
}

22. Suppose that tuition denotes the tuition per semester, semesterUnits denotes the average
semester units, courseUnits denotes the number of course units, semesterWeeks denotes the
number of weeks in a semester, classDaysPerWeek denotes the number of days a class meets in a
week, classDaysPerSemester denotes the total number of days a class meets in a semester,
costPerUnit denotes the cost of one unit of a course, and costPerClass denotes the cost of one
class.
a. Get tuition
b. Get semesterUnits
c. Get semesterWeeks
d. Get courseUnits
e. Get classDaysPerWeek
f. Compute costPerUnit using the following formula.
costPerUnit = tuition / semesterUnits;
g. Compute classDaysPerSemester using the following formula.
classDaysPerSemester = classDaysPerWeek * semesterWeeks;
h. Compute costPerClass using the following formula.
costPerClass = (costPerUnit * courseUnits) / classDaysPerSemester;
23. Suppose averageTestScore denotes the average test score, highestScore denotes the highest
test score, testScore denotes a 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 adding the current test score to sum.
iii. Use the following formula to find the average test score.
if (count is 0)
averageTestScore = 0;
otherwise

5
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
c. The following algorithm determines the highest test score
i. Get first student’s test score and call it highestTestScore.
ii. Repeat the following for each of the remaining students in the class
1. Get testScore
2. if (testScore is greater than highestTestScore)
highestTestScore = testScore;
d. To print the names of all the students whose test score is the same as the highest test score,
compare the test score of each student with the highest test score and if they are equal print the
name. The following algorithm accomplishes this.
Repeat the following for each student in the class:
i. Get studentName and testScore
ii. if (testScore is equal to highestTestScore)
print studentName

You can use the solutions of the subproblems obtained in parts a to d to design the main algorithm as
follows:
1. Use the algorithm in part a to find the average test score.
2. Use the algorithm in part b to print the names of all the students whose score is below the average
test score.
3. Use the algorithm in part c to find the highest test score.
4. Use the algorithm in part d to print the names of all the students whose test score is the same as the
highest test score

6
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
2. b, d, e, f
3. b, e
4. A keyword is a reserved word and is defined by the system. A keyword cannot be redefined in a
program. A user-defined identifier can be redefined.
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
6 . a. 22
b. 2
c. 14
d. 8
e. 7.00
f. 21
g. 20
h. 0.00
i. 15.50

7. a. 7
b. 5.50
c. -1.00
d. Not possible. Both the operands of the operator % must be integers. y + z is of type double. Both
operands, y + z and x, of %V must be integers.
e. 13.50
f. 1
g. Not possible. Both the operands of the operator % must be integers. Because the second operand, z,
is a floating-point value, the expression is invalid.
h. 3.00

8. a, b, c, e, i, j, and k are valid;


d, f, and g are invalid because the left side of an expression must be a variable. h is invalid because the
operands of the mod operator must be integers.
9. x = 9, y = 5, z = 3, w = -3
10. Variable declarations in Lines 1, 6, and 7 are correct.

7
Variable declaration in Line 2 is incorrect. Now, B+ is a string, so it must be enclosed in double
quotes mark. Also, grade is a char variable and a string cannot be assigned to a char variable. A
correct declaration is:
char grade = 'B'; //Line 2

Variable declaration in Line 3 is incorrect because the left side of the assignment operator must be a
variable, and the semicolon at the end of the statement is missing. A correct declaration is:
double num = 28.5; //Line 3

The variable declaration in Line 4 is incorrect because strings are enclosed in double quotation marks.
A correct declaration is:
string message = "First C++ course"; //Line 4

The variable declaration in Line 5 is incorrect because the value assigned to age must be an int value.
A correct declaration is:
int age = 18; //Line 5

11. a and c are valid


12. a. int x, y;
x = 25;
y = 18;
b. int temp = 10;
char ch = 'A';
c. x = x + 5;
d. double payRate = 12.5;
e. tempNum = firstNum;
f. temp = x;
x = y;
y = temp;
g. cout << x << " " << y << " " << x + 12 / y - 18 << endl;
h. char grade = 'A';
i. int num1, num2, num3, num4;
j. x = static_cast<int>(z + 0.5);

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)

8
j. (–b + (b * b – 4 * a * c)) / (2 * a)

14. x = 1
y = 102
z = 15
w = 44
15. x = 101
y = 11
z = 104
w = 159.00
t = 81.50
16. a. x = 18, y = 5, z = 4
b. 5 * x - y = 85
c. Product of 18 and 4 is 72
d. x - y / z = 17
e. 18 square = 324

17. a. 1000
b. 42.50
c. 1.25
d. 11.00
e. 9
f. 88.25
g. -2.00

18. a. cout << endl; or cout << "\n"; or cout << '\n';
b. cout << "\t";
c. cout << "\"";

19. a and c are correct


20.
a. char grade = '*';
b. double salesTax = 0.05;
c. int numOfJuiceBottles = 0;
d. double billingAmount = 0.0;

9
e. double gpa = 0.0;

10
21. a. int num1;
int num2;
b. cout << "Enter two numbers separated by spaces." << endl;
c. cin >> num1 >> num2;
d. cout << "num1 = " << num1 << ", num2 = " << num2
<< ", 2 * num1 – num2 = " << 2 * num1 – num2 << endl;

22. A correct answer is:


#include <iostream>
#include <string>

using namespace std;

const double DECIMAL = 5.50;


const string blanks = " ";
double PAY_RATE = 10.75;

int main()
{
int height, weight;
double discount;
double billingAmount;
double bonus;
int hoursWorked = 45;
double price;

height = 6;
weight = 156;

cout << height << " " << weight << endl;

discount = (2 * height + weight) % 10;


price = 49.99;

billingAmount = price * (1 - discount) - DECIMAL ;


// DECIMAL = 7.55;

cout << price << blanks << "$" << billingAmount << endl;

bonus = hoursWorked * PAY_RATE / 50;

cout << "Bonus = " << bonus << endl;

return 0;
}

23. A correct answer is:


#include <iostream>

using namespace std;

const char STAR = '*';


const int PRIME = 71;

11
int main()
{
int count, sum;
double x;

int newNum; //declare newNum

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;
}

24. A correct answer is:

#include <iostream>
#include <string>

using namespace std;

int main()
{
int num1, num2;
string str1;

cout << "Enter a string without any blanks in it : ";


cin >> str1;
cout << endl;

cout << "Enter two integers: ";


cin >> num1 >> num2;
cout << endl;

cout << str1 << " "


<< "num1 * num2 = " << num1 * num2 << endl;

return 0;
}

25. An identifier must be declared before it can be used.


26. b.
27. a. x += 5;
b. x *= 2 * y
c. totalPay += currentPay;
d. z *= (x + 2);

12
e. y /= x + 5;

28. a. x = x + 5 – z;
b. y = y * (2 * x + 5 – z);
c. w = w + 2 * z + 4;
d. x = x – (z + y – t);
e. sum = sum + num;
29.
a b c
a = (b++) + 3; 8 3 und
c = 2 * a + (++b); 8 2 12
b = 2 * (++c) – (a++); 9 -3 11

30.
a b c sum
sum = static_cast<int>(a + b + c); 6 3 2.2 11
b += c * a; 6 16 2.2 11
c -= a; 6 16 -3.8 11
a *= 2 * b - c; 214 16 -3.8 11

31. (The user input is shaded.)


firstNum = 62
Enter three numbers: 35 10.5 27

The numbers you entered are 35, 10.5, and 27


z = 33
Enter grade: B

The letter that follows your grade is: C

32. (The user input is shaded.)


Enter last name: Miller

Enter a two digit integer: 34

Enter a decimal number: 62.5

Name: Miller
Id: 34
Mystery number: -5.14286

33.
#include <iostream>
#include <string>

using namespace std;

13
const double X = 13.45;
const int Y = 18;
const char STAR = '*';

int main()
{
string employeeID;
string department;
int num;
double salary;

cout << "Enter employee ID: ";


cin >> employeeID;
cout << endl;

cout << "Enter department: ";


cin >> department;
cout << endl;

cout << "Enter a positive integer less than 80: ";


cin >> num;
cout << endl;

salary = num * X;

cout << "ID: " << employeeID << endl;


cout << "Department " << department << endl;
cout << "Star: " << STAR << endl;
cout << "Wages: $" << salary << endl;
cout << "X = " << X << endl;
cout << "X + Y = " << X + Y << endl;

return 0;
}

34. The program requires four inputs in the following order:


string decimal_number decimal_number integer

14
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
2. a. x = 78, y = 86, z = 18, ch = '#'
b. x = 8, y = 86, z = 18, ch = '7'
c. x = 78, y = 86, z = 18, ch = ' '
d. x = 78, y = 6, z = 18, ch = 8
e. x = 8, y = 86, z = 18, ch = '7'
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.
4. a. x = 38, y = 26, symbol = '2'
b. x = 38, y = 67, symbol = ' '
c. x = 24, y = 38, symbol = '$'
d. x = 67, y = 24, symbol = '3'
e. x = 24, y = 63, symbol = '$'
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.
6. a. int1 = 13, int2 = 4, dec = 16.2, ch = '2'
b. int1 = 45, int2 = 36, dec = 9.2, ch = '$'
c. int1 = 16, input failure, trying to read '.' into int2, which is an int variable.
7. The function pow calculate xy in a program. That is, pow(x, y) = xy. To use this function the
program must include the header file. cmath
8. The function sqrt calculate the square root of a nonnegative real number. To use this function the
program must include the header file cmath.
9. The manipulator scientific is used to output floating-point numbers in scientific format. To use
this function the program must include the header file iomanip.
10. iostream
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.

15
12. 9.00^3.20 = 1131.30
5.0^2.5 = 55.90
sqrt(48.35) = 6.95
static_cast<int>(sqrt(pow(y, 4))) = 10
Length of str = 47

13. iostream

14. a. num = 34, discard = '#'


b. Input failure. After peeking into the input stream, cin tries to input # into num. However, num is
an int variable, so the stream enters the fail state.
c. num = 34, discard = '#'
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.
16. cout << setfill('*') << setw(35) << '*' << endl;
17. a. name = " Christy Miller", height = 5.4
b. name = " ", height = 5.4
18. a. name = "Christy Miller", height = 5.4
b. name = "Christy Miller", height = 5.4
19.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
int num1, num2;
ifstream infile;
ofstream outfile;

infile.open("input.dat");
outfile.open("output.dat");

infile >> num1 >> num2;


outfile << "Sum = " << num1 + num2 << endl;

infile.close();
outfile.close();

return 0;
}

20. Invalid data may cause the input stream to enter the fail state. When an input stream enters the fail
state, all further inputs associated with that input stream are ignored. The program continues to execute
with whatever values the variables have.
21. fstream
22. infile.open("employee.dat ");

16
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.
24. infile >> acctNumber;
infile >> accountType;
infile >> balance;
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();

17
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
2. a. 0 (false) b. 0 (false) c. 1 (true) d. 1 (true)
e. 1 (true) f. 0 (false)
3. a. false; b. true; c. true; d. true;
4. a. false; b. true; c. true; d. false; e. false
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
6. c and e.
7. a. +--+
b. 12 / 2 != 4 + 1
c. *
d. C++
C++
e. low
high

8. b and e
9. a. ?%!!
b. a b c d
##
c. Flying Coding

10. The value of done is: 1


11. The value of done is: 0

12. 28 25
31
1
0
1
0
31 25
13. Omit the semicolon after else. The correct statement is:
if (score >= 60)
cout << "Pass" << endl;

18
else
cout << "Fail" << endl;

14. a.
if (standing == 'F')
cout << << "First Year" << endl;
else if ((standing == 'S')
cout << << "Sophomore" << endl;
else
cout << << "Junior or Senior" << endl;

b.
if (standing == '1' || standing == '2')
cout << << "First Year or Sophomore" << endl;
else if ((standing == '3' || standing == '4')
cout << << "Junior or Senior" << endl;
else
cout << << "Graduate Student" << 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;

16. 27 12 39 -15
17. 20 10
18. a. -10 -20
b. 5 15
19. if (sale > 20000)
bonus = 0.10
else if (sale > 10000 && sale <= 20000)
bonus = 0.05;
else
bonus = 0.0;

20. if (0 < overSpeed && overSpeed <= 5)


fine = 20.00;
else if (5 < overSpeed && overSpeed <= 10)
fine = 75.00;
else if (10 < overSpeed && overSpeed <= 15)
fine = 150.00;
else if (overSpeed > 15)
fine = 150.00 + 20.00 * (overSpeed – 15);

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 statement 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.

19
22. a. (i) The output is: Grade is C. The value of score after the if statement executes is 70.
(ii) The output is: Grade is C. The value of score after the if statement executes is 70.

b. (i) No output. The value of score after the if statement executes is 80.
(ii) The output is: Grade is C. The value of score after the if statement executes is 70.

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;
c. (loanAmount >= 200000) ? closingCosts = 10000 : closingCosts = 8000;
24. a. if (overSpeed > 10)
fine = 200;
else
fine = 75;
b. if (fuel >= 10)
drive = 150;
else
drive = 30;
c. if (bill >= 50.00)
tip = 0.20;
else
tip = 0.10;
25. a. 40.00
b. 40.00
c. 55.00

26. a, c, and d are valid. b is invalid; a case value cannot appear more than once and there should be a
colon after a case value.
27. a. 8 b. 64 c. 1 d. 12
28. a. 2 b. 22 c. -1 d. 9
29. a. 7 b. 12167 c. 8000 d. 3

30. A correct code is:

#include <iostream>

using namespace std;

int main()
{
int num1, num2;
bool found = false;

cout << "Enter two integers: ";


cin >> num1 >> num2;
cout << endl;

found = (num1 > num2);

if (found)
switch (num1 % num2)
{

20
case 0:
num2 = num1 / 2;
break;
case 1:
num1 = num2 / 2;
break;
default:
num1 = num1 / num2;
num2 = num1 * num2;
}
else
{
num1 = num1 - num2;
num2 = (num1 + num2) / 10;
}

cout << num1 << " " << num2 << endl;

return 0;
}

a. 1 8
b. -5 0

31.
#include <iostream>

using namespace std;


const int SECRET = 5;

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;
}

cout << "w = " << w << endl;

return 0;
}

32.
#include <iostream>
#include <cmath>
using namespace std;

int main()

21
{
double firstNum, secondNum;

cout << "Enter two nonzero numbers: ";


cin >> firstNum >> secondNum;
cout << endl;

if (firstNum == 0 || firstNum < 0 || secondNum == 0 || secondNum < 0)


cout << "Both numbers must be positive." << endl;
else if (firstNum == secondNum)
cout << firstNum + secondNum << endl;
else if (firstNum <= 2)
cout << pow(secondNum, firstNum) << endl;
else
cout << firstNum * secondNum << endl;

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;
break;
case 'n':
if (gpa >= 3.75)
dues = 25.00;
else
dues = 75.00;
break;
default:
cout << "Invalid class standing code." << endl;
}

34. Suppose that we have the following variables:


double billingAmount;
double payment; //payment made by the customer
double credit; //credit for the next bill
double penalty; //penalty to be added the next month’s bill
double balance; //unpaid balance
double paymentPercent; //percent of the billing amount paid

The following algorithm determines the credit or penalty, and the unpaid balance.

1. Prompt the user to enter the billing amount.


2. Input the billing amount into the variable billingAmount.

22
3. Prompt the user to input the payment.
4. Input the payment into the variable payment.
5. Determine the unpaid balance using the formula:
balance = billingAmount - payment;
6. Determine the percent of the billing amount made by the customer:
if (billingAmount != 0.0)
paymentPercent = payment / billingAmount;
else
paymentPercent = 0.0;
7. Determine the credit or the penalty, and the unpaid balance including penalty, if any, using the
following if/else statement.

if (paymentPercent == 1.0)
{
credit = billingAmount * 0.01;

if (credit > 10.00)


credit = 10.00;
}
else
{
if (paymentPercent >= 0.50)
penalty = balance * 0.05;
else if (paymentPercent >= 0.20 && paymentPercent < 0.50)
penalty = balance * 0.10;
else
penalty = balance * 0.20;

balance = balance + penalty;


}

23
Chapter 5
1. a. true; b. false; c. true; d. false; e. true; f. true; g. true; h. false ; i. false; j. true
2. i = 5 and temp = 48
3. 40
4. 1 3 5 7
5. if ch > 'Z' or ch < 'A'
6. Sum = 90
7. Sum = 22
8. Sum = 190
9. temp = 0
10.
int count = 0;
int sum = 0;
int num;

while (count < 20)


{
cin >> num;
sum = sum + num;
count++;
}

11. a. 20 *
b. *
c. 41 70 111 *
d. 27 44 71 *

12. 0 1 -1 1 -1 -3 6 5
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;
14. 2 3 4 5
15. 2 3 4 5 6
16. 8 6 4 2
17. 0 3 8 15 24

24
18. a. Counter controlled loop.
b. Sentinel controlled loop.
c. EOF controlled loop.
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);
20. 25 600
21. num = 485, y = 15
22. a. ii
b. iii
c. ii
23. a. *
b. infinite loop
c. infinite loop
d. ****
e. ******
f. ***
24.
sum = 0;
for (i = 0; i <= 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
sum = sum + i;
}
25. The relationship between x and y is: 3y = x.
Output: x = 19683, y = 10
26. 2 4 16 256
27.
0 - 24
25 - 49
50 - 74
75 - 99
100 - 124
125 - 149
150 - 174
175 - 200
28. temp = 896
29. a. both
b. do...while

25
c. while
d. while
30. There is more than one answer. One solution is:
#include <iostream>

using namespace std;

const int SECRET = 111;

int main()
{
int num1, num2;
double x = 0, y = 0;
int count;

cout << "Enter two integers: ";


cin >> num1 >> num2;
cout << endl;

for (count = 1; count > SECRET; ++count)


{
x = (num1 + num2) / 2.0;
y = (num1 - num2) % 2;
num1 = num1 + num2;
num2 = num2 * (count - SECRET - 1);
}
cout << num1 << " " << num2 << " " << x / 5
<< " " << (y / 7) << endl;

return 0;
}

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 evaluated after executing the body of the loop. A posttest loop executes at
least once, while a pretest loop may not execute at all.
32. a. The loop is executed 5 times; Output: 55 50
b. The loop is executed 4 times; Output: 80 80
c. The loop is executed 1 time; Output: 7 20
d. The loop is executed 3 times; Output: 35 35
e. The loop is executed 3 times; Output: 40 30
f. The loop is executed 0 times; Output: 5 30
33. int num;
do
{
cout << "Enter a number less than 20 or greater than 75: ";
cin >> num;
}
while (20 <= num && num <= 75);

34. int i, value = 0;


for (i = 0; i <= 20; i++)

26
{
if (i % 2 == 0 && i <= 10)
value = value + i * i;
else if (i % 2 == 0 && i > 10)
value = value + i;
else
value = value - i;
}

cout << "value = " << value << endl;

The output is: value = 200


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);

cout << "value = " << value << endl;

The output is: value = 200

36. There is more than one answer to this problem. One solution is:
do
{
cin >> number;
if (number != -1)
total = total + number;
count++;
}
while (number != -1);

37. cin >> number;


while (number != -1)
{
total = total + number;
cin >> number;
}
cout << endl;
cout << total << endl;

38. cin >> number;


while (number != -1)
{
total = total + number;
cin >> number;
}

27
cout << endl;
cout << total << endl;

39. a.
number = 1;
while (number <= 10)
{
cout << setw(3) << number;
number++;
}

b.
number = 1;
do
{
cout << setw(3) << number;
number++;
}
while (number <= 10);

40. a.
int value = 3;
int i = 1;
while (i < 5)
{
value = value * (i + 1) + i;
i++;
}
cout << "value = " << value << endl;

b.
int value = 3;
int i = 1;
do
{
value = value * (i + 1) + i;
i++;
}
while (i < 5);

cout << "value = " << value << endl;

41. a. 36 94 260
b. 4 20
c. 30
d. 98 250

28
42.
a.

1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
b.
2 3 4 5
3 4 5
4 5
5
c.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
d.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99100

e.
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

43 -1 0 3 8 15 24
44. 12
45. 12 11 9 7 6 4 2 1
46. The execution of a break statement in a loop terminates the loop.

29
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
2. a. # b. K c. 3 d. - e. t f. : g. u h. {
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

4. a. pow(9.2, 4.0) b. sqrt(5 * x - 3 * x * y) c. pow(a + b, 1/3.0)


d. (-b + sqrt(b * b – 4 * a * c)) / (2 * a)
e. fabs(3 * x * x - 2 * y)

5. a and b

6. a. 10.00
b. 10.00
c. 15.00
d. -31.00

7. a, b, c, d, 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.
8. a. 5
b. 3
c. 40 10
d. 8

9. a. 2; double
b. 3; int
c. 3; string
d. 2; char
e. The function third requires 4 actual parameters. The type and the order of these
parameters is: 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;
10. In a C++ program, typically the function main appears before any other user-defined function. The
compiler compiles the program sequentially from beginning to end. Now the function main contains
calls to user-defined functions. So to correctly translate each function call, the user-defined function
prototypes appears before any function definition. Because function prototypes appear before any
function definition, the compiler translates these first. The compiler can then correctly translate a function call

30
11. bool isWhitespace (char ch)
{
if (isspace(ch))
return true;
else
return false;
}

12. a. 4.00
b. 74.00
c. 92.63
13. a. (i) 72 (ii) -200
b. The function computes mn, where m and n are the arguments of the function.
14. bool funcEx14(double x, double y, double z)
{
if (floor(x * y) == floor(z))
return true;
else
return false;
}
15. a. 385
b. This function computes 1+4+9+16+25+36+49+64+81+100
16. 7
-17
-1
1
2
17. double funcEx17(double x, double y)
{
return pow(x, y) + pow(y, x);
}

18. a. -120
b. 37
c. 6
d. 0

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.
20. a.
Function prototype: void func(int, int, double&, char&); //Line 6
Function heading: int main() //Line 7
void func(int speed, int time, //Line 19
double& distance, char& c) //Line 20

Function body:
(function main): starts at Line 8 and ends at Line 18
(function func): starts at Line 21 and ends at Line 26
Function definitions:
(function main): starts at Line 7 and ends at Line 16

31
(function func): starts at Line 19 and ends at Line 26
b.
Function call: Statements in Lines 13 and 15
func(s, t, d, ch); //Line 13
func(75, 8, d, ch); //Line 15
Formal parameters (function func): speed, time, distance, c
Actual parameters: s, t, d, ch (in Line 13)
75, 8, d, ch (in Line 15)
c.
Value parameters (function func): speed, time
Reference parameters (function func): distance, c
d.
Local variables (function main): s, t, d, ch
(function func): num
Global variable: temp
e. Named constant: RATE, STAR

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 definition is called a global variable.
22. a. Take Programming I.
b. Take Programming II.
c. Take Invalid input. You must enter a 1 or 2
d. Take Invalid input. You must enter a 1 or 2
23. void funcEx23(int num)
{
if (num % 2 == 0)
cout << 2 * num << endl;
else
cout << 5 * num << endl;
}

24. void sumAvg(double x, double y, double z, double& sum,


double & avg, string& result)
{
sum = x + y + z;
avg = sum / 3;

if (avg >= 70)


result = "Pass";
else
result = "Fail";
}

25. void initialize(int& x, double& y, string& str)


{
x = 0;
y = 0;
str = "";
}

32
26. void sumAvgResult(int n, int m, int& sum, double& avg)
{
int count = 0;
sum = 0;

if (n >= m)
{
count = n - m + 1;

for (int i = m; i <= n; i++)


sum = sum + i;
}
else
{
count = m - n + 1;

for (int i = n; i <= m; i++)


sum = sum + i;
}

avg = static_cast<double>(sum) / count; //count != 0


}

27. 7, 0, 0
1, 0, 8
8, 1, 8
2, 1, 1

28. 6 10 20
2 10 8
2 2 14

29. #include <iostream>

using namespace std;

int secret(int, int);

void func(int x, int& y);

int main()
{
int num1, num2;

__1__ num1 = 6;

__2__ cout << "Enter a positive integer: ";


__3__ cin >> num2;
__4__ cout << endl;
__8__ cout << secret(num1, num2) << endl;
__9__ num2 = num2 – num1;
_10__ cout << num1 << " " << num2 << endl;
_15__ func(num2, num1);
_16__ cout << num1 << " " << num2 << endl;

_17__ return 0;
}

int secret(int a, int b)

33
{
int d;

__5__ d = a + b;
__6__ b = a * d;

__7__ return b;
}

void func (int x, int& y)


{
int val1, val2;

_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
64
10 24
34 4

30. a. The user input is shaded.


Enter two numbers: 3 5

z = 8.00, one = 11.00, two = 5.00


z = 16.00, one = 11.00, two = 21.00
b. The user input is shaded.
Enter two numbers: 4 11

z = 15.00, one = 19.00, two = 11.00


z = 30.00, one = 19.00, two = 41.00
c. One possible answer is: (The user input is shaded.)
Enter two numbers: 10 10

z = 20.00, one = 30.00, two = 10.00


z = 40.00, one = 30.00, two = 50.00

31. void trackVar(double& x, double y, double& z)


{
z = floor(x) + ceil(y);
x = x + z;
y = y - z;
}

32.

34
Visibility Visibility
Identifier in trackVar in main
main Y Y
local variables of main N Y
trackVar (function name) Y Y
x (trackVar formal parameter) Y N
y (trackVar formal parameter) Y N
z (trackVar local variable) Y N

33. 3 5
108 0
108 5

34.
Sample Run:
Line 9: In main: num1 = 10, num2 = 20
Line 19: In funOne: a = 10, x = 12, and z = 22
Line 21: In funOne: a = 10, x = 17, and z = 22
Line 23: In funOne: a = 18, x = 17, and z = 22
Line 11: In main after funOne: num1 = 18, num2 = 20

Before the statement in Line 9 executes, the variables are:

main

num1 10
num2 20

Line 9 produces the following line of output:


Line 9: In main: num1 = 10, num2 = 20
The statement in Line 10 calls the function funOne; control transfers to the function funOne. Before
the statement in Line 18 executes, the variables are:

main funOne

num1 10 a
num2 20 12 x
z

After the statement in Line 18 executes, the variables are:

35
main funOne

num1 10 a
num2 20 12 x
22 z

Line 19 produces the following output:


Line 19: In funOne: a = 10, x = 12, and z = 22
After the statement in Line 20 executes, the variables are:

main funOne

num1 10 a
num2 20 17 x
22 z

Line 21 produces the following output:


Line 21: In funOne: a = 10, x = 17, and z = 22
After the statement in Line 22 executes, the variables are:

main funOne

num1 18 a
num2 20 17 x
22 z

Line 23 produces the following output:


Line 23: In funOne: a = 18, x = 17, and z = 22

36
After the statement in Line 23 executes, control goes back to the function main at Line 11. Before the
statement in Line 11 executes, the variables are:

main

num1 18
num2 20

Line 11 produces the following output:


Line 11: In main after funOne: num1 = 18, num2 = 20

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

36. The signature of a function consists of the function name and its formal parameter list.
37. a, b, and d are correct.
38. a. 69, 71.50
b. 51, 53.50
c. 53, 60.50
d. 51, 57.50

37
Chapter 7
1. a. true; b. false; c. true; d. false; e. false; f. true; g. true; h. true; i. false; j. false; \

2. a. enum flowerType {ROSE, DAISY, CARNATION, FREESIA, GARDENIA,


ALLIUM,TULIP, IRIS, SUNFLOWER, LILAC, ORCHID};
b. flowerType flower;
c. flower = TULIP;
d. flower = static_cast<flowerType>(flower + 1);
e. flower = static_cast<flowerType>(flower - 1) ;
f. switch(flower)
{
case ROSE:
cout << "Rose";
break;
case DAISY:
cout << "Daisy";
break;
case CARNATION:
cout << "Carnation";
break;
case FREESIA:
cout << "Freesia";
break;
case GARDENIA:
cout << "Gardenia";
break;
case ALLIUM:
cout << "Allium";
case TULIP:
cout << "Tulip";
break;
case IRIS:
cout << "Iris";
break;
case SUNFLOWER:
cout << "Sunflower";
break;
case LILAC:
cout << "Lilac";
break;
case ORCHID:
cout << "Orchid";
}

g. string str;
cin >> str;

if (str == "Rose")

38
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;
else if (str == "Allium")
flower = ALLIUM;
else if (str == "Tulip")
flower = TULIP;
else if (str == "Iris")
flower = IRIS;
else if (str == "sunflower")
flower = SUNFLOWER;
else if (str == "Lilac")
flower = LILAC;
else if (str == "Orchid")
flower = ORCHID;
else
cout << "Invalid flower name." << endl;

3. Only a and c are valid.

4. a. 4
b. GRAPE
c. MANGO
d. 1 (true)
e. No output. Syntax error. The expression fruit++ should be
static_cast<fruitType>(fruit + 1)
5.
flowerType readIn()
{
string str;
flowerType flower = 0;

cin >> str;

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;
else if (str == "Allium")
flower = ALLIUM;

39
else if (str == "Tulip")
flower = TULIP;
else if (str == "Iris")
flower = IRIS;
else if (str == "sunflower")
flower = SUNFLOWER;
else if (str == "Lilac")
bir flower d == LILAC;
else if (str == "Orchid")
flower = ORCHID;
else
cout << "Invalid flower name." << endl;

return flower;
}
6.
void printflowerName(flowerType flower)
{
switch(flower)
{
case ROSE:
cout << "Rose";
break;
case DAISY:
cout << "Daisy";
break;
case CARNATION:
cout << "Carnation";
break;
case FREESIA:
cout << "Freesia";
break;
case GARDENIA:
cout << "Gardenia";
break;
case ALLIUM:
cout << "Allium";
case TULIP:
cout << "Tulip";
break;
case IRIS:
cout << "Iris";
break;
case SUNFLOWER:
cout << "Sunflower";
break;
case LILAC:
cout << "Lilac";
break;
case ORCHID:
cout << "Orchid";
}//end switch
}//end printflowerName

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 cannot return an anonymous type value. Also, values used in one

40
anonymous type can be used in another anonymous type, but variables of those types are treated
differently.
8. enum quadrilateralType {SQUARE, RECTANGLE, RHOMBUS, TRAPEZIOD,
PARALLELOGRAM, QUADRILATERAL,
KITE} quadrilateral;
9. The statement in Line1 1 and 2 should be:
#include <iostream> //Line 1

using namespace std; //Line 2

10. The program does not use the statement: using namespace std;
There are several errors in this code. The correct code is:
#include <iostream> //Line 1
#include <string> //Line 2

int main() //Line 3


{ //Line 4
std::string str; //Line 5
std::cin >> str; //Line 6
std::cout << str << std::endl; //Line 7
return 0; //Line 8
} //Line 9
//Line 9
11. The statement in Line 2 should be:
using namespace std; //Line 2
12. Replace the statement in Line 2 with the following:
using namespace mySpace //Line 2

Replace the statement in Line 12 with the following:


mySpace::x = static_cast<int>(num); //Line 12
Also, either include the following statement before the function main:
using namespace mySpace;

or replace the statements in Lines 11, 13, and 14 with the following statements:

num = 2 * mySpace::PRIZE; //Line 11


cout << mySpace::PRIZE << " " << mySpace::x << " " //Line 13
<< num << endl; //Line 14

13. Either include the statement:


using namespace aaa;
before the function main or refer to the identifiers x and y in main as aaa::x and aaa::y,
respectively.
14. The statement in Line 2 should be: #include <cmath>
In Line 3, nameSpace should be namespace.
Statement in Line 4 should be: int main() //Line 4
15. a. Sammer Vucation
b. Temperary Projoct
c. Nocial Setwork

41
16. a. Temporary > Storage
b. Main < Memory
c. run! = run!
17. Regular exercise
Regular exercise and low fat diet
33
8
8
health insurance
insurance
Regular exercise can reduce health insurance $$$$.
$ocial Nedia!!
14
Social Media!!

18. a. 45
b. we will drive across
c. This spring we will drive across the country!
d. This spring we will enjoy Caribbean cruise!

42
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

2. a. currentBalance

b. 91
c. double
d. 0 to 90
e. first = 0, middle = 45, last = 90
3. a. This declaration is correct.

b. Array size must be positive. A correct answer is: int testScores[10];


c. This declaration is correct.
d. Array size must be a positive integer not a range. A 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 . A correct statement is: const int LENGTH =
26;
g. This declaration is correct.

4. a. Valid
b. Invalid. The data type should be string.
c. Invalid. The size of the array gpa must be specified as a positive integer.
d. Invalid. Incorrect syntax and array size. A correct declaration is: double ratings[50];
e. Valid.
f. Valid.
g. Invalid. The size of array sales must be a positive integer. The expression 100 - 2 * MAX_SIZE
= 100 - 2 * 50 = 0.
5. 0 to 64. first = 0, middle = 32, last = 64

6. a. int alpha[50];

b. for (int i = 0; i < 50; i++)


alpha[i] = -1;
c. cout << alpha[0] << endl;
d. alpha[24] = 62;
e. alpha[9] = alpha[49] + 10.
f. for (int i = 0; i < 50; i++)
if (i % 2 == 0 || i % 3 == 0)
cout << alpha[i] << " ";
cout << endl;

43
g. cout << alpha[49] << endl;
h. for (int i = 0; i < 50; i++)
{
cout << alpha[i] << " ";

if ( (i + 1) % 15)
cout << endl;
}
cout << endl;
i. for (int i = 0; i < 50; i = i + 2)
alpha[i] = alpha[i] + 1;

j. int diffAlpha[49];
for (int i = 0; i < 49; i++)
diffAlpha[i] = alpha[i] - alpha[i - 1];
Size of diffAlpha is 49.
7. 0.00 1.50 9.00 28.50 66.00
57.00 1.50 30.00 28.50 66.00
8. 0 2 6 12 0 2 8 9

9. 1 2 2 4 8 32 224 6944

10. 2.50 2.50 5.00 15.00 30.00 75.00

11. int myList[10];

for (int i = 0; i < 10; i++)


myList[i] = i;
12.

int intList[5];

for (int i = 0; i < 5; i++)


cin >> intList[i];

for (int i = 0; i < 5; i++)


cout << intList[i] << " ";
cout << endl;

13. If array index is less than 0 or greater than arraySize – 1, we say that the array index is out-of

bounds. C++ does not check for array indices within bound.

14. The output of the code is:

points[2] and points[3] are out of order.


points[7] and points[8] are out of order.

The correct code is:

44
for (int i = 0; i < 10; i++)
if (points[i + 1] > points[i])
cout << "points[" << i << "] and points[" << (i + 1)
<< "] are out of order." << endl;
15. a. double heights[10] = {5.2, 6.3, 5.8, 4.9, 5.2, 5.7, 6.7, 7.1, 5.10, 6.0};
or
double heights[] = {5.2, 6.3, 5.8, 4.9, 5.2, 5.7, 6.7, 7.1, 5.10, 6.0};
b. int weights[7] = {120, 125, 137, 140, 150, 180, 210};
or
int weights[] = {120, 125, 137, 140, 150, 180, 210};
c. char specialSymbols[] = {'$', '#', '%', '@', '&', '! ', '^'};
d. string seasons[4] = {"fall", "winter", "spring", "summer"};
or
string seasons[] = {"fall", "winter", "spring", "summer"};

16. a. Valid. The size of list is 4.


b. Valid. The size of x is 10.
c. Invalid. The size of y is 4. However, the number of array initializers is 5, excedding the size of
the array.
d. Valid.
e. Invalid. When initializing an array during declaration, all elements that follow the first
unspecified element must be unspecified.
f. Valid.
17. alpha[0] = 3, alpha [1] = 12, alpha [2] = -25, alpha [3] = 72,

alpha [4] = 0.

18. a. for (int i = 0; i < 6; i++)


cout << list[i] << " ";
cout << endl;
b. for (int i = 0; i < 5; i++)
list[i] = list[i] – 3 * list[i + 1];
19. -5 0 10 60 360 600
20. alpha: 1 3 5 7 9 -1 2 5 8 11
beta: -2 3 8 13 18 27 20 13 6 -1 45 33 21 9 -3

21. a. Correct.
b. Correct.
c. Incorrect. None of the formal parameters list and sList are 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.
22. a. Valid.

45
b. Valid.
c. Invalid.
d. Valid.

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
24.

int cars[10];
int sum = 0;

int maxIndex;
int max;

for (int j = 0; j < 10; j++)


inFile >> cars[j];

for (int j = 0; j < 10; j++)


sum = sum + cars[j];

cout << "The total number of cars sold = " << sum << endl;

max = cars[0];

for (int j = 1; j < 10; j++)


if (max < cars[j])
max = cars[j];

cout << "The salesperson(s) selling the maximum number of cars: ";

for (int j = 0; j < 10; j++)


if (max == cars[j])
cout << j << ", ";
cout << endl;

25. list: 810 0 270 180 90

26.

Quantity Unit Cost Amount


3 15.00 45.00
5 20.00 100.00
2 5.00 10.00
8 3.00 24.00
1 75.00 75.00
Total due: $254.00
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

28. The base address of the array.

46
29. No.

30. List before the first iteration: 12, 50, 68, 30, 46, 5, 92, 10, 38
List after the first iteration: 5, 50, 68, 30, 46, 12, 92, 10, 38
List after the second iteration: 5, 10, 68, 30, 46, 12, 92, 50, 38
List after the third iteration: 5, 10, 12, 30, 46, 68, 92, 50, 38
List after the fourth iteration: 5, 10, 12, 30, 46, 68, 92, 50, 38
List after the fifth iteration: 5, 10, 12, 30, 38, 68, 92, 50, 46
List after the sixth iteration: 5, 10, 12, 30, 38, 46, 92, 50, 68
List after the seventh iteration: 5, 10, 12, 30, 38, 46, 50, 92, 68
List after the eighth iteration: 5, 10, 12, 30, 38, 46, 50, 68, 92

31. 1 0 1 1 1 0 0 1 1

32. Cindy Blair


Chris Johnson
Sheila Mann

33. No, because during compile time the formal parameter list has no first and last elements.

34. a. Invalid; the assignment operator is not defined for C-strings.


b. Valid
c. Valid
d. Valid
e. Valid
f. Invalid; the relational operators are not defined for C-strings.
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.
36. a. Yes
b. Yes
c. Yes
d. No. It outputs eight characters, while "Shelly" has only six characters.
37. a. strcpy(myStr, "Summer Vacation");
b. cout << strlen(yourStr) << endl;
c. strcpy(myStr, yourStr);
d. compare = strcmp(myStr, yourStr);

38. a. Valid
b. Valid
c. Valid

47
d. Invalid; the assignment operator is not defined for C-strings.
e. Invalid; the relational and assignment operators are not defined for C-strings.
f. Valid
g. Valid
h. Valid
39. double matrix[4][3] = {{2.5, 3.2, 6.0}, {5.5, 7.5, 12.6},
{11.25, 16.85, 13.45}, {8.75, 35.65, 19.45}};
40. a. for (int i = 0; i < 3; i++)
cin >> matrix[0][i];
b. for (int i = 0; i < 4; i++)
cout << matrix [i][0]<< endl;
c. cout << matrix[0][2] << endl;
d. matrix[3][2] = matrix[3][2] + 13.6;
41. a. 30
b. 5
c. 6
d. row
e. column

42. a. int alpha[10][20];


b. for (int j = 0; j < 10; j++)
for (int k = 0; k < 20; k++)
alpha[j][k] = 0;

c.
for (int k = 0; k < 20; k++)
alpha[0][k] = 1;

for (int j = 1; j < 10; j++)


for (int k = 0; k < 20; k++)
alpha[j][k] = 2;

d.
for (int j = 0; j < 10; j++)
alpha[j][0] = 5;

for (int k = 1; k < 20; k++)


for (int j = 0; j < 10; j++)
alpha[j][k] = 2 * alpha[j][k - 1];

e.
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 20; k++)
cout << alpha[j][k] << " ";
cout << endl;
}

48
f.
for (int k = 0; k < 20; k++)
{
for (int j = 0; j < 10; j++)
cout << alpha[j][k] << " ";
cout << endl;
}
43. a. beta is initialized to 0.

b. First row of beta: 0 1 2


Second row of beta: 1 2 3
Third row of beta: 2 3 4
c. First row of beta: 0 0 0
Second row of beta: 0 1 2
Third row of beta: 0 2 4
d. First row of beta: 0 2 0
Second row of beta: 2 0 2
Third row of beta: 0 2 0
e. First row of beta: 0 0 0
Second row of beta: 0 1 2
Third row of beta: 0 2 1

44.
int flowers[28][10];
int animals[15][10];
int trees[100][10];
int inventory[30][10];

a.
void readIn(int list[][10], int rowSize)
{
for (int i = 0; i < rowSize; i++)
for (int j = 0; i < 10; j++)
cin >> list[i][j];
}

Function calls:
readIn(flowers, 28);
readIn(animals, 15);
readIn(trees, 100);
readIn(inventory, 30);

b.
void sumRow(int list[][10], int rowSize)
{
int sum;

for (int i = 0; i < rowSize; i++)


{
sum = 0;
for (int j = 0; i < 10; j++)
sum = sum + list[i][j];

cout << "Row " << i + i << " sum = " << sum << endl;

49
}

Function calls:
sumRow(flowers, 28);
sumRow(animals, 15);
sumRow(trees, 100);
sumRow(inventory, 30);

c.
void print(int list[][10], int rowSize)
{
for (int i = 0; i < rowSize; i++)
{
for (int j = 0; i < 10; j++)
cout << list [i][j] << " ";

cout << endl;


}
}

Function calls:
print(flowers, 28);
print(animals, 15);
print(trees, 100);
print(inventory, 30);

50
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
2. struct computerType
{
string manufacturer;
string modelType;
string processorType;
int ram;
int hardDriveSize;
int yearBuilt;
double price;
};

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;

4. a. houseType oldHouse, newHouse;


b. oldHouse.style = "Two-Story";
oldHouse.numOfBedrooms = 5;
oldHouse.numOfBathrooms = 3;
oldHouse.numOfCarsGarage = 4;
oldHouse.yearBuilt = 1975;
oldHouse.finishedSquareFootage = 3500;
oldHouse.price = 675000;
oldHouse.tax = 12500.00;
c. newHouse oldHouse;

5. if (firstHouse.style == secondHouse.style &&


firstHouse.price == secondHouse.price)
cout << "true" << endl;
else
cout << "false" << endl;

6. struct fruitType
{
string name;
string color;
int fat;
int sugar;
int carbohydrate;
};

7. fruitType fruit;

51
fruit.name = "banana";
fruit.color = "yellow";
fruit.fat = 1;
fruit.sugar = 15;
fruit.carbohydrate = 22;

8. a. void getFruitInput(fruitType& fruit)


{
cin >> fruit.name << fruit.color << fruit.fat
<< fruit.sugar << fruit.carbohydrate;
}

b. void printFruitInfo (houseFruit fruit)


{
cout << "Name: " << fruit.name
<< "Color: " << fruit.color
<< "Fat: " << fruit.fat
<< "Sugar: " << fruit.sugar
<< "Carbohydrate: " << fruit.carbohydrate
}

9. Assignment statement and function return value.

10. a. Valid
b. Valid
c. Invalid; classList[1].name is a struct variable of type nameType while student is a
struct variable of type studentType, mismatch data types;
d. Invalid ; The struct variable classList[0] does not have the component callNum .
e. Valid
f. Invalid ; course is a struct variable of type courseType while classList[0] is a
struct variable of type studentType, mismatch data types;
g. Invalid; classList[0] is a struct variable. There are no aggregate input operations on a
struct.
h. Valid
i. Invalid; classList is an array. There are no aggregate assignment operations on arrays.
j. Valid

11. a. classList[0].name.first = "Jessica";


classList[0].name.last = "Miller";
classList[0].gpa = 3.8;
classList[0].course.name = "Data Structure";
classList[0].course.callNum = 8340;
classList[0].course.credits = 3;
classList[0].course.grade = 'B';

b. student = classList[0];

12. a course.name = "Programming I";


course.callNum = 13452;
course.credits = 3;
course.grade = "";

52
b. for (int j = 0; j < 100; j++)
classList[j].gpa = 0.0;

c. student = classList[30];
d. classList[9].gpa = classList[9].gpa + 0.75;

13. a. Invalid; the member name of newEmployee is a struct. Specify the member names to store the
value "John Smith". For example,
newEmployee.name.first = "John";
newEmployee.name.last = "Smith";

b. Invalid; the member name of newEmployee is a struct. There are no aggregate output operations
on a struct. A correct statement is:

cout << newEmployee.name.first << " "


<< newEmployee.name.last << endl;

c. Valid
d. Valid
e. Invalid; employees is an array. There are no aggregate assignment operations on arrays.

14. a. newEmployee.name.first = "Mickey";


newEmployee.name.last = "Doe";
newEmployee.pID = 111111111;
newEmployee.performanceRating = 2;
newEmployee.dept = "ACCT";
newEmployee.salary = 34567.78;

b. for (j = 0; j < 100; j++)


employees[j].performanceRating = 0;

c. newEmployee = employees[19];
d. employees[49].salary += 5735.87;

15. sportsType soccer[20];

struct sportsType
{
string sportName;
string teamName;
int numberOfPlayers;
double teamPayroll;
double coachSalary;
};

16. a. for (int j = 0; j < 20; j++)


{
soccer [i].sportName = "";
soccer [i].teamName = "";
soccer [i].numberOfPlayers = 0;
soccer [i].teamPayroll = 0.0;
soccer [i].coachSalary = 0.0;

53
}

b. for (int j = 0; j < length; j++)


cin >> soccer [i].sportName >> soccer [i].teamName
>> soccer [i].numberOfPlayers
>> soccer [i].teamPayroll
>> soccer [i].coachSalary;
c. for (int j = 0; j < length; j++)
if (soccer [i].teamPayroll >= 10000000)
cout << soccer [i].teamName << endl;

17. a. void getData(sportsType & sp)


{
cin >> sp[i].sportName >> sp[i].teamName
>> sp[i].numberOfPlayers
>> sp[i].teamPayroll
>> sp[i].coachSalary;
}

for (int j = 0; j < 100; j++)


getData(soccer[i]);

b. void printData(sportsType sp)


{
cout << "Sport Name: " << sp[i].sportName << endl;
cout << "Team Name: " << sp[i].teamName << endl;
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;
}

for (int j = 0; j < 20; j++)


printData(soccer[i]);

18. a. tourType destination;

b. destination.cityName = "Chicago";
destination.distance = 550;
destination.travelTime.hr = 9;
destination.travelTime.min = 30;

c. void print(const tourType& dest)


{
cout << "City: " << dest.cityName << endl;
cout << "Distance: " << dest.distance << endl;
cout << "Travel time: " << dest.travelTime.hr << " hour(s) "
<< dest.travelTime.min << " minute(s)" << endl;
}

d. tourType getData()
{
tourType dest;

cin >> dest.cityName;


cin >> dest.distance;
cin >> dest.travelTime.hr >> dest.travelTime.min;

54
return dest;
}

e. void getData(tourType& dest)


{
cin >> dest.cityName;
cin >> dest.distance;
cin >> dest.travelTime.hr >> dest.travelTime.min;
}

55
Chapter 10
1. a. false; b. false; c. true; d. false; e. false
2. In Line 4, the name of the constructor is misspelled. Line 4 should be:
syntaxErrors1(); //Line 4

Missing semicolon after } in Line 10. Line 10 should be:


}; //Line 10

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

4. A class is not a function. The function isEqual must have a return type. Because the second
parameter of the constructor is a default parameter, the first parameter must be a default
parameter. The statements in Lines1, 5, and 8 should be:
class syntaxErrors3 //Line 1
bool isEqual(int a, int b); //Line 5
syntaxErrors3(int = 0, int = 0); //Line 8

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:
void set(string, int, double); //Line 4
syntaxErrors4() const; //Line 6
}; //Line 12

6.
a. 16
b. 6
c. 2
d. 7
e. fruit1 is initialized by the default constructor. fruit2 is initialized by the constructor with
parameters.
f.
class foodType
{
public:
void set(string, int, double, int, double, double);
void print() const;

void setName(string s);


string getName() const;

void setCalories(int c);


int getCalories() const;

void setFat(double f);


double getFat() const;

56
void setSugar(int s);
int getSugar() const;

void setCarbohydrate(double c);


double getCarbohydrate() const;

void setPotassium(int p);


double getPotassium() const;

foodType();
foodType(string, int, double, int, double, double);

private:
string name;
int calories;
double fat;
int sugar;
double carbohydrate;
double potassium;
};
g.
foodType(string s = "", int c = 0, double f = 0.0,
int su = 0, double cr = 0.0, double p = 0.0);

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;

if (p >= 0)
potassium = p;
else

57
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;
}

int foodType::getCalories() const


{
return calories;
}

double foodType::getFat() const


{
return fat;
}

int foodType::getSugar() const


{
return sugar;
}

double foodType::getCarbohydrate() const


{
return carbohydrate;
}

double foodType::getPotassium() const


{
return potassium;
}

d.
foodType::foodType()
{
set("", 0, 0.0, 0, 0.0, 0.0);
}

e.
foodType::foodType(string s, int c, double f, int su,
double cr, double p)
{
set(s, c, f, su, cr, p);
}

58
f.
fruit2.print();

g.
foodType myFruit("Apple ", 52, 0.2, 10, 13.8, 148.0);

8.
a. i. Line 4
ii. Line 7
iii. Line 6
iv. Line 5
b.
productType::productType()
{
productName = "";
id = "";
manufacturer = "";
quantitiesInStock = 0;
price = 0.0;
discount = 0.0;
}
c.
productType::productType(int x, double y, double z)
{
productName = "";
id = "";
manufacturer = "";

if (x >= 0)
quantitiesInStock = x;
else
quantitiesInStock = 0;

if (y >= 0.0)
price = y;
else
price = 0.0;

if (z >= 0.0)
discount = z;
else
discount = 0.0;
}
d.
productType::productType(string s, int x, double y, double z)
{
productName = "";
id = s;
manufacturer = "";

if (x >= 0)
quantitiesInStock = x;

59
else
quantitiesInStock = 0;

if (y >= 0.0)
price = y;
else
price = 0.0;

if (z >= 0.0)
discount = z;
else
discount = 0.0;
}
e.
productType::productType(string n, string pID, string m,
int x, double y, double z)
{
productName = n;
id = pID;
manufacturer = m;

if (x >= 0)
quantitiesInStock = x;
else
quantitiesInStock = 0;

if (y >= 0.0)
price = y;
else
price = 0.0;

if (z >= 0.0)
discount = z;
else
discount = 0.0;
}
9. The functions print, getQuantitiesInStock, getPrice, and getDiscount are
accessors; functions set, setQuantitiesInStock, updateQuantitiesInStock,
setPrice, and setDiscount are mutators.
10.
a.
void productType::set(string n, string pID, string m,
int x, double y, double z)
{
productName = n;
id = pID;
manufacturer = m;

if (x >= 0)
quantitiesInStock = x;
else
quantitiesInStock = 0;

if (y >= 0.0)
price = y;

60
else
price = 0.0;

if (z >= 0.0)
discount = z;
else
discount = 0.0;
}

b.
void productType::print() const
{
cout << "Product Name: " << productName << endl;
cout << "Product ID: " << id << endl;
cout << "Manufacturer: " << manufacturer << endl;
cout << "Quantities In Stock: " << quantitiesInStock
<< endl;
cout << "Price: " << price << endl;
cout << "Discount: " << discount << endl;
}

c.
void productType::setQuantitiesInStock(int x)
{
if (x >= 0)
quantitiesInStock = x;
else
quantitiesInStock = 0;
}

d.
void productType::updateQuantitiesInStock(int x)
{
quantitiesInStock = quantitiesInStock + x;

if (quantitiesInStock < 0)
quantitiesInStock = 0;
}

e.
int productType::getQuantitiesInStock() const
{
return quantitiesInStock;
}

f.
void productType::setPrice(double x)
{
if (x >= 0.0)
price = x;
else
price = 0;
}

g.
double productType::getPrice() const
{

61
return price;
}

h.
void productType::setDiscount(double d)
{
if (d >= 0.0)
discount = d;
else
discount = 0;
}

i.
double productType::getDiscount() const
{
return discount;
}

11. a. 28; b. 8 c. 1; d. 9

12.
a.

void houseType::set(string s, int bed, int bath, int cg,


int yb, int fs, double pr, double tx)
{
style = s;
numOfBedrooms = bed;
numOfBathrooms = bath;
numOfCarsGarage = cg;
yearBuilt = yb;
finishedSquareFootage = fs;
price = pr;
tax = tx;
}
b.

void houseType::print() const


{
cout << "Style: " << style << endl;
cout << "Number of Bedrooms: " << numOfBedrooms << endl;
cout << "Number of Bathrooms: " << numOfBathrooms << endl;
cout << "Number of cars garage: " << numOfCarsGarage << endl;
cout << "Year built: " << yearBuilt << endl;
cout << "Finished square footage: " << finishedSquareFootage << endl;
cout << "Price: " << price << endl;
cout << "Tax: " << tax << endl;
}

c.

houseType::houseType(string s, int bed, int bath, int cg,


int yb, int fs, double pr, double tx)
{

62
style = s;
numOfBedrooms = bed;
numOfBathrooms = bath;
numOfCarsGarage = cg;
yearBuilt = yb;
finishedSquareFootage = fs;
price = pr;
tax = tx;
}
d. newHouse.print();

e. houseType house("Ranch", 3, 2, 2, 2005, 1300, 185000, 3600.0);

f. Accessors: print, getStyle, getNumOfBedrooms, getNumOfBathrooms,


getNumOfCarsGarage, getYearBuilt, getFinishedSquareFootage,
getPrice, getTax
Mutators: set, setStyle, setNumOfBedrooms, setNumOfBathrooms,
setNumOfCarsGarage, setYearBuilt, setFinishedSquareFootage,
setPrice, setTax

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 initialize 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;

14.
a.
void temporary::set(string d, double f, double s)
{
description = d;

if (f >= 0)
first = f;
else
first = 0;

if (s >= 0)
second = s;
else
second = 0;
}

b.
double temporary::manipulate()
{
if (description == "rectangle")
return first * second;

63
else if (description == "circle")
return 3.1416 * first * first;
else if (description == "sphere")
return (4.0 / 3.0) * 3.1416 * first * first * first;
else if (description == "cylinder")
return 3.1416 * first * second;
else
return -1;
}

c.
void temporary::print()
{
cout << description;

if (description == "rectangle")
cout << ": length = " << first << ", width = " << second
<< ", area = " << manipulate() << endl;
else if (description == "circle")
cout << ": radius = " << first
<< ", area = " << manipulate() << endl;
else if (description == "sphere")
cout << ": radius = " << first
<< ", volume = " << manipulate() << endl;
else if (description == "cylinder")
cout << ": radius = " << first << ", height = " << second
<< ", volume = " << manipulate() << endl;
else
cout << " -- invalid shape." << endl;
}

d.
temporary::temporary(string d, double f, double s)
{
set(d, f, s);
}

e.
void temporary::get(string& d, double& f, double& s)
{
d = description;
f = first;
s = second;
}

void temporary::setDescription(string d)
{
description = d;
}

void temporary::setFirst(double f)
{

if (f >= 0)
first = f;
else
first = 0;

64
}

void temporary::setSecond(double s)
{
if (s >= 0)
second = s;
else
second = 0;
}

string temporary::getDescription() const


{
return description;
}

double temporary::getFirst() const


{
return first;
}

double temporary::getSecond() const


{
return second;
}

15. The statement in Line 1 creates object1 and initializes the instance variables of this object

to "", 0, 0, that is, object1.description = "";, object1.first = 0.0;,

and object1.second = 0.0;. The statement 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 statement 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;.

16.
-- invalid shape.
rectangle: length = 8.50, width = 5.00, area = 42.50
circle: radius = 6.00, area = 113.10
cylinder: radius = 6.00, height = 3.50, volume = 65.97

65
sphere: radius = 4.50, volume = 381.70

17. There two built-in operations for class objects: Member access (.) and assignment (=).

18. By default, all members of a struct are public, and all members of a class are private.

19.
10:17:00
23:59:29
00:00:29
20. 3510862895423079232: The number of digits----
Even: 10
Zeros: 2
Odd: 9
21. a. personType student("Buddy", "Arora");

b. student.print();
c. student.setName("Susan", "Gilbert");

22. If you do not want the user of a class to manipulate or access certain members of a class

directly, such as instance variable, you declare them private. If a member of a class, such

as an instance variable, is private, you may need to include public members, in the class,

that manipulate or control the accessing of the private members so that the user can access the

private members through those public members.

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.

24. c. ~

25. A destructor is a member of a class and if it is included in a class, it executes automatically

when a class object goes out of scope. Its main purpose is to deallocate the dynamic memory

created by an object.

26. a–c.

#include <string>

66
using namespace std;

class stockType
{
public:
stockType(string n = "", string sym = "",
double curP = 0.0, double lowP = 0.0,
double highP = 0.0, double preDayClP = 0.0,
double fTWH = 0.0, double fTWL = 0.0);

void setStockName(string n);


string getName() const;

void setSymbol(string sym);


string getSymbol() const;

void setCurrentPrice(double curP);


double getCurrentPrice() const;

void setLowPriceOfTheDay(double lowP);


double getLowPriceOfTheDay() const;

void setHighPriceOfTheDay(double highP);


double getHighPriceOfTheDay() const;

void setPreviousDayClosingPrice(double preDayClP);


double getPreviousDayClosingPrice() const;

void setFiftyTwoWeeksHigh(double fTWH);


double getFiftyTwoWeeksHigh() const;

void setFiftyTwoWeeksLow(double fTWL);


double getFiftyTwoWeeksLow() const;

double percentGainLoss();

void print() const;

private:
string name;
string symbol;
double currentPrice;
double lowPriceOfTheDay;
double highPriceOfTheDay;
double previousDayClosingPrice;
double fiftyTwoWeeksHigh;
double fiftyTwoWeeksLow;
};

d.

void stockType::print() const


{
cout << "Name: " << name << endl;
cout << "Symbol: " << symbol << endl;

67
cout << "Current Price: " << currentPrice << endl;
cout << "Low Price Of The Day: " << lowPriceOfTheDay
<< endl;
cout << "High Pric eOf The Day: " << highPriceOfTheDay
<< endl;
cout << "Previous Day Closing Price: "
<< previousDayClosingPrice << endl;
cout << "Fifty Two Weeks High: " << fiftyTwoWeeksHigh
<< endl;
cout << "Fifty Two Weeks Low: " << fiftyTwoWeeksLow << endl;
}

void stockType::setStockName(string n)
{
name = n;
}

string stockType::getName() const


{
return name;
}

void stockType::setSymbol(string sym)


{
symbol = sym;
}

string stockType::getSymbol() const


{
return symbol;
}

void stockType::setCurrentPrice(double curP)


{
if (curP >= 0.0)
currentPrice = curP;
else
currentPrice = 0.0;
}

double stockType::getCurrentPrice() const


{
return currentPrice;
}

void stockType::setLowPriceOfTheDay(double lowP)


{
if (lowP >= 0.0)
lowPriceOfTheDay = lowP;
else
lowPriceOfTheDay = 0.0;
}

double stockType::getLowPriceOfTheDay() const


{
return lowPriceOfTheDay;
}

68
void stockType::setPreviousDayClosingPrice(double preDayClP)
{
if (preDayClP >= 0.0)
previousDayClosingPrice = preDayClP;
else
previousDayClosingPrice = 0.0;
}
double stockType::getPreviousDayClosingPrice() const
{
return previousDayClosingPrice;
}

void stockType::setHighPriceOfTheDay(double highP)


{
if (highP >= 0.0)
highPriceOfTheDay = highP;
else
highPriceOfTheDay = 0.0;
}

double stockType::getHighPriceOfTheDay() const


{
return highPriceOfTheDay;
}

void stockType::setFiftyTwoWeeksHigh(double fTWH)


{
if (fTWH >= 0.0)
fiftyTwoWeeksHigh = fTWH;
else
fiftyTwoWeeksHigh = 0.0;
}

double stockType::getFiftyTwoWeeksHigh() const


{
return fiftyTwoWeeksHigh;
}

void stockType::setFiftyTwoWeeksLow(double fTWL)


{

if (fTWL >= 0.0)


fiftyTwoWeeksLow = fTWL;
else
fiftyTwoWeeksLow = 0.0;
}

double stockType::getFiftyTwoWeeksLow() const


{
return fiftyTwoWeeksLow;
}

double stockType::percentGainLoss()
{
double diff;

diff = currentPrice - previousDayClosingPrice;

69
return diff / previousDayClosingPrice * 100;
}

stockType::stockType(string n, string sym, double curP,


double lowP, double highP, double preDayClP,
double fTWH, double fTWL)
{
name = n;
symbol = sym;

if (curP >= 0.0)


currentPrice = curP;
else
currentPrice = 0.0;

if (lowP >= 0.0)


lowPriceOfTheDay = lowP;
else
lowPriceOfTheDay = 0.0;

if (highP >= 0.0)


highPriceOfTheDay = highP;
else
highPriceOfTheDay = 0.0;

if (preDayClP >= 0.0)


previousDayClosingPrice = preDayClP;
else
previousDayClosingPrice = 0.0;

if (fTWH >= 0.0)


fiftyTwoWeeksHigh = fTWH;
else
fiftyTwoWeeksHigh = 0.0;

if (fTWL >= 0.0)


fiftyTwoWeeksLow = fTWL;
else
fiftyTwoWeeksLow = 0.0;
}

27.It typically inserts the code of an inline function at every location the function is
called.
28. a. equal and the constructor with default parameters.
b.
void myClass::set(int x, int y)
{
num1 = x;
num2 = y;
}

void myClass::print() const


{
cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
}

int myClass::compute(int x)

70
{
if (x > 0)
return (num1 + num2) / x;
else
return num1 -num2 + x;
}

myClass::myClass(int x, int y)
{
set(x, y);
}

c.
#include <iostream>
#include "myClass.h"

using namespace std;

int main()
{
myClass obj(23, 45);

obj.print();

cout << "Compute: " << obj.compute(10) << endl;


cout << "Are obj data members equal? " << obj.equal()
<< endl;
obj.set(34, 34);
cout << "After resetting the data member of obj, "
<< "are the data members equal? " << obj.equal()
<< endl;

return 0;
}
d.
class myClass
{
public:
void set(int x, int y) {num1 = x; num2 = y)}
void print() const;
//Function to output the values of num1 and num2;
int compute(int x);
//Function to return a value as follow:
//If x > 0, return (num1 + num2) / x;
//Otherwise, return num1 -num2 + x;

bool equal() { return (num1 == num2); }

myClass() {}

myClass(int x, int y) {num1 = x; num2 = y)}

private:
int num1 = 0;
int num2 = 0;
};

71
29.
a. myClass::count = 0;
b. myClass.incrementCount();
c. myClass.printCount();
d.

int myClass::count = 0;

void myClass::setX(int a)
{
x = a;
}

void myClass::printX() const


{
cout << x;
}

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.
h.
5
2
2
3
14
3
3

72
30.
#include <iostream>
#include "die.h"

using namespace std;

int main()
{
die rolls[100];
int maxNumRolled = 0;
int rollCount[6] = {0};
int num;
int maxRollCount = 0;
int maxTimesNumRolled;

for (int j = 0; j < 100; j++)


rolls[j].roll();

for (int j = 0; j < 100; j++)


{
num = rolls[j].getNum();
rollCount[num - 1]++;
}

for (int j = 0; j < 6; j++)


cout << (j + 1) << " " << rollCount[j] << endl;

for (int j = 0; j < 6; j++)


{
if (rollCount[j] > maxRollCount)
{
maxRollCount = rollCount[j];
maxTimesNumRolled = j + 1;
}

if (rollCount[j] != 0)
maxNumRolled = j + 1;
}

cout << "The highest number rolled is: " << maxNumRolled << endl;
cout << "This number is rolled: " << rollCount[maxNumRolled - 1]
<< " time(s). " << endl;

cout << "The number that is rolled maximum number of times: "
<< maxTimesNumRolled << endl;
cout << "This number is rolled: "
<< rollCount[maxTimesNumRolled - 1] << " time(s). " << endl;

return 0;
}

73
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

2.
animal

mammal reptile fish

dog horse cat snake alligator dolphin whale

eskimo hound shepherd burmese cyprus dusky river blue humpback

3. Some of the member variables that can be added to the class employeeType are:

department, salary, employeeCategory (such as supervisor and president), and

employeeID. Some of the member functions are: 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;
};

4. a. The functions that can be added to the class sphereType are volume and surfaceArea. No

additional data member is needed in the class sphereType.

74
b.
class sphereType: public circleType
{
public:
double volume();
double surfaceArea();

sphereType(double = 0);
};

c.
double sphereType::volume()
{
return (4.0 / 3.0) * 3.1416 * pow(getRadius(), 3.0);
}

double sphereType::surfaceArea()
{
return 4.0 * 3.1416 * pow(getRadius(), 2.0);
}

sphereType::sphereType(double r)
: circleType(r)
{
}

5. a. The base class is shoe and the derived class is runningShoe.

b. This is private inheritance.

6. a.The base class is house and the derived class is twoStory.

b. This is protected inheritance.

7. Private members of the object newCylinder are xCoordinate, yCoordinate, radius, and

height.

8.
void circle::print() const
{
cout << "x-coordinate: " << xCoordinate << endl;
cout << "y-coordinate: " << yCoordinate << endl;
cout << "radius: " << radius << endl;
}

void circle::setRadius(double r)
{
if (r >= 0)
radius = r;
else
radius = 0.0;
}

void circle::setCenter(double x, double y)

75
{
if (x >= 0)
xCoordinate = x;
else
xCoordinate = 0.0;

if (y >= 0)
yCoordinate = y;
else
yCoordinate = 0.0;
}

void circle::getCenter(double& x, double& y)


{
x = xCoordinate;
y = yCoordinate;
}

double circle::getRadius()
{
return radius;
}

double circle::area()
{
return 3.1416 * radius * radius;
}

circle::circle()
{
xCoordinate = 0.0;
yCoordinate = 0.0;
radius = 0.0;
}

circle::circle(double x, double y, double r)


{
setCenter(x, y);
setRadius(r);
}

void cylinder::print() const


{
circle.print();

cout << "height: " << height << endl;


}

void cylinder::setHeight(double h)
{
if (h >= 0)
height = h;
else
height = 0.0;

double cylinder::getHeight()
{
return height;

76
}

double cylinder::volume()
{
return circle.area() * height;
}

double cylinder::area()
{
return 2 * circle.area() + 2 * 3.1416 * getRadius() * height;
}

cylinder::cylinder()
{
height = 0.0;
}

cylinder::cylinder(double x, double y, double r, double h)


: circle(x, y, r);
{
setHeight(h);
}

Note that the functions print and area of the class cylinder overrides the function print and
area of the class circle.
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:

Omit the word const from the prototypes of the functions setHoursWorked and setPay
because these functions modify the instance variables. These prototypes should be:
void setHoursWorked(double hrsWk);
void setPay();

Replace ; after the label private with :. This statement should be

private:

10. a. Omit semicolon at the end of the first statement. Omit const from the heading of the function

power because it manipulates data, so it cannot be a constant function. Insert semicolon after }.

A correct definition of class derivedFromTemp is:

class derivedFromTemp: public temp


{
public:
void print();
//outputs the values of all the instance variables.
void setZ(double);

77
//sets the value of z according to the parameter.
double getZ();
//returns the value of z.
double power();
//returns x to the power of z.

derivedFromTemp();
//sets the values of instance variables to "",
//0.0, and 0.0, respectively.
derivedFromTemp(string, double, double);
//sets the values of instance variables according,
//to the parameters.
private:
double z;
};

b. The function setPay of the class hourlyEmployee overloads the function setPay of the

class employee because they have different parameter list.

c.
void hourlyEmployee::setData(string n, string d, int a,
double p, double hrsWk, double payRate)
{
employee::setData(n, d, a, p);

if (hrsWk >= 0)
hoursWorked = hrsWk;
else
hoursWorked = 0.0;

if (payRate >= 0)
hourlyPayRate = payRate;
else
hourlyPayRate = 0;
}

void hourlyEmployee::setHoursWorked(double hrsWk)


{
if (hrsWk >= 0)
hoursWorked = hrsWk;
else
hoursWorked = 0.0;
}
double hourlyEmployee::getHoursWorked() const
{
return hoursWorked;
}

void hourlyEmployee::setHourlyPayRate(double payRate)


{
if (payRate >= 0)
hourlyPayRate = payRate;
else
hourlyPayRate = 0;
}

double hourlyEmployee::getHourlyPayRate() const

78
{
return hourlyPayRate;
}

void hourlyEmployee::setPay()
{
employee::setPay(hoursWorked * hourlyPayRate);
}

hourlyEmployee::hourlyEmployee(string n, string d, int a,


double p, double hrsWk, double payRate)
{
setData(n, d, a, p, hrsWk, payRate);
}
11. a.

void print() const;

b.
void set(int, int, int);
void get(int&, int&, int&);

12. In overriding a public member function of a base class, in the derived class, the corresponding function

must have the same name, number, and types of parameters. In other words, the name of the function

being redefined in the derived class must have the same name and the same set of parameters. In

overloading, the corresponding functions in the base class and the derived class have the same name

but different sets of parameters.

13. First a constructor of class one will execute, then a constructor of class two will execute, and

finally a constructor of class three will execute.

14. a. None.

b. The member functions print, set, and sum.

15. a. Invalid. z is an instance variable of the derived class, it cannot be accessed by the members of

the class smart.

b. Invalid. secret is a private member of the class smart. It cannot be accessed directly
outside of the class. Also z is a private member of the class superSmart. It cannot be
accessed directly outside of the class.

c. Valid
d. Invalid. smart is the name of a class, not an object of this class. It cannot be used to call its
member function print.

79
e. Invalid. superSmart is the name of a class. It cannot be used to access its members.

16. a.
smart::smart()
{
x = 0;
y = 0;
}
b.
superSmart:: superSmart()
{
z = 0;
}
c.
void smart::set(int a, int b)
{
x = a;
y = b;
}

d.
int smart::sum()
{
return x + y;
}

e.
int superSmart::manipulate()
{
return static_cast<int>(pow(sum(), z * 1.0);
}

17. Between the preprocessor directive #ifndef and #endif. The definitions of the classes one

and two can be placed between these directives as follows:

#ifndef H_one #ifndef H_two


#define H_one #define H_two

//place the definition of the //place the definition of the


//class one here //class two here

#endif #endif

18. a. istream b. ostream

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

80
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 functions) of the derived class

through the public or protected members of the base class.

20. In a protected inheritance, the public members of the base class are protected members of

the derived class. They can be accessed by the member functions (and friend functions) of the

derived class. The protected members of the base class are protected members of the

derived class. They can be 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 functions) of the derived class through the public or protected members of the

base class.

21. In a public inheritance, the public members of the base class are public members of the

derived class. They can be accessed by the member functions (and friend functions) of the

derived class. The protected members of the base class are protected members of the

derived class. They can be 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 functions) of the derived class through the public or protected members of the

derived class.

22. The private members of a class cannot be directly accessed by the member functions of the

derived class. The protected members of the base class can be directly accessed by the

member functions of the derived class.

81
23. The protected members of a base class can be directly accessed by the member functions of

the derived class, but they cannot be directly accessed in a program that uses that class. The

public members of a class can be directly accessed by the member functions of any derived

class as well as in a program that uses that class.

24. a. setZ and secret

b. getX, getY, mystryNum, and the default constructor.


c. class myClass: public base
{
}

d. The members setXYZ, setX, getX, setY, getY, mystryNum, and print are public
members of the class myClass; and the members z and setZ, and secret are
protected members of the class myClass. The private members x and y of the
class base are hidden in class myClass and they can be accessed in class
myClass only through the protected and public members of class base.

25. a. class yourClass: protected base


{
}

b. The members setXYZ, setX, getX, setY, getY, mystryNum, and print, z, setZ, and
secret are protected members of the class yourClass. The private members x
and y of the class base are hidden in class yourClass and they can be accessed in
class yourClass only through the protected and public members of class base.

26. a. class dummyClass: base


{
}

or

class dummyClass: private base


{
}

b. All members of the class base becomes private members in class dummyClass.

27. a. Because the memberAccessSpecifier is not specified, it is a private inheritance.

b. All members of the class base becomes private members in class derived.

28. The function setX is a protected member of the class classA. In Line 11, it cannot be
directly accessed by the object aObject.
29. a.
void base::print() const

82
{
cout << "num = " << num << ", x = " << x;
}

double base::compute(int n)
{
return n + manipulate(n, n);
}

double base::manipulate(int a, int b)


{
return num * a + x * b;
}
b.
void derived::print() const
{
base::print();
cout << ", z = " << z;
}

double derived::compute(int a, double b)


{
return base::compute(a) + z * manipulate(0, b);
}

c.
num = 2, x = 5.50
59.50
num = 3, x = 1.50, z = 2.00
17.50

30.
2 This is the base class
Derived class: 7
10 Hello Base

83
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;
2. a. Valid

b. Valid;
c. Invalid; p3 is a pointer of type double and p2 is a pointer variable of type int. The value of p2
cannot be assigned to p3.
d. Valid;
e. Valid; *p3 is a variable of type double and num1 in an int variable. An int value can be
assigned to a variable of type double with 0 decimal part.
f. Invalid; num1 is an int variable and p2 is a pointer variable. The value of p2 cannot be assigned
to num1.
g. Invalid; p1 is a pointer of type int, so it can only point to a memory of type int. &p2 gives the
address of p2 and p2 is a pointer variable. So the value &p2 cannot be assigned to p1.
h. Invalid; &num1 gives the address of num1, which is an int variable and p3 is a pointer variable of
type double. The address of num1 cannot be assigned to p3.
i. Valid;
j. Invalid; num2 is a variable of type int. It cannot store the address of a memory location.

3. a. To create a pointer, in the variable declaration, operator * is placed between the data type and

the variable name. For example 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.

4. This statement could misinterpret that q is a pointer variable. However, q is an int variable.

5. *numPtr given the address of the memory location to which numPtr points, while &numPtr
gives the address of numPtr.

6. 57 80
80 80
7. numPtr = &num;
(*numPtr)++;
8. sunny cloudy

84
cloudy cloudy
9. 33.8 3.8
33.8 3.8
10. In the last four cout statements, use the dereferencing operator to access the values of the
radius of the base (*baseRadius) and height (*height). The correct code is:

double *baseRadius;
double *height;

cout << fixed << showpoint << setprecision(2);

baseRadius = new double;


*baseRadius = 1.5;

height = new double;

*height = 2 * (*baseRadius);

baseRadius = new double;


*baseRadius = 4.0;

cout << "Radius of the base: " << *baseRadius << endl;
cout << "Height: " << *height << endl;
cout << "Volume: " << 3.14 * (*baseRadius) * (*baseRadius)
<< endl;
cout << "Surface area: "
<< 2 * 3.14 * (*baseRadius) * (*height) << endl;
Output:
Radius of the base: 4.00
Height: 3.00
Volume: 50.24
Surface area: 75.36
11. The correct code is:
double *length;
double *width;

cout << fixed << showpoint << setprecision(2);

length = new double;


*length = 6.5;

width = new double;


*width = 3.0;

cout << "Area: " << (*length) * (*width) << ", ";
cout << "Perimeter: " << 2 * (*length + *width) << endl;

Output:
Area: 19.50, Perimeter: 19.00

12. 10 18
23 8

85
17 4
13. Trip total cost: $550.00
Highest trip cost: $275.00
14. In Line 4, &speed gives the address of speed not the address of memory location speed is
pointing to. Replace &speed with *speed. The statement in Line 5, stores 8.5 in the
memory location pointed to by travelTime. However, no such memory location exists. Add
statement to allocate a memory space of type double and store the address of the allocated
memory space in travelTime. The statement in Line 7 stores the value of an expression of
type double. However, distance is pointer variable. In this statement, replace distance
with *distance. The correct code is:

int *speed = new int; //Line 1


double *travelTime; //Line 2
double *distance; //Line 3

*speed = 65; //Line 4

travelTime = new double; //Line **


*travelTime = 8.5; //Line 5

distance = new double; //Line 6

*distance = (*speed) * (*travelTime); //Line 7

cout << *distance << endl; //Line 8

Output: 552.5

15. In Line 6, the operator delete deallocates the memory space to which nextPtr points. So the
expression *nextPtr, in Line 9, does not have a valid value.

16. 54 49
17. 12 37 78 62 62 13
18. 7 9 13 19 27
19. numPtr = 1058 and gpaPtr = 2024

20. The operator new allocates memory space of a specific type and returns the address of the

allocated memory space.

21. The operator delete deallocates the memory space to which a pointer points.

22. 10 80 90 60 100
Sum = 340

23. a. sales = new double[50];

86
b. for (int i = 0; i < 50; i++)
cin >> sales[i];
c. int maxIndex = 0;
for (int i = 1; i < 50; i++)
if (sales[maxIndex] < sales[i])
maxIndex = i;
d. delete []sales;

24. a. for (int i = 0; i < 4; i++)


cout << strPtr[i] << " ";
cout << endl;
b. delete strPtr;

25. Because at compile time dynamic arrays have no first and last elements, so the functions begin

and end cannot be called on dynamic arrays.

26. Because p is a dynamic array, the range-based loop in Line 5 cannot be used on p.

27. In a shallow copy of data, two or more pointers point to the same memory space. In a deep copy
of data, each pointer has its own copy of the data.
28. a. The statement in Line 4 copies the value of myPtr into yourPtr. After this statement
executes, both myPtr and yourPtr point to the same memory space. The statement in Line 6
deallocates the memory space pointed to by yourPtr, which in turn invalidates myPtr.
Therefore, the values printed by the statement in Line 7 are unpredictable.
b. The statement in Line 5 copies the value of myListPtr into yourListPtr. After this
statement executes, both myListPtr and yourListPtr point to the same array. The statement
in Line 6 deallocates the memory space, which is an array, pointed to by yourListPtr, which
in turn invalidates myListPtr. Therefore, the values printed by the statement in Line 8 are
unpredictable.
29. int *myList;
int *yourList;

myList = new int[5];


myList[0] = 8;
for (int i = 1; i < 5; i++)
myList[i] = i * myList[i - 1];

yourList = new int[5];


for (int i = 0; i < 5; i++)
yourList[i] = 2 * myList[i];
30. a. int ** votes;
b. votes = new int* [50];
for (int i = 0; i < 50; j++)
votes[i] = new int[10];

87
c. for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 10; j++)
cout << votes[i][j] << " ";
cout << endl;
}

d. for (int i = 0; i < 50; i++)


delete [] votes[i];

delete [] votes;

31. The copy constructor makes a copy of the actual variable.


32.The copy constructor executes when a variable is passed by value and when a variable is declared
and initialized using another variable.
33. Classes with pointer data members should include the destructor, overload the assignment
operator, and explicitly provide the copy constructor by including it in the class definition and
providing its definition.
34. 5
small: --
x: 2, y = 3
*-*-*-*-*-*-*-*-*-*-*-*

8
small: --
x: 3, y = 5
35. 5
small: --
x: 2, y = 3
*-*-*-*-*-*-*-*-*-*-*-*

17
small: --
x: 3, y = 5
noSmall--- z: 9
36. In compile-time binding, the compiler generates the necessary code to call a function. In run-time binding,
the run-time system generates the necessary code to make the appropriate function call.

37. Yes.
38.
public studentType: public personType
{
public:
virtual void print() = 0;
virtual void calculateGPA() = 0;
void setID(long id);
void setCourses(const string c[], int noOfC);
void setGrades(const char cG[], int noOfC);

void getID();
void getCourses(string c[], int noOfC);

88
void getGrades(char cG[], int noOfC);
void studentType(string fName = "", string lastName = "",
long id, string c[] = NULL,
char cG[] = NULL, int noOfC = 0);

private:
long studentId;
string courses[6];
char coursesGrade[6];
int noOfCourses;
}

39. a. Because employeeType is an abstract class, you cannot instantiate an object of this class.
Therefore, this statement is illegal.
b. This statement is legal.
c. This statement is legal.

89
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

2. To overload an operator for a class:

a. Include the statement to declare the function to overload the operator (that is, the operator
function) prototype in the definition of the class.
b. Write the definition of the operator function.

3. b

4. a. Using the pointer this.

b. The statement return this; returns the address of the object while the statement return

*this;returns the value of the object.

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.

6. A friend function is nonmember of a class while a member function is a member of a class.

7. d; Because the left operand of << is a stream object, which is not of the user-defined class type.

8. a. friend bool before(const dateType&, const dateType&);

b. bool before(const dateType& obj1, const dateType& obj2)


{
if ((obj1.dYear < obj2.dYear) ||
(obj1.dYear == obj2.dYear && obj1.dMonth < obj2.dMonth) ||
(obj1.dYear == obj2.dYear && obj1.dMonth == obj2.dMonth
&& obj1.dDay < obj2.dDay))
return true;
else
return false;
}
9. a. One b. Two

10. The far left operand must be of type temp.


11. object1.operator+(object2)

90
12. operator+(object1, object2)
13. a. bool b. bool

14. a. friend istream& operator>>(istream&, strange&);


b. const strange& operator=(const strange&);
c. strange operator+(const strange&) const;
d. bool operator==(const strange&) const;
e. strange operator++(int);
15. a. friend strange operator+(const strange&, const strange&);
b. friend bool operator==(const strange&, const strange&);
c. friend strange operator++(strange&, int);

16. The statement in Line 4, overloads the binary operator * for the class opOverload. Because * is a
member function of the class opOverload, it must have one parameter. The correct statement is:

opOverload operator*(const opOverload& obj); //Line 4

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

18. In Line 4, the function operator + is overloaded as member of the class, so it should have only one
parameter. The correct statement is:

discover operator+(const discover& a); //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
20. In Line 3, the function operator+ is a friend function of the class, so it cannot be constant.

friend mystery operator+(const mystery& a,


const mystery& b); //Line 3

21. In Line 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 heading 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:

friend findErrors operator*(const findErrors& a,


const findErrors& b); //Line 3
double operator*(const findErrors& a,

91
const findErrors& b) //Line 10

temp.first = a.first * b.first; //Line 13


temp.second = b.second * b.second; //Line 14

22. a. Because leftmost operand of << is not an object of the class type for which << is overloaded.
b. Because leftmost operand of >> is not an object of the class type for which >> is overloaded.
23. A reference to an object of the class istream.
24. A reference to an object of the class ostream.
25. The function that overloads the pre increment operator has no parameter, while the function that overloads
the post increment operator has one (dummy) parameter.
26. To avoid self assignment.
27. a. None b. One
28. One b. Two.
29.
class complexType
{
//overload the stream insertion and extraction operators
friend ostream& operator<<(ostream&, const complexType&);
friend istream& operator>>(istream&, complexType&);

public:
void setComplex(const double& real, const double& imag);
//set the complex number according to the parameters
//Postcondition: realPart = real; imaginaryPart = imag

complexType(double real = 0, double imag = 0);


//constructor
//initialize the complex number according to the parameters
//Postcondition: realPart = real; imaginaryPart = imag

complexType operator+(const complexType& otherComplex) const;


//overload +
complexType operator*(const complexType& otherComplex) const;
//overload *

complexType operator~() const;

double operator!() const;

bool operator==(const complexType& otherComplex) const;


//overload ==

private:
double realPart; //variable to store the real part
double imaginaryPart; //variable to store the imaginary part
};

// Definitions of operator~ and operator!

92
complexType complexType::operator~() const
{
complexType temp = *this;

temp.imaginaryPart = -temp.imaginaryPart;

return temp;
}

double complexType::operator!() const


{
return (pow((realPart * realPart +
imaginaryPart * imaginaryPart), 0.5));
}

30.
class complexType
{
//overload the stream insertion and extraction operators
friend ostream& operator<<(ostream&, const complexType&);
friend istream& operator>>(istream&, complexType&);

friend complexType operator+(const complexType& one,


const complexType& two);
//overload +
friend complexType operator*(const complexType& one,
const complexType& two);
//overload *

friend complexType operator~(const complexType&);

friend double operator!(const complexType&);

friend bool operator==(const complexType& one,


const complexType& two);
//overload ==

public:
void setComplex(const double& real, const double& imag);
//set the complex number according to the parameters
//Postcondition: realPart = real; imaginaryPart = imag

complexType(double real = 0, double imag = 0);


//constructor

private:
double realPart; //variable to store the real part
double imaginaryPart; //variable to store the
//imaginary part
};

//Definitions of operator~ and operator!


complexType operator~(const complexType& cObj)
{
complexType temp = cObj;

93
temp.imaginaryPart = - temp.imaginaryPart;

return temp;
}

double operator!(const complexType& cObj)


{
return (pow((cObj.realPart * cObj.realPart +
cObj.imaginaryPart * cObj.imaginaryPart), 0.5));
}

31. When the class has pointer data members.


32. a. Explicitly overload the assignment operator; b. Include the copy constructor, and c. Include the
destructor

33. Error in Line 4. A template instantiation can be for only a built-in type or a user-defined type. The word
“type” between the angular brackets must be replaced either with a built-in type or a user-defined type.
34. a. strange<int> sObj;
b. bool operator==(const strange&) const;
c.
bool strange::operator==(const strange& right) const
{
return (a == right.a && b == right.b);
}

35. a. 12 b. Sunny Day


36. a. 376.00 b. LisaRobinson
37.
template <class Type>
void swap(Type &x, Type &y)
{
Type temp;
temp = x;
x = y;
y = temp;
}
38.
a. (i) Function prototypes to appear in the definition of the class:
newString operator+(const newString& right) const;
newString operator+(char ch) const;

private:
char* strConcat(char *str2);
char* strConcat(char * &str1, const char *str2);

94
(ii) Definitions of the functions to overload +

newString newString::operator+(const newString& rightStr)


{
newString temp = *this;

strConcat(temp.strPtr, rightStr.strPtr);

temp.strLength = strlen(temp.strPtr);

return temp;
}

newString newString::operator+(char ch)


{
newString temp = *this;

char *temp1 = strPtr;


char chStr[2];

chStr[0] = ch;
chStr[1] = '\0';

strConcat(temp.strPtr, chStr);

temp.strLength = strlen(temp.strPtr);

return temp;
}

char* newString::strConcat(char *str2)


{
char *str;

int len1 = strLength;


int len2 = strlen(str2);

int len = strLength + len2;

str = new char[len + 1];

for (int i = 0; i < len1; i++)


str[i] = strPtr[i];
for (int i = len1; i < len; i++)
str[i] = str2[i - len1];
str[len] = '\0';

return str;
}

char* newString::strConcat(char * &str1, const char *str2)


{
char *temp;
int len1 = strlen(str1);
int len2 = strlen(str2);

temp = new char[strlen(str1) + 1];


strcopy(temp, str1);

95
delete [] str1;

str1 = new char[len1 + len2 + 1];

for (int i = 0; i < len1; i++)


str1[i] = temp[i];
for (int i = len1; i < len1 + len2; i++)
str1[i] = str2[i - len1];

str1[len1 + len2] = '\0';

return str1;
}

b.
(i) Function prototypes to appear in the definition of the class:

const newString& operator+=(const newString& right);


const newString& operator+=(char ch);

(ii) Definitions of the functions to overload +=

const newString& newString::operator+=(const newString& rightStr)


{
strConcat(strPtr, rightStr.strPtr);

strLength = strlen(strPtr);

return *this;
}

const newString& newString::operator+=(char ch)


{
char chStr[2];

chStr[0] = ch;
chStr[1] = '\0';

strConcat(strPtr, chStr);
strLength = strlen(strPtr);

return *this;
}

39. These statements generate and output a random integer between 10 and 25.

96
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;

2. The statements that may generate an exception are placed in a try block. The try block also

contains statements that should not be executed if an exception occurs.

3. The program will terminate with an error message.

4. If no exception is thrown in a try block, all catch blocks associated with that try block are

ignored and program execution resumes after the last catch block.

5. At most one.

6. The catch block with three elipses as parameters.

7. The thrown value then may not be accessible in the catch block exception handling code.

8. A throw statement.

9. The object being thrown can be either a specific object or an anonymous object.

10. The catch block has no associated try block, that is, the catch block does not follow any try

block. Also, the try block has no associated catch block, that is, there is no catch block that

follows the try block. The correct code is:

double balance = 25000;


double intRate;

try
{
cout << "Enter the interest rate: ";
cin >> intRate;
cout << endl;

if (intRate < 0.0)


throw intRate;

cout << "Interest: $" << balance * intRate / 100 << endl;
}
catch (double x)
{
cout << "Negative interest rate: " << x << endl;
}

97
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

if (raise < 0.0) //Line 8


throw raise; //Line 9

cout << "Salary increase: $"


<< salary * raise / 100 << endl; //Line 10
cout << "Exiting the try block." << endl; //Line 11
} //Line 12
catch (double x) //Line 13
{ //Line 14
cout << "Negative raise: " << x << endl; //Line 15
} //Line 16

(In a and b, the user input is shaded.)


a. Enter the raise: 5

Salary increase: $3900


Exiting the try block.

b. Enter the raise: -4

Negative raise: -4

12. a. The try block is between lines 4 and 17.

b. There are two catch blocks in the code. The first catch block between 18 and 22; the second

catch block is between lines 23 and 28.

c. The parameter of the catch block at line 18 is num and it is of type int. The parameter of the

catch block at line 23 is dec and its type is double.

d. This code contains the following throw statements:

throw numOfItems; //Line 10


throw unitCost; //Line 15

98
13. (In the following, the user input is shaded.)
a. Enter the number of items: 25

Enter the cost of one item: 5.50

Total cost: $137.50


b. Enter the number of items: -55

Negative number of items: -55


Numer of items must be nonnegative.
c. Enter the number of items: 37

Enter the cost of one item: -4.5

Negative unit cost: -4.50


Unit cost must be nonnegative.
d. Enter the number of items: -10

Negative number of items: -10


Numer of items must be nonnegative.
14. a. Entering the try block.
Exception: Lower limit violation.
After the catch block

b. Entering the try block.


Exiting the try block.
After the catch block

15. a. 55
Exiting the try block.
b. Exception: Division by 0
c. Exception: Total score is out of range.
d. Exception: Division by 0
16. class exception
17. a. class out_of_range
b. class length_error
c. class runtime_error

18. If you define your own exception class, you typically include constructors and the function what
in that class.
19. A throw statement.

20. One possible answer is:

#include <string>

using namespace std;

99
class tornadoException
{
public:
tornadoException()
{
message = "Tornado: Take cover immediately!";
}

tornadoException(int m)
{
string str = "";
int rem;

while (m != 0)
{
rem = m % 10;
str = static_cast<char>(rem + static_cast<int> ('0')) + str;
m = m / 10;
}

message = "Tornado: " + str + " miles away; and approaching!";


}

string what()
{
return message;
}

private:
string message;
};

If we write the definition of the member functions of the class tornadoException outside
the class, then the definition of the class tornadoException and the definitions of the
member functions are as follows.
#include <string>

using namespace std;

class tornadoException
{
public:
tornadoException();
tornadoException(int m);
string what();

private:
string message;
};

Definition of the member functions:

tornadoException::tornadoException()
{
message = "Tornado: Take cover immediately!";
}

100
tornadoException::tornadoException(int m)
{
string str = "";
int rem;

while (m != 0)
{
rem = m % 10;
str = static_cast<char>(rem + static_cast<int> ('0')) + str;
m = m / 10;
}

message = "Tornado: " + str + " miles away; and approaching!";


}

tornadoException::string what()
{
return message;
}

21. (Assume that the definition of the class tornadoException is in the header file
tornadoException.h.)
#include <iostream>
#include "tornadoException.h"

using namespace std;

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;
}

22. If the exception is thrown with the default constructor, the output is:
Immediate attention required!
myException thrown!

101
If the exception is thrown with the constructor with parameters with the actual parameter, "May

Day, May Day", the output is:

Attention required!
May Day, May Day
23. A function specifies the exceptions it throws in its heading using the throw clause.

24. Terminate the program; fix the error and continue; and log the error and continue.

25. (1) Do nothing; (2) Partially process the exception and throw the same exception or a new

exception; (3) Throw a new exception.

102
Chapter 15
1. a. true; b. true; c. false; d. false; e. false; f. false; g. true; h. true;
2. a. The case in which the solution to the problem is obtained directly.
b. The case in which the solution is defined in terms of smaller versions of itself.
3. A definition in which something is defined in terms of a smaller version of itself.
4. An algorithm that finds the solution to a given problem by reducing the problem to smaller
versions of itself is called a recursive algorithm.
5. Because a base case stops the recursion.
6. a. A function is called directly recursive if it calls itself.
b. A function that calls another function and eventually results in the original function call is
said to be indirectly recursive.
c. A recursive function in which the last statement executed is the recursive call is called a
tail recursive function.
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.
8. a. The statements in Lines 3 and 4.
b. The statements in Lines 5 to 15.
c. It is a valid call. The output is: % & ' ( ) * + , - . / 0 1 0
d. It is an invalid call. Infinite loop.
e. It is a valid call. The output is: ] \ [ Z Z Z Z Z Z 0
9. a. 8 5 2 b. 7 c. 6 3 d. -85

10. a. Infinite loop, continuously printing Nonegative. b. Zero!


c. Negative Negative Zero!

11. a. 4 12 28
b. 5 15 34 72 148
c. 2 8 21 47 98
d. It does not produce any output.
12. a. 24 b. -2 c. 149 d. 26
13. a. 0
b. 4
c. 8

103
d. 162
14. a. 28 28 28 28 10 8 8 2 0 0 0 0 2
b. 23 23 3 2 2 2 2 2 2 2 1 0 0 1
c. 8 8 8 8 8 8 5 3 2 1 0 0 1
d. 36 36 20 16 4 0 0 0 0 4

15. a. 10 b. 21 c. -23 d. 2 e. -56

16. Suppose that low specifies the starting index and high specifies the ending index in the
array. The elements of the array between low and high are to be reversed.
if (low < high)
{
a. swap(list[low], list[high])
b. reverse the elements between low + 1 and high - 1
}
17.
0 if n = 0

multiply(m, n) = m if n = 1
m + multiply(m, n − 1) otherwise

The base cases are when n = 0 or n = 1. The general case is specified by the option otherwise.
18. a.
1 if r = 0 or n = r

c(n, r ) = n if r = 1
c(n − 1, r − 1) + c(n − 1, r ) otherwise

The base cases are when r = 0, r = 1, or n = r. The general case is specified by the option
otherwise.

b. C(5,3) = 10 ; C(9,4) = 126.

19. A selection control structure.


20. When executing a recursive function, every (recursive) call requires the system to allocate
memory space for its formal parameters and (automatic) local variables, and then deallocate
the memory space when the function exits. Therefore, memory space and for each recursive
call, and computer time is required to allocate and deallocate that memory space.

104
Chapter 16
1. a. true; b. false; c. false; d. true; e. false; f. false; g. false; h. true

2. a. 6
b. 10
c. 1
d. 3
e. 10
3. int seqOrderedSearch(const int list[], int listLength,
int searchItem)
{
int loc;
bool found = false;

for (loc = 0; loc < listLength; loc++)


if (list[loc] >= searchItem)
{
found = true;
break;
}

if (found)
if (list[loc] == searchItem)
return loc;
else
return -1;
else
return -1;
}
4. a. 2 b. 7 c. 11 d. 9 e. 13

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

6. List before the first iteration: 82, 17, 40, 28, 15, 55, 46, 93, 6, 67, 11, 3
List after the first iteration: 17, 40, 28, 15, 55, 46, 82, 6, 67, 11, 3, 93

105
List after the second iteration: 17, 28, 15, 40, 46, 55, 6, 67, 11, 3, 82, 93
List after the third iteration: 17, 15, 28, 40, 46, 6, 55, 11, 3, 67, 82, 93
List after the fourth iteration: 15, 17, 28, 40, 6, 46, 11, 3, 55, 67, 82, 93
List after the fifth iteration: 15, 17, 28, 6, 40, 11, 3, 46, 55, 67, 82, 93
List after the sixth iteration: 15, 17, 6, 28, 11, 3, 40, 46, 55, 67, 82, 93
List after the seventh iteration: 15, 6, 17, 11, 3, 28, 40, 46, 55, 67, 82, 93
List after the eighth iteration: 6, 15, 11, 3, 17, 28, 40, 46, 55, 67, 82, 93
List after the ninth iteration: 6, 11, 3, 15, 17, 28, 40, 46, 55, 67, 82, 93
List after the tenth iteration: 6, 3, 11, 15, 17, 28, 40, 46, 55, 67, 82, 93
List after the eleventh iteration: 3, 6, 11, 15, 17, 28, 40, 46, 55, 67, 82, 93

7. 4

8. a. 6 b. 6

9. a. 8, 12, 18, 25, 38, 45, 74, 60, 30


b. 10

10. a. 1 b. 8 c. 42

11. Bubble sort: 21,121,750; selection sort: 21,121,750; insertion sort: 10,567,374
12. a.
void bubbleSort(int list[], int length)
{
int temp;
int iteration;
int index;

bool done = false;

iteration = 1;

while (iteration < length && !done)


{
done = true;
for (index = 0; index < length - iteration; index++)
if (list[index] > list[index + 1])
{
temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
done = false;
}
}
}
b. 5.

13. 26

14. 5, 12, 25, 32, 38, 46, 58, 62, 85, 90, 97, 105, 110
a.

106
Iteration first last mid list[mid] No. of comparisons
1 0 12 6 58 2
2 0 5 2 25 2
3 3 5 4 38 2
4 3 3 3 32 1 (found is true)
5 2 1 the loop stops unsuccessful search

The item is found at location 3 and the total number of comparisons is 7.

b.
Iteration first last mid list[mid] No. of comparisons
1 0 12 6 58 2
2 0 5 2 25 2
3 0 1 0 5 2
4 1 1 1 12 2
5 2 1 the loop stops unsuccessful search

This is an unsuccessful search. The total number of comparisons is 8.

c.
Iteration first last mid list[mid] No. of comparisons
1 0 12 6 58 2
2 7 12 9 90 2
3 10 12 11 105 1 (found is true)

The item is found at location 9 and the total number of comparisons is 5.

d.
Iteration first last mid list[mid] No. of comparisons
1 0 12 6 58 2
2 7 12 9 90 2
3 7 8 7 62 2
4 7 6 the loop stops unsuccessful search

This is an unsuccessful search. The total number of comparisons is 6.

15. a. 6 b. 7 c. 8 d. 7 e. 1 f. 3 g. 8
16.
void descendingToAscending(int list[], int length)
{
int temp;
int index;
int last = length - 1;

for (index = 0; index <= (length - 1) / 2; index++)


{
cout << last << endl;
temp = list[index];
list[index] = list[last];
list[last] = temp;
last--;
}
}
17. To use a vector object in a program, the program must include the header file vector.

107
18. a. This statement declares list to be a vector object of size 50. The data type of the elements that
the object list can store is int.
b. This statement declares nameList to be an empty vector object. The data type of the elements
that the object nameList can store is string.
19. 5 11 24 51 106 217 440
20. a. Sheila -- Anita -- Cecelia -- Henry --
b. Danny -- -- Sheila -- Anita -- Cecelia -- Henry --
c. The size of classList in (a) is 4. The size of classList in (b) is 6.
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] << " ";

cout << endl;

22. 5 23
23. a. cout << myList.front() << " " << myList.back() << endl;
b length = myList.size();

c.
for (int i = 0; i < myList.size(); i++)
cout << myList[i] << " ";

cout << endl;

24. Size indicated the number of elements currently in the vector. Capacity indicated the number of
elements that can be currently added to the vector.

25. 0 2 6 12 20
26. 2 0 -6 -24 -78

108
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;

2. The two typical components of a single linked list are data and link. The component data stores the
relevant information and the component link stores the address of the next node or the value
nullptr.
3. nullptr
4. If the linked list is empty, the value nullptr is stored in first; otherwise the address of the first
node of the linked list is stored in first.
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.
6. a. 12
b. 92 65
c. 80
d. 46
e. No output; because last->link is nullptr so last->link->info does not exist.
f. 5
7. a. true
b. true
c. false
d. true
e. true
f. false
8. a. Sets the link field of the node with info 5 to nullptr, deletes the last node from the linked list,
and deallocates the memory occupied by the last note, and after deleting the last node sets list
point to the last node of the list.
b. Deletes the nodes with info 5 from the linked list.
c. Sets the info of the first node to 58.
d. Deletes the node with info 86 from the linked list, and deallocates the memory occupied by this
node.
e. Sets the info of the node before temp to 60.
f. Deletes the nodes with info 92, 65, and 80 from the linked list.
9. a. p->link->info = 24;
b. q = current->link;
c. first = first->link;

109
d. trail = p->link;
e. p = nullptr;
f. temp->link->info = 54;
g. while (first->info != 5)
first = first ->link;
10. a. Valid
b. Valid
c. Valid
d. Invalid; current->link is a pointer whereas temp->info is an int value.
e. Invalid; p is a pointer variable whereas *last is a struct.
f. Invalid; first is a pointer variable whereas 90 is a nonzero int value.
g. Valid
h. Invalid; current->info is an int variable whereas temp->link is a pointer.
i. Valid
j. Valid; This statement will result in execution error because last->link->link is nullptr,
so last->link->link does not exist.
k. Invalid ; trail does not point to any node in the list, so trail->link->link->info does
not exist.
11. a. while (first != nullptr)
first = first->link;
b. q = new nodeType;
q->info = 17;
q->link = current->link;
current->link = q;
c. q = temp->link;
q->link = nullptr;
delete last;
last = q;
d. q = p->link;
p->link = current;
delete q;
e. q = current->link;
q->link = temp->link;
temp->link = q;
current->link = temp;

12. a. 47 12 92 65 80 46 5 78
b. 78
c. This is an infinite loop, continuously printing 12.
13. 65 5 78
14. After the execution of the statement in Line 4, current is nullptr, so current ->info does not
exist. This code will result in run time error.

110
15. 39 26 78
16. 46 52 91 72

17. nodeType head, p, q;

head = new nodeType;


head->info = 72;
head->link = nullptr;
p = new nodeType;
p->info = 43;
p->link = head;
head = p;
p = head->link;
q = new nodeType;
q->info = 8;
q->link = nullptr;
p->link = q;
q = new nodeType;
q->info = 12;
q->link = p;
head->link = q;

p = head;
while (p != nullptr)
{
cout << p->info << " ";
p = p->link;
}
cout << endl;

The output of this code is: 43 12 72 8

18.
a. list
b. 25 16 12
c. nodeType *q;

ptr = list->link;
q = new nodeType;
q->info = 45;
q->link = ptr->link;
ptr->link = q;
d. nodeType *q;

q = new nodeType;
q->info = 58;
q->link = list;
list = q;
Insertion of 58 requires us to the change the value of the pointer that was pointing to the
first node of the linked list.

e. ptr = list;
list = list->link;

111
delete ptr;

Deletion of 25 requires us to the change the value of the pointer that was pointing to the first node
of the linked list.

19. a. The function begin returns an iterator to the first node of a linked list.
b. The function end returns an iterator one past the last node of a linked list.

20. The function insertFirst of the class unorderedLinkedList insert a node at the beginning
of a linked list, whereas the function insertFirst of the class orderedLinkedList insert
the node at the proper place in the list so that the resulting list remains sorted.

21. The item to be deleted is not in the list.


90 15 65 36 30 27

22. list = 16 120 64 40 12 45 35 83 23 11 98


The item to be deleted is not in the list.
The item to be deleted is not in the list.
copyList = 16 120 64 40 12 45 35 83 23 11 98

23.
doublyLinkedList<Type>

#count: int
#*first: nodeType<Type>
#*last: nodeType<Type>

+operator=(const doublyLinkedList<Type> &):


const doublyLinkedList<Type>&
+initializeList(): void
+isEmptyList() const: bool
+print() const: void
+reversePrint() const: void
+length() const: int
+front() const: Type
+back() const: Type
+search(const Type&) const: bool
+insert(const Type&): void
+deleteNode(const Type&): void
+doublyLinkedList()
+doublyLinkedList(const doublyLinkedList<Type>&)
+~doublyLinkedList()
-copyList(const doublyLinkedList<Type>&): void

112
24.

dvdType

-dvdTitle: string
-movieStar1: string
-movieStar2: string
-movieProducer: string
-movieDirector: string
-movieProductionCo: string
-copiesInStock: int

+operator<<(ostream&, const dvdType&): friend ostream&


+setDVDInfo(string, string, string, string,
string, string, int): void
+getNoOfCopiesInStock() const: int
+checkOut(): void
+checkIn(): void
+printTitle() const: void
+printInfo() const: void
+checkTitle(string): bool
+updateInStock(int): void
+setCopiesInStock(int): void
+getTitle() const: string
+dvdType(string = "", string = "", string = "",
string = "", string = "", string = "",
int = 0)
+operator==(const dvdType&) const: bool
+operator!=(const dvdType&) const: bool

25.

dvdListType

+dvdSearch(string) const: bool


+isDVDAvailable(string) const: bool
+dvdCheckOut(string): void
+dvdCheckIn(string): void
+dvdCheckTitle(string) const: bool
+dvdUpdateInStock(string, int): void
+dvdSetCopiesInStock(string, int): void
+dvdPrintTitle() const: void
-searchDVDList(string, bool&,
nodeType<dvdType>* &) const: void

113
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;

2. The value of stack.top gives the number of elements in the stack and if stack.top is nonzero,

then stack.top - 1 gives the index of the top element of the stack.

3. a. 8 b. 7 c. dec = stack.top(); d. stack.pop();

4. a. 6 b. 5. c. cout << stack.top(); d. stack.push("StacksAndQueues");

5. 13
32 32 13 16 28
temp = 16
6. cin >> num;

while (cin)
{
if (!stack.isFullStack())
{
if (num >= 0)
stack.push(sqrt(num));
else
stack.push(num * num);
}
cin >> num;
}

cout << "Stack Elements: ";

while (!stack.isEmptyStack())
{
cout << " " << stack.top();
stack.pop();
}
cout << endl;

7. secretNum = 226

8. Starting from right to left, this program segment stores the 2-digit blocks of an integer into a
stack. It then finds the sum of the 2-digit blocks of the integer.

9. a. 16
b. -4
c. 39

114
d. 12
e. 15
10. a. x y + z + w t / -
b. x y z + w * - t u - s / +
c. x y + z / u v - * t / w +
d. x y / z / u v * t * w / + s -
11. a. x * y + z - t
b. x * (y + z) - w / u
c. (x - y) * (z / u) - (t + s)
d. x * (y - (z + w))

12. Chelsea Jackson


Kirk McCarthy
David Miller
Stephanie Pratt
Bianca Hollman
Katie Smith
Holly Klien

13. 1 16 27 16 5

14. In this linked implementation of stacks, the memory to store the stack elements is allocated
dynamically. Therefore, logically, the stack is never full. The stack is full only if we run out of
memory space. So it is not necessary to implement the operation to determine whether the stack
is full.
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.
16. template <class Type>
void linkedListType<Type>::printListReverse()
{
linkedStackType<nodeType<Type>* > stack;

nodeType<Type> *current;

current = first;

while (current != NULL)


{
stack.push(current);
current = current->link;
}

while (!stack.isEmptyStack())
{
current = stack.top();
cout << current->info << " ";
stack.pop();
}
cout << endl;

115
}
17. template <class elemType>
elemType second(stackType<elemType> stack)
{
elemType temp1, temp2;

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;
}

18. a. 19

b. num = queue.front();

c. queue.deleteQueue();

d. queue.addQueue(28);

19. a. 4

b. 21

c.!queue.isEmptyQueue()

d. queue.addQueue("programming")

After the insertion operation the index of the last element is 5

20. Queue elements: 20 42 5 16 30


temp = 15
21. cin >> num;

while (cin)
{

116
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

cin >> num;


} //end while

After processing these numbers, stack and queue are:

stack: 14 289 10 121 28


queue: 15 -9 21 -3 33

22. The method mystery reverses the elements of a queue of int objects and also doubles the
values of the queue elements.

23. a. 26
b. queueFront = 35; queueRear = 61.
c. queueFront = 36; queueRear = 60.

24. a. 23
b. queueFront = 63; queueRear = 21.
c. queueFront = 0; queueRear = 20.

25. a. 31
b. queueFront = 25; queueRear = 56.
c. queueFront = 26; queueRear = 55.

26. a. 1
b. queueFront = 64; queueRear = 0.
c. queueFront = 0; queueRear = 64.

27. 51

28. a. queueFront = 74; queueRear = 0.


b. queueFront = 75; queueRear = 99. Position of the removed element was 75.

29. 5 -4 5 -7 1 2 1 4 1 -2 2 -7 7 -6

117
30. The program segment uses a stack and a queue to output the difference of the successive digits of

an integer.

31. template <class Type>


void reverseStack(stackType<Type> &s)
{
linkedQueueType<Type> q;
Type elem;

while (!s.isEmptyStack())
{
elem = s.top();
s.pop();
q.addQueue(elem);
}

while (!q.isEmptyQueue())
{
elem = q.front();
q.deleteQueue();
s.push(elem);
}
}

32. template <class Type>


void reverseQueue(queueType<Type> &q)
{
stackType<Type> s;

Type elem;

while (!q.isEmptyQueue())
{
elem = q.front();
q.deleteQueue();
s.push(elem);
}

while (!s.isEmptyStack())
{
elem = s.top();
s.pop();
q.addQueue(elem);
}
}

33. template <class Type>


int queueType<Type>::queueCount()
{
return count;
}

118
34.
linkedStackType<Type>

-*stackTop: nodeType<Type>

+operator=(const linkedStackType<Type>&):
const linkedStackType<Type>&
+isEmptyStack() const: bool
+isFullStack() const: bool
+initializeStack(): void
+push(const Type&): void
+top() const: Type
+pop(): void
+linkedStackType()
+linkedStackType(const linkedStackType<Type>&)
+~linkedStackType()
-copyStack(const linkedStackType<Type>&): void

35.
queueADT<Type>

+isEmptyQueue() const = 0: virtual bool


+isFullQueue() const = 0: virtual bool
+initializeQueue() = 0: virtual void
+front() const = 0: virtual Type
+back() const = 0: virtual Type
+addQueue(const Type&) = 0: virtual void
+deleteQueue() = 0: virtual void

119
36. a.

queueType<Type>

-maxQueueSize: int
-count: int
-queueFront: int
-queueRear: int
-*list: Type

+operator=(const queueType<Type>&):
const queueType<Type>&
+isEmptyQueue() const: bool
+isFullQueue() const: bool
+initializeQueue(): void
+front() const: Type
+back() const: Type
+addQueue(const Type&): void
+deleteQueue():void
+queueType(int = 100)
+queueType(const queueType<Type>&)
+~queueType()

b.

linkedQueueType<Type>

-*queueFront: nodeType<Type>
-*queueRear: nodeType<Type>

+operator=(const linkedQueueType<Type>&):
const linkedQueueType<Type>&
+isEmptyQueue() const: bool
+isFullQueue() const: bool
+initializeQueue():void
+front() const: Type
+back() const: Type
+addQueue(const Type&): void
+deleteQueue():void
+linkedQueueType()
+linkedQueueType(const linkedQueueType<Type>&)
+~linkedQueueType

120

You might also like