C++ Programming From Problem Analysis To Program Design 8th Edition Malik Solutions Manual 1
C++ Programming From Problem Analysis To Program Design 8th Edition Malik Solutions Manual 1
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.
2
1 1. Get the radius. cin >> 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.
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;
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
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
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 << "\"";
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;
int main()
{
int height, weight;
double discount;
double billingAmount;
double bonus;
int hoursWorked = 45;
double price;
height = 6;
weight = 156;
cout << height << " " << weight << endl;
cout << price << blanks << "$" << billingAmount << endl;
return 0;
}
11
int main()
{
int count, sum;
double x;
count = 1;
sum = count + PRIME;
x = 25.67; // x = 25.67;
newNum = count * 1 + 2; //newNum = count * ONE + 2;
sum++; //(x + sum)++;
sum = sum + count; //sum + count = sum;
x = x + sum * count; // x = x + sum * COUNT;
sum += 3; //sum += 3--;
cout << " count = " << count << ", sum = " << sum
<< ", PRIME = " << PRIME << endl;
return 0;
}
#include <iostream>
#include <string>
int main()
{
int num1, num2;
string str1;
return 0;
}
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
Name: Miller
Id: 34
Mystery number: -5.14286
33.
#include <iostream>
#include <string>
13
const double X = 13.45;
const int Y = 18;
const char STAR = '*';
int main()
{
string employeeID;
string department;
int num;
double salary;
salary = num * X;
return 0;
}
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
int main()
{
int num1, num2;
ifstream infile;
ofstream outfile;
infile.open("input.dat");
outfile.open("output.dat");
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
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;
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;
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;
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
#include <iostream>
int main()
{
int num1, num2;
bool found = false;
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>
int main()
{
int x, y, w, z;
z = 9;
if (z > 10)
{
x = 12;
y = 5;
w = x + y + SECRET;
}
else
{
x = 12;
y = 4;
w = x + y + SECRET;
}
return 0;
}
32.
#include <iostream>
#include <cmath>
using namespace std;
int main()
21
{
double firstNum, secondNum;
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;
}
The following algorithm determines the credit or penalty, and the unpaid balance.
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;
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;
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;
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>
int main()
{
int num1, num2;
double x = 0, y = 0;
int count;
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);
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;
}
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);
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);
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
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;
}
32
26. void sumAvgResult(int n, int m, int& sum, double& avg)
{
int count = 0;
sum = 0;
if (n >= m)
{
count = n - m + 1;
27. 7, 0, 0
1, 0, 8
8, 1, 8
2, 1, 1
28. 6 10 20
2 10 8
2 2 14
int main()
{
int num1, num2;
__1__ num1 = 6;
_17__ return 0;
}
33
{
int d;
__5__ d = a + b;
__6__ b = a * d;
__7__ return b;
}
_11__ val1 = x + y;
_12__ val2 = x * y;
_13__ y = val1 + val2;
_14__ cout << val1 << " " << val2 << endl;
}
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
main
num1 10
num2 20
main funOne
num1 10 a
num2 20 12 x
z
35
main funOne
num1 10 a
num2 20 12 x
22 z
main funOne
num1 10 a
num2 20 17 x
22 z
main funOne
num1 18 a
num2 20 17 x
22 z
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
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; \
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;
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;
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
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
or replace the statements in Lines 11, 13, and 14 with the following statements:
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.
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];
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
int intList[5];
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.
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"};
alpha [4] = 0.
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.
int cars[10];
int sum = 0;
int maxIndex;
int max;
cout << "The total number of cars sold = " << sum << endl;
max = cars[0];
cout << "The salesperson(s) selling the maximum number of cars: ";
26.
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
33. No, because during compile time the formal parameter list has no first and last elements.
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
c.
for (int k = 0; k < 20; k++)
alpha[0][k] = 1;
d.
for (int j = 0; j < 10; j++)
alpha[j][0] = 5;
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.
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;
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] << " ";
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;
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;
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
b. student = classList[0];
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:
c. Valid
d. Valid
e. Invalid; employees is an array. There are no aggregate assignment operations on arrays.
c. newEmployee = employees[19];
d. employees[49].salary += 5735.87;
struct sportsType
{
string sportName;
string teamName;
int numberOfPlayers;
double teamPayroll;
double coachSalary;
};
53
}
b. destination.cityName = "Chicago";
destination.distance = 550;
destination.travelTime.hr = 9;
destination.travelTime.min = 30;
d. tourType getData()
{
tourType dest;
54
return dest;
}
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
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;
56
void setSugar(int s);
int getSugar() 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;
}
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.
c.
62
style = s;
numOfBedrooms = bed;
numOfBathrooms = bath;
numOfCarsGarage = cg;
yearBuilt = yb;
finishedSquareFootage = fs;
price = pr;
tax = tx;
}
d. newHouse.print();
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;
}
15. The statement in Line 1 creates object1 and initializes the instance variables of this object
and object1.second = 0.0;. The statement in Line 2 creates object2 and initializes
statement in Line 3 creates object3 and initializes the instance variables of this object as
object3.second = 0.0;. The statement in Line 4 creates object4 and initializes the
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
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. ~
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);
double percentGainLoss();
private:
string name;
string symbol;
double currentPrice;
double lowPriceOfTheDay;
double highPriceOfTheDay;
double previousDayClosingPrice;
double fiftyTwoWeeksHigh;
double fiftyTwoWeeksLow;
};
d.
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;
}
68
void stockType::setPreviousDayClosingPrice(double preDayClP)
{
if (preDayClP >= 0.0)
previousDayClosingPrice = preDayClP;
else
previousDayClosingPrice = 0.0;
}
double stockType::getPreviousDayClosingPrice() const
{
return previousDayClosingPrice;
}
double stockType::percentGainLoss()
{
double diff;
69
return diff / previousDayClosingPrice * 100;
}
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;
}
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"
int main()
{
myClass obj(23, 45);
obj.print();
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;
myClass() {}
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::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"
int main()
{
die rolls[100];
int maxNumRolled = 0;
int rollCount[6] = {0};
int num;
int maxRollCount = 0;
int maxTimesNumRolled;
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
3. Some of the member variables that can be added to the class employeeType are:
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
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)
{
}
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;
}
75
{
if (x >= 0)
xCoordinate = x;
else
xCoordinate = 0.0;
if (y >= 0)
yCoordinate = y;
else
yCoordinate = 0.0;
}
double circle::getRadius()
{
return radius;
}
double circle::area()
{
return 3.1416 * radius * radius;
}
circle::circle()
{
xCoordinate = 0.0;
yCoordinate = 0.0;
radius = 0.0;
}
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;
}
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:
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();
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 }.
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
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;
}
78
{
return hourlyPayRate;
}
void hourlyEmployee::setPay()
{
employee::setPay(hoursWorked * hourlyPayRate);
}
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
13. First a constructor of class one will execute, then a constructor of class two will execute, and
14. a. None.
15. a. Invalid. z is an instance variable of the derived class, it cannot be accessed by the members of
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
#endif #endif
19. In a private inheritance, the public members of the base class are private members of the
derived class. They can be directly accessed in the derived class. The protected members of
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
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
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
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.
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.
or
b. All members of the class base becomes private members in class dummyClass.
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);
}
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
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 = #
(*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;
*height = 2 * (*baseRadius);
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 << "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:
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
21. The operator delete deallocates the memory space to which a pointer points.
22. 10 80 90 60 100
Sum = 340
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;
25. Because at compile time dynamic arrays have no first and last elements, so the functions begin
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;
87
c. for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 10; j++)
cout << votes[i][j] << " ";
cout << endl;
}
delete [] votes;
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;
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
b. The statement return this; returns the address of the object while the statement return
5. A friend function of a class is a nonmember function of the class, but has access to all the
7. d; Because the left operand of << is a stream object, which is not of the user-defined class type.
90
12. operator+(object1, object2)
13. a. bool b. bool
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:
17. In Line 4, the formal parameter of the function operator+ should be of type myClass. The correct
statement is:
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:
19. In Line 3, the return type of the function operator should be bool. The correct statement is:
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:
91
const findErrors& b) //Line 10
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
private:
double realPart; //variable to store the real part
double imaginaryPart; //variable to store the imaginary part
};
92
complexType complexType::operator~() const
{
complexType temp = *this;
temp.imaginaryPart = -temp.imaginaryPart;
return temp;
}
30.
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
private:
double realPart; //variable to store the real part
double imaginaryPart; //variable to store the
//imaginary part
};
93
temp.imaginaryPart = - temp.imaginaryPart;
return temp;
}
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);
}
private:
char* strConcat(char *str2);
char* strConcat(char * &str1, const char *str2);
94
(ii) Definitions of the functions to overload +
strConcat(temp.strPtr, rightStr.strPtr);
temp.strLength = strlen(temp.strPtr);
return temp;
}
chStr[0] = ch;
chStr[1] = '\0';
strConcat(temp.strPtr, chStr);
temp.strLength = strlen(temp.strPtr);
return temp;
}
return str;
}
95
delete [] str1;
return str1;
}
b.
(i) Function prototypes to appear in the definition of the class:
strLength = strlen(strPtr);
return *this;
}
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
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.
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
try
{
cout << "Enter the interest rate: ";
cin >> intRate;
cout << endl;
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
try //Line 3
{ //Line 4
cout << "Enter the raise: "; //Line 5
cin >> raise; //Line 6
cout << endl; //Line 7
Negative raise: -4
b. There are two catch blocks in the code. The first catch block between 18 and 22; the second
c. The parameter of the catch block at line 18 is num and it is of type int. The parameter of the
98
13. (In the following, the user input is shaded.)
a. Enter the number of items: 25
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.
#include <string>
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;
}
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>
class tornadoException
{
public:
tornadoException();
tornadoException(int m);
string what();
private:
string message;
};
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;
}
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"
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
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
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
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
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.
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;
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
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;
iteration = 1;
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
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
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)
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
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;
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] << " ";
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] << " ";
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
p = head;
while (p != nullptr)
{
cout << p->info << " ";
p = p->link;
}
cout << endl;
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.
23.
doublyLinkedList<Type>
#count: int
#*first: nodeType<Type>
#*last: nodeType<Type>
112
24.
dvdType
-dvdTitle: string
-movieStar1: string
-movieStar2: string
-movieProducer: string
-movieDirector: string
-movieProductionCo: string
-copiesInStock: int
25.
dvdListType
113
Chapter 18
1. a.true; b. false; c. false; d. true; e. false; f. true; g. false; h. false; i. true; j. true;
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.
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;
}
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))
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 (!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")
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
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
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.
while (!s.isEmptyStack())
{
elem = s.top();
s.pop();
q.addQueue(elem);
}
while (!q.isEmptyQueue())
{
elem = q.front();
q.deleteQueue();
s.push(elem);
}
}
Type elem;
while (!q.isEmptyQueue())
{
elem = q.front();
q.deleteQueue();
s.push(elem);
}
while (!s.isEmptyStack())
{
elem = s.top();
s.pop();
q.addQueue(elem);
}
}
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>
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