Sunteți pe pagina 1din 50

Friedman/Koffman 6th Edition

Answers to Odd-Numbered Exercises

Chapter 1

Section 1.1
1. microcomputers (hand-held or palm, netbook, laptop, desktop)
minicomputers
mainframes and supercomputers
3. The first electronic digital computer was designed in the late 1930s by Dr. John Atanasoff and
Clifford Berry. J. Presper Eckert and John Mauchley designed the ENIACthe earliest, large-scale
general-purpose electronic digital computer. The basis for the modern digital computer is credited to
Von Neumann, who proposed the stored-program computer.

Section 1.2
1. cell 1 contains 354
cell 998 contains X
3. Bit, byte, memory cell, main memory, secondary memory, LAN, WAN
5. The Internet.
7. While it is being typed, a letter may be stored in main memory or RAM. After it is finished, the letter
will be stored on a secondary storage device. Usually this will be the computers hard disk, but it may
be stored on a floppy disk or zip disk too. A software package that you purchase is installed on the
hard disk. Very large files that are no longer needed would also go on a secondary storage device, but
probably not the hard disk.
9. 354 + (-26) or 328

Section 1.3
1. a.
b.
c.
d.
e.

Store the difference of gross and net in profit.


Multiply 1.8 times celsius, add 32, and store the sum in fahren.
Store percent divided by 100.0 in fraction.
Store sum plus x in sum.
Add the product of oldPrincipal times interest to oldPrincipal. Store the sum in
newPrincipal. Another way to say this is: add interest to 1.0. Multiply oldPrincipal by
this sum. Store the result in newPrincipal.

Answers to Odd Numbered Exercises

f.

Subtract 32.0 from fahren, multiply the difference by 5 and then divide the product by 9. This
should convert a temperature in degrees Fahrenheit (value of fahren) to degrees Celsius.

Answers to Odd Numbered Exercises

3. Methods are operations that can be performed on an objects data.


5. An abstraction is a computer representation or model of an object or concept. For example, a fraction
consists of a numerator and a denominator, both of which are integers. Two fractions can be added,
multiplied, etc.

Section 1.4
1. Syntax errors are found in source files or source programs. The compiler would find any syntax
errors. Syntax errors can be corrected by going back to the word processor or to the editor window in
an Integrated Development Environment.
3. It is possible that certain programming environments may leave the source program in memory
instead of saving it to a disk. A source program could be lost if it is not explicitly saved to disk after
every modification, before attempting to run it.
5.

The source program contains the lines of the program the user entered with an editor. Once the user
finishes entering the program, an object program is created. The object program, created by the
compiler, is a syntax free machine language translation of the source program entered. The linker
combines additional object programs with the original object program to form the executable
program. The final step involves the loader loading the executable file into memory for execution.

Section 1.5
1. The five steps/stages of the software development method are:
Problem specification
Problem analysis
Program design
Program implementation
Program testing
3. If an error occurs and you havent saved your program file on disk, you could lose it if you need to
stop running the IDE in order to recover from the error.

Section 1.6
Algorithm
1. Get the distance in kilometers.
2. Convert the distance to miles.
3. The distance in miles is .621 times the distance in kilometers.
4. Display the distance in miles.

Section 1.7
1. You might do this in order to preemptively protect against viruses. Hopefully, people that you know
will not send you a virus intentionally, but sometimes a friends computer will be controlled by a
hacker and will send email messages with viruses to everyone in your friends email address book.
3. Email attachments that are not text files may incorporate executable program statements that are
viruses or worms. These malicious programs can execute when you open the attachment.

Answers to Odd Numbered Exercises

Chapter 2

Section 2.1
1. The characters kms; are part of the comment and they should not be. Anything after /* and before */
is ignored by the compiler.
float miles, // input: distance in miles
kms;
// output: distance in kilometers
3. The variable declarations tell the compiler how to allocate storage. Executable statements are
translated into machine language. Compiler directives, comments, and using namespace
statements are not translated into machine language.
5.

The symbol >> is the extraction operator. It is used to extract characters or their numeric values from
a data file (or the keyboard) and store them in a memory cell. The symbol << is the insertion
operator. It is used to copy characters or numeric values stored in a memory cell and place them into
an output file (or the console window).

7.

cout << Enter weight in pounds: ;


cin >> weight;

Section 2.2
1. C++ reserved words cant be used as identifiers.
3. C++ reserved words:

float, return

Valid Identifiers:

var, so_is_this, cout, xyz123, Bill, thisIsLong,


under_score, rate, include, start

Invalid Identifiers:

x=y*z, Prog#2, hyphen-ate, 123xyz, hello, a

5. The value of e should not be changed by a program operation so it should be defined as a constant.

Section 2.3
1. Predefined types are built into the language. Class types are defined in class libraries or by the
programmer. Predefined types have data stores that are variables; class types have data stores that are
objects. A string is a class type.
3. a.

0.0345
3456000
345678
b. 5.678E3 or 5.678e3
5.6789E2 or 5.6789e2
5.67E-3 or 5.67e-3

Answers to Odd Numbered Exercises

5. The area of a circle would be a float. The number of cars passing through an intersection in an
hour would be an int. A name would be stored in a string variable. The first letter of a last name
would be stored in a char.
7. The first declaration stores the character r in the variable color which is of data type char.
The second declaration stores the literal string r in the variable colorS which is of class type
string.
9. The first declaration declares name as a type string variable whose contents is not defined yet.
The second declaration stores the literal string Obama in the string variable pres. The third
declaration creates a type string constant FIRST_PRES that will always store the literal string
WaShington.

Answers to Odd Numbered Exercises

Section 2.4
1. Enter two numbers: 3.0 5.0 (data entered in italics)
a = -2
b = -10
Note: This assumes a and b are declared as type double or float.
3. My name is: Doe, Jane
I live in Ann Arbor, MI and my zip code is 48109
5. The library is iostream.

Section 2.5
1. /*
/*
/*
/*

This is a comment? */
This one */
seems like a comment */
doesnt it */

Section 2.6
1. 7 15 2 5
3. m = (m / n) * n + (m % n)
m = 45
n=5
45 = (45 / 5) * 5 + (45 % 5)
45 = 9 * 5 + 0
5. a.
b.
c.
d.
e.
f.
g.
h.
i.
j.
k.
l.
m.
n.
o.

i = a % b;

i is assigned 3

i
i
i
i
x
x
i
x
i
i
i
x
i
x

i is assigned 3
invalid: y must be type int
i is assigned 3
i is assigned 9
x is assigned 3.14159
x is assigned 3.14159
i is assigned 1
runtime error: cannot divide by 0
runtime error: cannot divide by 0
runtime error: cannot divide by 0
i is assigned 3
i is assigned 3.0
system dependent, 3 or 3
x is assigned 0

=
=
=
=
=
=
=
=
=
=
=
=
=
=

(MAX_I - 990 / a);


a % y;
(990 - MAX_I) / a;
PI * a;
PI * y;
PI / y;
(MAX_I - 990) % a
a % (a / b);
a % 0;
b / 0;
a % (MAX_I - 990)
a / y;
a % (990 - MAX_I);
a / b;

Answers to Odd Numbered Exercises

7. a.
b.
c.
d.
e.
f.

white = color * 2.5 / purple;

white is assigned 1.66667

green = color / purple; green is assigned 0.666667


orange = color / red;
orange is assigned 0
blue = (color + straw) / (crayon + 0.3); blue is assigned 3
lime = red / color + red % color; lime is assigned 2
purple = straw / red * color;
purple is assigned 0

Section 2.7
1. In interactive programs, the cout line just before the cin line is used to prompt the user to enter
input. In a batch program, there is no need for this prompt because the data items are obtained from a
batch data file. In a batch file, after the cin line, the cout line is used to echo the data. This lets the
user know what data values were read. Input data is provided to an interactive program through the
standard input stream (cin) or the console; input is provided to a batch program through a batch data file.

Chapter 3

Section 3.1
1. Problem Output
float numGallons
float milesPerGallon

//gallons of gas purchased


//amount of gas used up every mile

Problem Input
float miles
float gasCost
float costPerGallon

//miles the car can drive


//final gas bill
//cost of a gallon of gas

Formulas
number of miles
cost of gas

= number of gallons miles per gallon


= number of gallons cost per gallon

Initial Algorithm
1. Get the number of gallons.
2. Get the miles per gallon.
3. Get the cost of a gallon.
4. Compute the number of miles.
5. Compute the gas cost.
6. Display the number of miles and gas cost.
Algorithm Refinements
4.1 Assign numGallons * milesPerGallon to miles
5.1 Assign numGallons * costPerGallon to gasCost

Answers to Odd Numbered Exercises

3.

Problem Input
float tripDistance
float milesPerGallon
float costPerGallon
Problem Output
float tripCost

//miles traveled during the trip


//amount of gas used up every mile
//cost of a gallon of gas

//total cost of the trip

Formula
number of gallons = distance of trip / miles per gallon
cost of gas
= number of gallons x cost per gallon
Initial Algorithm
1. Get the distance of the trip.
2. Get miles per gallon.
3. Get average cost of a gallon.
4. Compute the total cost of the trip.
5. Display total cost of the trip.
Program variable
float numGallons

//number of gallons

Algorithm Refinements
4.1 Assign tripDistance / milesPerGallon to numGallons
4.2 Assign numGallons * costPerGallon to tripCost
5.

Program outline

// Computes
int main ()
{
float
float
float

the gross salary

hours
rate
gross

//hours worked by employee


//hourly pay rate
//employees gross salary

// Get the hours worked.


// Get hourly rate.
// Compute gross salary.
// Assign hours * rate to gross
// Display gross salary.
}

Answers to Odd Numbered Exercises

Section 3.2
1. a.

sqrt(u + v) * w * w

b. log(pow(x,y))
c. sqrt (pow(x-y, 3))
d. fabs((a/c)- (w*z))
3. It is system dependent. Some C++ versions will consider this a syntax error. Some will convert the
real argument to an integer (truncate the fractional part) and return the absolute value of the integer.

Section 3.3
1.

3. Program design.

10

Answers to Odd Numbered Exercises

Section 3.4
1. Prints the 5 by 5 letter O.
After a line space, prints the 5 by 5 letter H.
Three lines are skipped.
Prints the 5 by 5 letter H.
Prints the 5 by 5 letter I.
After a line space, prints the 5 by 5 letter M.
3. Neither. The functions execute in the order in which they are called by the main function or by
another function that is called by the main function.

Section 3.5
1. a. 778.0 b. 18.8495

c. 12.5664

d. 7.85397

3. Function arguments are used to pass information between the separate modules of a program and
between the main function and its modules. Arguments make it easier for a function to be reused by
other functions or programs. Functions with arguments are building blocks for constructing larger
programs.
5. The syntax error Too few arguments for function functionName (or Too many arguments )

Section 3.6
1.
Name

Visible in scale

Visible in main

Scale

yes

yes

Main

yes

yes

num1

no

yes

num2

no

yes

x (float parameter)

yes

no

n (int parameter)

yes

no

scaleFactor

yes

no

Section 3.7
1. line 1:
line 2:
line 3:
line 4:
line 5:

line 6:

The variable name is declared as type string.


The prompt name: is displayed. We type Jones***John Boy
The literal that was typed, excluding the newline character, is stored in name.
name is searched until the group *** is found. The position of the first item in this group
is stored in the variable start, which is 5.
3 characters of the string are erased, the first is the character at the position indicated by
start, and the second and third are the characters that come after that. This method call
results in the literal *** being erased and everything after *** is shifted to the left to fill
in the empty space.
A , is inserted into the string at position 5. The characters starting with the second
letter J, which was previously at postion 5, are shifted to the right by one position.

Answers to Odd Numbered Exercises

line 7:

11

The modified contents in name is displayed: Jones, John Boy.

3. wholeName = lastName + , + firstName;

Section 3.8
1. The y-dimension is smaller than the x-dimension; i.e., the height of the window (and most screens) is
smaller than its width.
3. In Figure 3.16, the windows should be 2 solid rectangles in the top half of the house (below the roof).
Insert the following statements after the one that draws the door.
bar((x1+x6)/2, (y1+y6)/2 +25, (x1+x6)/2 + 50, (y1+y6)/2 - 25);
bar((x3+x5)/2-25, (y1+y6)/2 +25, (x3+x5)/2 + 25, (y1+y6)/2 - 25);

Chapter 4

Section 4.2
1. x = 15.0, y = 10.0
x != y
x < y
x >= (y x)

true
false
true

x == (y+x-y) true
a. Either x must be < 5.1 or x must be >= 5.1 so one of those conditions must be true and the
result will be true regardless of the values of x and y.
b. If q is false, then both p && q and q && r must be false, so the result is false.
3. a.

Either x must be < 5.1 or x must be >= 5.1 so one of those conditions must be true and the result
will be true regardless of the values of x and y.
b. If q is false, then both p && q and q && r must be false, so the result is false.

Section 4.3
1. a.

for x = 10 the output is:


less
done
for x = 20 the output is:
done
b. O.K.

12

Answers to Odd Numbered Exercises

3. a.

the is located at position 8 (value of posTarget) and is replaced by that.


testString becomes Here is that string.

b. Here is located at position 0 (value of posTarget) and replaced by There.


testString becomes There is the string.
c. Where is not located so the condition involving posTarget is false and the error message is
displayed.

Section 4.4
1. if (x > y)
{
x = x + 10.0;
cout << x bigger than y << endl;
}
else
{
y = y + 10.0;
cout << x smaller than y << endl;
}
cout << x is << x
<< y is << y << endl;

Answers to Odd Numbered Exercises

3.

13

Placing braces around the last two lines in the answer to Question 1 would cause the value of y to be
displayed only when x <= y is true.

Section 4.5
1. Program is more readable and easier to modify.
3. We would have to change only the definition for the constant DUES (new value 25) defined in the
main function.

Section 4.6
1. hours is 41, rate is 5.0. Replace Step 3.1.4 in Table 4.9 with steps 3.1.1, 3.1.2, 3.1.3. gross will
be 205.0 and net will be 190.0.

Section 4.7
1.
Statement Part

salary

tax

Effect

135000.00 ?
if (salary < 0.0)
else if (salary < 15000.00)

135000.00 < 0.0 is false.

else if (salary < 30000.00)

135000.00 < 15000.00 is false

else if (salary < 50000.00)

135000.00 < 30000.00 is false.

else if (salary < 80000.00)

135000.00 < 50000.00 is false.

else if (salary < 150000.00)

135000.00 < 80000.00 is false.

else if (salary < 150000.00)

135000.00 < 150000.00 is true.

tax = (salary - 80000.00)

tax evaluates to 55000.00.

* .25
+ 14250.00

3. a.

tax evaluates to 13750.00.


28000.00 tax evaluates to 28000.00.

There would be a division by zero error without short-circuit evaluation (y / x). With short
circuit-evaluation, the value would be false. Because (x > 10) && . . . is false,
evaluation would stop.
b. There would be a division by zero error without short-circuit evaluation (x / (y 7)).
With short circuit-evaluation, the value would be true. Because (x <= 10) || . . . is
true, evaluation would stop.
5. if ch1 is + or ch1 is * or ch1 is - or ch1 is /
Set isOp to true
else if (ch1 is | and ch2 is |) or (ch1 is & and ch2 is &)
Set isOp to true
else
Set isOp to false

14

Answers to Odd Numbered Exercises

Section 4.8
1. red
blue
yellow
switch (color)
{
case R: case r:
cout << red << endl;
break;
case B: case b:
cout << blue << endl;
break;
case Y: case y:
cout << yellow << endl;
default:
cout << color not determined
break;
<< endl;
}
3. In Section 4.7, the selection is determined based on a sizable range of values rather than a specific
value. With the switch statement, selection is based on a single value or a small, easily listable set
of values.
5. Logic error, a wattage of 25 would also be assigned a value of 1000.

Chapter 5

Section 5.1
1. a.

The loop will repeat forever (infinite loop), since countEmp remains 0.

b. Since countEmp is undefined, the results cannot be predicted.


3. 024681012*** 30
5. Repetition #1 outputs 9.
Repetition #2 outputs 81.

Answers to Odd Numbered Exercises

Section 5.2
1.
Count

Data Value

Data Value

Data Value

Output
1

Output
1

Output
1

1
2

5
25

6
36

7
49

3
4

125

216

1296

Exit loop

Exit loop

Exit loop

This loop displays x0 through x3 for every x entered by the user.


3. The segment should read:
count = 0;
sum = 0;
while (count < 5)
{
cout << Enter data item: ;
cin >> item;
sum += item;
count++;
}
cout << count << data items were added << endl;
cout << their sum is << sum << endl;

Section 5.3
1.

16

25

Sum of positive odd numbers less than 10 is 25

15

16

Answers to Odd Numbered Exercises

3. a.

Nothing would be displayed because 5 is less than 10. The loop body will not execute.

b. Celsius
-5
0
5
10
c.

Celsius
-5

5
d. Nothing would be displayed because 5 is less than 10. The loop body will not execute.
5. ++i;
--j;
n = i * j;
m = i + j;
j--;
p = i + j;
7. I

Output

10

10

4
3
2

8
6
4

4
3
2

8
6
4

Section 5.4
1. supply = 990.0
3. Enter initial oil supply: 5000
Enter amount used today: 4000.5
After removal of 4000.5 gallons,
number of gallons left is 999.5.
999.5 gallons left in tank.
Warning - amount of oil left is below minimum!

Answers to Odd Numbered Exercises

5.

n >0 && pow(2,n) < 1000

Output

true

32

true

16

10

false

The while loop exit occurs and 5 is not read in

Section 5.5
1. The first score would not be included in the sum but the sentinel would be.
3. a.

The loop would repeat forever, since digitRead remains false.

b. nextChar = 2 Both relational expressions are true.


nextChar = a The first relational expression is true but the second is false.
c.

if ((0 <= nextChar) && (nextChar <= 9))


digitRead = true;
+else
digitRead = false;

Section 5.6
1. Output
10
8
6
4
2
3. const int SENTINEL = Q;
int count = 0;
do
{
. . .
count++;
} while(toupper(choice) != SENTINEL || count < 10);
5. m = 10;
cout << m << endl;
for (int i = m 2; i > 0; i = i 2)
{
cout << i << endl;
}

17

18

Answers to Odd Numbered Exercises

Section 5.7
1. Output
a. 5
10
15
20
25
30
35
40
45
50
b.
for (num = 5; num <= 50; num += 5)
{
cout << num << endl;
}
c. num = 5;
do
{
cout << num << endl;
num += 5;
} while (num <= 50);
3. The do-while loop should be used only in situations where it is certain that the loop should execute
at least once. It can be used in data entry loops when you know at least one data item will always be
entered.

Section 5.8
1. 100 times. 10 times.
The addition table could be printed by modifying the statement within the inner loop to
cout << setw(3) << (rowVal + colVal);

Answers to Odd Numbered Exercises

3. Outer
Inner
Inner
Inner
Inner
Outer
Inner
Inner
Inner
Inner
Inner

0
0
0
0
0
1
1
1
1
1
1

19

0
1
2
0
0
1
2
1
0

Section 5.9
1. sum = 0;
cout << Enter << n << integers and press return:
<< endl;
for (int count = 0; count <= n; count++)
{
cout << count << count << endl;
cin >> item;

// debug

sum += item;
cout << sum << sum << endl; // debug
} // end for
The addition of these debug statements should show that the loop has an off by 1 error. The prompt
is requesting n data items. The loop is expecting n+1 data items. This can be corrected by changing
the relational operator from <= to <.

Section 5.10
1. A circle with blue color hatch fill. Each time the user presses a key, the circle moves right by the
amount of its radius and the color changes. After the tenth circle is displayed, the program stops.

20

Answers to Odd Numbered Exercises

Chapter 6

Section 6.1
1. test(m, -63, y, x, next);
Actual Argument

Formal Parameter

Description

int, value

-63

int, value

float, reference

float, reference

next

char, reference

Answers to Odd Numbered Exercises

test(35, m*10, y, x, next);


Actual Argument

Formal Parameter

Description

35

int, value

m * 10

int, value

float, reference

float, reference

next

char, reference

test(m, m, x, m, a);
Not correct because the fourth parameter should be type int. It should also be a variable, not a
character literal.
3. Invalid function calls:
e. must use variable for call by reference
g. a, b not declared in main
i. must use variable for call by reference
k. too many arguments
Calls requiring standard conversion:
a. value of z is converted to int
d. float value returned to m is converted to int. If m is used as INOUT, initial value of m is
converted to float.
j. value of x is converted to int
5. Algorithm for function addFrac with input parameters: num1, denom1, num2, denom2 and output
parameters numSum, denomSum. To add 2 fractions, you must first give them both the same
denominator. You do this by multiplying the first fraction by denom2 / denom2 and the second
fraction by denom1 / denom1. This gives both fractions the denominator denom1 x denom2.
1. Set numSum to (num1 x denom2 + num2 x denom1)
2. Set denomSum to denom1 x denom2
3. Return

Section 6.2
1. a.

5
5
-2

3
3
8

8
-2
-2

2
8
8

-10

-2

21

22

Answers to Odd Numbered Exercises

b. sumDiff computes the sum and difference of its first two arguments and places the answers in
its third and fourth parameters. The input parameters cannot be modified, but sumDiff changes
the value of the output parameters, which are passed by reference.
c. // Pre: num1 and num2 are defined.
// Post: num3 and num4 contain the sum and difference
//
of num1 and num2.

Answers to Odd Numbered Exercises

23

Section 6.3
1.
// Pre:
// Post:
//
// Returns:

numItems and sum are defined; numItems must be > 0.0


If numItems is positive, the average (variable ave)
is
computed as sum / numItems; otherwise ave is set to
0.0
The average (variable ave) if numItems is positive;

//
otherwise variable ave is set to 0.0
void computeAve (int numItems,
// IN: number of data items
float sum,
// IN: sum of data
float & ave)

// OUT: average of data

{
if (numItems < 1)
{
cout << Invalid value for numItems = << numItems << endl;
cout << Average not computed. << endl;
ave = 0.0;
} //endif
else
ave = sum / float (numItems);
} // end computeAve
The solution is not as good because a function that computes a single value should return that
value as its result (by executing a return statement).
3.

5. 1.
2.
3.
4.

Read the number of items


while the number of items is <= 0
Display an error message
Read the number of items.

24

Answers to Odd Numbered Exercises

Section 6.4
1.
Statement

posComma Effect

MoneyToNumberString

moneyToNumberString is passed

(string& -$5,405,123.65)

-$5,405,123.65 by reference

if (moneyString.at(0) == $)

value is false
value is true

else if (moneyString.find(-$) == 0)
moneyString.erase(1, 1);
posComma = moneyString.find(,);

removes the -$
2

while (posComma >= 0 &&

loop while posComma >= 0 and

posComma < moneyString.length())

< the length of moneyString

moneyString.erase(2, 1);
posComma = moneyString.find(,);

removes the first comma


5

moneyString.erase(5,1);
posComma = moneyString.find(,);

posComma is assigned 2

posComma is assigned 5
removes the second comma

>=11

there are no more commas in


moneyString

Section 6.5
1. Enter the number of items to be processed: 10
Function computeSum entered
The number of items is 10
The sum of the data is 100.00
The average of the data is 10.00
3. Black-box testing assumes the tester has no knowledge of the system code. The tester must enter
representative data sets and check the correctness of the output for each input sample. White-box
testing assumes the tester knows how the system is coded. The tester must provide a data set for each
possible execution path. Top-down testing involves testing the flow of control between a main
function and its subordinate functions, possibly using stubs for the functions that are not yet
completed. Bottom-up testing involves testing each individual function separately as it is completed.
Unit testing is the process of thoroughly testing each individual function to be part of a system.
System integration testing is the process of putting the system together and testing the entire system
after all unit testing has been performed.
5. A function prototype tells the compiler the function result type and its parameter data types. It does not
have a body. A stub substitutes for the actual function definition. Therefore, it has a body that
displays the name of the function and returns a simple value if one is needed.

Answers to Odd Numbered Exercises

Section 6.6
1. n = 5;
Call factorial(4) and return 5 times the result
n = 4;
call factorial(3) and return 4 times the result
n = 3;
call factorial(2) and return 3 times the result
n = 2;
call factorial(1) and return 2 times the result
n = 1;
return 1;
return 2 x 1 or 2;
return 3 x 2 or 6;
return 24;
return 5 x 24 or 120;
3. int gcd(int m, int n)
{
if(n > m)
return gcd(n, m);
else if(m % n == 0)
return n;
else
return gcd(n, m % n);
}

Chapter 7

Section 7.1
1. const int MAXINT = 32767; valid
const int MININT = -MAXINT; valid, MININT is -32767
const char FIRST_FEMALE = Eve; invalid char constant
const int MAX_SIZE = 50.5; invalid int constant
const int MIN_SIZE = maxsize - 10; invalid expression
const int ID = 4FD6; invalid int constant
const int KOFFMAN_AGE = 67; valid
const int FRIEDMAN_AGE = z66; invalid int constant
const float PRICE = $3,335.50; invalid float constant
const float PRICE = 3335.50; valid
const float PRICE = 3335.50; invalid float constant

25

26

Answers to Odd Numbered Exercises

3. The difference between the #define and the const declaration is that the identifier used in the
#define has no storage associated with it. The #define is a compiler directive that tells the
compiler to replace one string of characters with another everywhere the first string of characters
appears in the source file. Using a const declaration involves placing the constant value in a storage
location. The contents of this storage location cannot be changed during program execution.
Generally a constant declaration is preferred in C++.

Section 7.2
1. 215 1 (32767)
3. For x = 6.875 the result is 6.88.
For x = -6.875 the result is 6.87.
if (x >= 0)
x = float(int(x * 100 + 0.5)) / 100.0;
else
x = float(int(x * 100 0.5)) / 100.0;
5. a. 3.0 b. 12.9 c. 12.9 d. 13

Answers to Odd Numbered Exercises

Section 7.3
1. Note it is not really necessary to know the ASCII code. Each of these answers can be determined
without using the actual code values.
a. int(d) int(a)
100 97 = 3
b. char((int(M) int(A)) + int(a))
char((77-65) + 97)
char(109) = m
c. int(7) int(0)
55 48 = 7
d. char(int(5) + 1)
char(53 + 1)
char(54) = 6
3.

Type

Value

Explanation

a.

isdigit(a);

int

false

a is not the character


representation of a digit.

b.

isdigit(7);

int

true

7 is the character
representation of a digit.

c.

isdigit(9);

int

false

9 is not the character


representation of a digit

d.

toupper(#);

char

# is not a letter.

e.

tolower(A);

char

A is uppercase; returns
corresponding lowercase.

f.

tolower(p);

char

p is lowercase.

g.

digitToNumber(0)

int

Returns the number


corresponding to 0

Section 7.4
Condition

Complement

x <= y && x == 25

x > y || x != 25

b.

(x > y && x != 15) || z <= 7

(x <= y || x == 15) && z > 7

c.

x != 15 || z == 7 && x <= y

x == 15 && (z != 7 || x > y)

d.

flag || !(x != 15)

!flag && x != 15

e.

!flag && x > 8

flag || x <= 8

1. a.

3. The loop keeps asking for a number until a number between 1 and 10 inclusive is entered.
When the loop is exits, the value entered that made inRange() return true, is retained in n.
The condition at the end of the loop can be written as (!inRange(n, 1, 10))
5. xBigger = (x > y);
This assign the value of the bool expression x > y to xBigger. It is more efficient.

27

28

Answers to Odd Numbered Exercises

Section 7.5
1. The enumerator red has value 0, green has value 1, yellow has value 2, and blue has value 3.
The type day enumerators have values 0, 1, 2, . . . , 6. The type specialChars
enumerators have values \b, \a, \n, \r, \t, \v (8, 7, 10, 13, 9, 11).
3. a.
b.

c.

d.

enum logical {true, false};

invalid: true and false are values of type


bool.

enum letters {A, B, C};

valid

enum twoletters {A, B};

invalid: an identifier may not be used more


than once in any enumeration within the same
scope of definition.

enum
wed,
enum
thu,
enum

valid

day {sun, mon, tue,


thu, fri, sat};
weekDay {mon, tue, wed,
fri};
weekEnd {sat, sun};

invalid: see reason in Part b above


invalid: see reason in Part b above

enum trafficLight {red,


yellow, green};

valid

int green;

invalid: see reason in Part b above

Section 7.6
1. Any pair of numbers that has-0.729 in its interval. The difference between the 2 numbers should be
1. For example, -1.2 and -0.2 or -0.9 and 0.1.

Section 7.7
1. The random number seed should only be set once. If the call to srand is inside drawShape, it would
be reset each time the function was called.
3. The text color is the same as the color of the shape just displayed.

Chapter 8

Section 8.1
1. cin >> next; skips over white space. Any blank characters in the input would not be counted.
The while loop wouldnt terminate on newlines.
3. cin >> n >> n >> x >> c >> c >> c >> c >> n >> c;
5. If the innermost cin.get were omitted, the program would execute forever as no new data
characters would be read.
7. n gets 3, ch1 gets a, ch2 gets b. When the data for m is extracted, the first character encountered is c
which is not numeric, therefore, the value of m is not defined.

Answers to Odd Numbered Exercises

Section 8.2
1. The e is read in the loop in function copyLine. It is written to the output file. The s is read next
and written to the output file. The . is read next and written to the output file. The <nwln> is read
next, causing loop exit. <nwln> is written to the output file. Control passes back to main.
lineCount is incremented. Since end-of-file is true, the loop in main is exited. Statistics are
displayed on the screen, files are closed, and execution is terminated.
3. Some advantages of using external (permanent) files for program input and output are as follows:
a. The input data can be reused without being reentered. This is especially helpful while you are
debugging your program.
b. The input information can be printed and examined as often as needed.
c. The output information can be used as input data for another program.

Section 8.3
1. a. Leading blanks are ignored when each employees first name is read so they cause no problem.
b. Blank lines in the middle of the data stream would cause no problem because they would be
skipped when reading the next employees first name. A blank line at the end would cause the
while loop to execute an extra time.
3. getline(eds, name, \n);
eds >> hours >> rate;
or if you wanted to read data into firstName and lastName:
getline(eds, firstName, );
getLine(eds, lastName, \n);
eds >> hours >> rate;
5.

Open input file one


Open the output file
Set payroll to 0
while not at the end of input file 1
Read the employee name and hourly rate from file 1
Set found to false
Open input file 2
while not found and not at the end of input file 2
Read the employee name and hours worked from file 2
if the names are the same
Calculate the employees salary and add it to payroll
Set found to true
Write the employees name and salary to the output file
end of inner loop
if not found
Display a message that employees hours worked are missing
Close input file 2
end of outer loop
Display the total payroll
Close all files

29

30

Answers to Odd Numbered Exercises

Section 8.4
1. To write the name and salary on separate lines use the following statement:
pds << name << endl << salary << endl;
3. This statement extracts and ignores (skips) all characters in the input stream through the next *
character. If there are more than 80 characters before the next * character, it will only skip the first
80 characters.

Section 8.5
1. #####15.99#####13.45 (# represents a space character)
3. Jane#############Doe (# represents a space character)

Chapter 9

Section 9.1
1. x3 is a simple variable. A single value is associated with this single memory location. x[3] is a part
of a collection of variables, called an array, all having the same data type. An array is a structured
variable. x[3] refers to the fourth element in this array.
3. a.

string names[100];

b. float checks[20];
c. bool madeBonus[7];
d. int daysInMonth[12];

Section 9.2
1. a.

Each time the body of the loop is executed, the value of i is displayed followed by a space and
the value in array x at index i, squared, followed by a comma. This is done 10 times (from 9
down to 0). So the first pair is 9 and x[9] * x[9]; the last pair is 0 and x[0] * x[0]
b. The loop displays elements with even subscripts (0,2,...,8). There is a single space between
values.

3. i = 0
ch is 4, pos is -1, message[0] remains 4
i=1
ch is , pos is -1, message[1] remains
i=2
ch is h, pos is 7, message[2] becomes i
i=3
ch is e, pos is 4, message[3] becomes f
i=4
ch is a, pos is 0, message[4] becomes b

The output displayed is: The cryptogram is

: 4 ifbsut

Answers to Odd Numbered Exercises

Section 9.3
1. size1.
3. // Pre: a1, a2 are defined.
// Post: contents of a1 are exchanged with the contents of a2.
int exchange
(int& a1,
int& a2)

// item to exchange with a2


// item to exchange with a1

{
int temp;

// stores (saves) contents of a1 prior to moving


// contents of a2 into a1

temp = a1;
a1 = a2;
a2 = temp;
} // end exchange
// Pre: a[i] and b[i] (0 <= i <= size-1) are assigned values.
// Post: Returns true if a[i] == b[i] for all i in range 0 through
// size-1; otherwise returns false.
int sameArray
(const int a[],
// IN: char array to be compared to array b
const int b[],
const int size)

// IN: char array to be compared to array a


// IN: size of the arrays

31

32

Answers to Odd Numbered Exercises

{
for (int i = 0;
i < size 1 && a[i] == b[i];
i++);
return a[i] == b[i];
} // end sameArray
5.

If the function intent is to access all the elements in its array argument, then it needs to know the
size of the array. The size must be passed as a separate argument.

Section 9.4
1. In readScores, the int array scores must be changed to float. Local data SENTINEL and
tempScore must be changed from int to float.
3. The number of scores to read could be different from MAX_SIZE (the declared size), so the function
should read this number into sectionSize from the data file and compare it to MAX_SIZE. If it is
larger than MAX_SIZE, reset sectionSize to MAX_SIZE and display a warning that only
MAX_SIZE scores can be read the rest will be ignored. This is all to be done before the while-loop.
If sectionSize is smaller or less than MAX_SIZE then execute the while-loop. The value for
sectionSize should be the first value in the data file and should be the only value on the first
line.

Section 9.5
1. a. The array subscript of the last item is returned to the calling function.
b. The array subscript of the first item matching target is returned to the calling function.
3. We could use a function findIndexOfMax to arrange the data items in the array in descending
order. We should also change the variable minSub to maxSub to improve readability.
5. Before the call to the function exchange, we could check to see if minSub == i. Call
exchange only if these two values are not equal.
if (i != minSub)
exchange(items[minSub], items[i]);
This if-statement always increases the number of comparisons by 1 for each pass but can decrease
the number of exchanges.

Section 9.6
1. a.
b.
c.
d.

Executes n times for each i, or n2 times; O(n2).


Executes 2 times for each i, or 2n times; O(n).
Executes n times for each i, or n2 times; O(n2).
Executes i times for each i, or ((n 1) * (n 2)) / 2 times; O(n2).

Answers to Odd Numbered Exercises

33

Section 9.7
1.a. 45
b. cout << matrix[2][3];
c. matrix[8][4]
d. matrix[4][2] or
matrix[MAX_ROW/2][MAX_COL/2]
3. The compiler can compute the offset of any element from the first knowing just the size of the second
and third dimensions. The array element order is sales[0][0][0] . . .
sales[0][0][11], sales[0][1][0] . . . sales[0][1][11] . . .
sales[0][4][0] . . .sales[0][4][11]. Then the same sequence for the first subscript 1, the
first subscript 2 . . . the first subscript 9. The last element is sales[9][4][11]. The offset for
sales[i][j][k] is computed by the formula
offset = 5 12 + j 12 + k

Section 9.8
1. The value of the rate component of organist is multiplied by 2.
It is not valid to display the struct variable organist.
The rate component of organist is multiplied by 40.0 and assigned to the totWages component.
The message Female is displayed if the gender component of organist is F

Section 9.9
1. a.
b.
c.
d.
e.
g.
g.
h.

Accesses the stuName component of aStudent.


Accesses the first character of the stuName component of aStudent.
invalid, examStats is a type, not a variable.
invalid, scores[2] is the last one.
The last score of aStudent.
invalid, examStats is a type, not a variable.
Copies each member of bStudent into aStudent.
Assigns the ASCII code for bStudent.grade ( type char) to aStudent.score (type int).

3. void printEmployee (const employee& oneEmployee)


{
cout << Name: << oneEmployee.name << endl;
cout << ID: << oneEmployee.id << endl;
cout << Gender: << oneEmployee.gender << endl;
cout << # of Dependents << oneEmployee.numDepend << endl;
cout << Hourly rate: << oneEmployee.rate << endl;
}

34

Answers to Odd Numbered Exercises

To call this function to display an Employee struct, simply state:


printEmployee(oneEmployee);

Section 9.10
1. a.
b.
c.
d.
e.
f.
g.
h.

gender attribute of second employee


invalid
the last employee (a struct)
invalid
invalid
invalid
the last employees name
invalid

3. a.

company[0].name

b. company[1].id
c. company[1].name
d. company[0].id

Section 9.11
1.a. char dayName[] = Sunday;
cout << length is << strlen(dayName);
b. char monthName[10];
strcpy(monthName, February);
c. string fName = data.txt;
aStream.open(fName.c_str());
d. string year = 2004;
int yearN = atoi(year.c_str()); yearN++;
e. char initial[4];
initial[0] = E; initial[1] = B;
initial[2] = K; initial[3] = \n;

Section 9.12

Answers to Odd Numbered Exercises

35

36

Answers to Odd Numbered Exercises

Chapter 10

Section 10.1
1. These are all member functions of class counter. To call them, we must associate them with a
particular object of this class using dot notation.
3. a.
b.
c.
d.
e.

counter c1(20);
c1.setCount(15);
c1.decrement();
c1.decrement();
decrement();

Section 10.2
1. The scope resolution operator :: is used as a prefix to the function name in each member function
header. This operator tells the compiler that the scope of the function name and of the identifiers
appearing in the function is the class that precedes the operator ::.
3. The constructors are used to initialize the data members of a new object of the class type. The
argument of the second constructor can be used to set the initial state of the new object. The compiler
can determine which overloaded constructor function to use based on the presence or absence of an
actual argument.

Section 10.3
1. counts[2].setCount(5);
cout << counts[4].getCount();
3. An array of 10 counters is declaraed and counts[0] is set to 1.
In the loop, each elements of counts (starting with counts[1]) is first set to the same value as the
previous element (the one with the next lower subscript) and then its value is incremented. The effect
is that counts[1] is 2, counts[2] is 3, counts[9] is 10.

Section 10.4
1. 1, 1

Section 10.5
1.

Answers to Odd Numbered Exercises

3. Replace the body of function subtract with return


f1.add(f2.negate());. This statement uses method negate to negate fraction f2 and then
adds this result to fraction f1 using function add.

37

38

Answers to Odd Numbered Exercises

Section 10.6
1.

3. To form a rectangle class, substitute the attributes width and length (type float) for the
attribute radius. Replace member function setRadius with setDimensions. The function
setDimensions would have two arguments, representing the width and length of a rectangle.
Replace member function getRadius with two accessor functions: getWidth and getLength.
Replace displayCircle with displayRectangle. The bodies of the new member functions
would process the new attributes. Functions computeArea and computePerimeter would do
the calculations for a rectangle instead of a circle. The five member functions that set and retrieve the
objects coordinates and color would be unchanged.
5.

It is a local constant in function simpleString::at.

Section 10.7
1. It does store the leading blanks. One way to change it would be to use the extraction operator >> to
get the first character only instead of function get.
3. Since the driver function is a client program, the details of the class simpleString are to be
hidden from the driver function, while the member function writeString has access to the class
data members. So the for loop in the driver function uses the public member function getLength,
while the for loop in the member function writeString uses length.

Section 10.8
1. Each account has a unique id number and the id number must be specified as part of the deposit
transaction. Unless the user enters the wrong id number, it would not be possible to place a deposit
intended for one account in the other account.

Chapter 11

Section 11.1
1. dummy<float> a, b, c;
float num1, num2, n1, n2, sum;
cout << Enter two numbers: ;

Answers to Odd Numbered Exercises

cin >> num1 >> num2;


a. setItem(num1);
b. setItem(num2);
c. setItem(a.getItem() + b.getItem());
sum = c.getItem();
cout << sum << endl;
3.

dum1 and dum2 are declared as dummy objects with a type float data field item. The value of
dum1.item is set to 0 and dum2.item is set to 0.5. The line 0, 0.5 is displayed.

Section 11.2
1. array attribute smallList.elements has room for 5 float values.
smallList.size is 0.
contents of elements is 3.5, smallList.size is 1
contents of elements is 3.5, 5.7, smallList.size is 2
contents of elements is 5.7, smallList.size is 1
display 5.7, elements and size are not changed.
contents of elements is 15.5, smallList.size is 1
contents of elements is 15.5, 5.5, smallList.size is 2
display 1, index of 5.5.
contents of elements is 5.5, 15.5, smallList.size is 2
display array elements: 5.5, 15.5, smallList.size is 2.

39

40

Answers to Odd Numbered Exercises

Section 11.3
1. It returns the count of array elements that are larger than the array element they follow. For example,
if elements contains 3.5, 5.6, 4.6, 7.7, the value returned would be 2 because 5.6 and 7.7 are larger
than the array element they follow.
3. Change the function body to:
{
for (int i = 0; i < size; i++)
if (elements[i] == target)
return i;
return -1;
}

Section 11.4
1.

3.

The advantage of the current approach is that the contactList class is not restricted to using an
indexList for data storage in a contactList object. The private data member contacts
could be changed to some other data type. It also enables the client to call member functions for a
general contactList object rather than using member functions specific to the indexList
class.
If selectOp were in the contactList class, a contactList object would not be passed as a parameter.
Instead function selectOp would be applied to a contactList object in the client program. In function
selectOp, the prefix addressBook. should be removed before each member function of contactList
called in selectOp. The reason for the approach taken is that the actual interaction that takes place
interactively with the program user should be determined within the client program, not within the
contactList class.

Section 11.5
1. In the definition of friend operator >>, all three occurrences of operators << and >> in the body
have a stream as the left operand and a string object as the right operand. C++ has defined >> and <<
for stream and string objects.
cout << Enter name: ;
// << defined in iostream class
getline(ins, dE.name, \n); // getline defined in string, iostream
class
cout << Enter number: ;
// << defined in iostream class
ins >> dE.number;
// >> defined in string, iostream class
3. fraction operator * (const fraction&, const fraction&);

Section 11.6
1. Statment

Effect

vector<char> s(10);

Creates a character vector of size 10.

s[0] = a;

Assigns a at the beginning of vector; s.size() is 1

s[9] = z;

Inserts z at the end of vector; s.size() is 10

Everything in between s[0] and s[9] is NULL.

Answers to Odd Numbered Exercises

s.push_back($);

Assigns $ at position 10 of the vector. s.size() is 11.

for(int i = 0; i < s.size();

Will display the line below with 8 spaces in middle.

i++) cout << s.at(i);

a z$

char ch1 = s.front();

ch1 = a

char ch2 = s.back();

ch2 = $

cout << ch1 << ***


<< ch2 << endl;

a***$

41

42

Answers to Odd Numbered Exercises

Chapter 12

Section 12.1
1.

Raise 5 to the power of 4


Subproblems generated by 1.
1.1 Raise 5 to the power of 3.
1.2 Multiply the result of 1.1 by 5.
Subproblems generated by 1.1
1.1.1 Raise 5 to the power of 2.
1.1.2 Multiply the result of 1.1.1 by 5.
Subproblems generated by 1.1.1
1.1.1.1 Raise 5 to the power of 1.
1.1.1.2 Multiply the result of 1.1.1.1 by 5.
Raise 4 to the power of 5
Subproblems generated by 1.
1.1 Raise 4 to the power of 4.
1.2 Multiply the result of 1.1 by 4.
Subproblems generated by 1.1
1.1.1 Raise 4 to the power of 3.
1.1.2 Multiply the result of 1.1.1 by 4.
Subproblems generated by 1.1.1
1.1.1.1 Raise 4 to the power of 2.
1.1.1.2 Multiply the result of 1.1.1.1 by 4.
Subproblems generated by 1.1.1.1
1.1.1.1.1 Raise 4 to the power of 1.
1.1.1.1.2 Multiply the result of 1.1.1.1.1 by 4.

Section 12.2
1. Each call to the recursive function displays an entry display before calling the function power
recursively (until n <= 1). The first exit display is displayed after the stopping case is reached,
power(8, 1). The return to the second activation frame is followed by displaying the exit display
for power(8, 2). The return to the first activation frame is followed by displaying the exit display
for power(8, 3).

Answers to Odd Numbered Exercises

3. power(4, 5)
m is 4
n is 5
5 <= 1 is false answer = 4 * power(4, 4)
return answer
power(4, 4)
m is 4
n is 4
4 <= 1 is false
answer = 4 * power(4, 3)
return answer
power(4, 3)
m is 4
n is 3
3 <= 1 is false
answer = 4 * power(4, 2)
return answer
power(4, 2)
m is 4
n is 2
2 <= 1 is false
answer = 4 * power(4, 1)
return answer
power(4, 1)
m is 4
n is 1
1 <= 1 is true
answer = 1
return answer
Contents of stacks after each recursive call to power:
power(4, 5)
m
n
4
5

power(4, 4)
m
n
4
5
4
4

power(5, 2)
m
n
4
5
4
4
4
3

power(5, 1)
m
n
4
5
4
4
4
3
4
2

Section 12.3
1.

float powerRaiser(int base, int power)


{
if (base == 0)

power(5, 1)
m
n
4
5
4
4
4
3
4
2
4
1

43

44

Answers to Odd Numbered Exercises

return 0;
else if (power == 0)
return 1;
else if (power < 0)
return 1.0 / base;
else
return base * powerRaiser(base, power - 1);
}
3. If the stopping condition for the Fibonacci number function were just (n == 1), the function would
call itself indefinitely. This occurs because not testing for (n == 2) allows n to become less than
the stopping value of 1, for example, n2 = 0 when n is 2. Since the stopping value of 1 is passed
over and can never be reached, 2 is continually subtracted from n, and the function continues
indefinitely.

Section 12.4
1.The initial call is to binsearch(table, 35, 0, 8)
2. middle is 4 and table[4] is 45, so the next call is to binsearch(table, 35, 5, 8)
3. middle is 6 and table[6] is 51 so 6 is returned as the function result; this result is passed up the chain
of recursive calls.

Section 12.5
1. Thirty-one moves are needed to solve the five-disk problem. The number of moves required to solve
the n-disk problem is 2n 1.

Chapter 13

Section 13.1
1. a.

The string CA is stored in the current field of the struct pointed to by p.

b. Copies the volts member of the struct pointed to by q to the volts member of the struct
pointed to by p.
c. The contents of the struct pointed to by q is copied into the struct pointed to by p.
d. p now contains the same memory address as q; i.e., it points to the same node.
e. Copies the string HT to the current field of the struct pointed to by p.
f. Invalid; the current field cannot be assigned an integer value.
g. Invalid; p cannot be assigned an integer.
h. Invalid.
3. a. (*p).current = CA;
b. (*p).volts = (*q).volts;

e. (*p).current = HT;
f. (*p).current = (*q).volts;

Answers to Odd Numbered Exercises

45

Section 13.2
1. The memory is not returned to the heap so it is unavailable for other programs and/or operations that
could use it.

Section 13.3
1. a.

Assigns the link field of the struct pointed to by r to point to the same node as p. Node pointed
to by q is deleted from this new circular list of 2 nodes.

b. Assigns NULL to the link field of the struct pointed to by p, thereby disconnecting this node
from the rest of the list.
c. Assigns the link field of the struct pointed to by p to point to the node pointed to by r. The list
is unchanged.
d. Causes the link field of the struct pointed to by p to point to the node pointed to by the link
field of the node pointed to by q, NULL. Effectively disconnects the rest of the list from the node
pointed to by p.
e. Assigns p to point to the struct pointed to by ps link field (node pointed to by r). The original
first node is deleted from the list.
f. Copies the word field the from the struct pointed to by r to the word field of the node that p
points to.
g. Assigns the count field of the struct pointed to by p to the same value as the count field of the
struct pointed to by q (ps count field is assigned the value 3).
h. Assigns the link field of the struct pointed to by r to NULL by following the chain of pointers
starting from p. The node pointed to by q is disconnected from the rest of the list.
i. Creates a new node and stores its address in the link field of the struct pointed to by q.
Initializes the fields of the newly created node to zzz, 0, and NULL for word, count, and
link. Thus, a new node is added to the end of the linked list.
j. Traverses through the list, incrementing the count field of each node by one until all nodes have
been processed.
3. Assume the pointer to the node to be removed is a list iterator named ptr and the list is referenced
by l. Use the statement:
l.remove(*ptr);

Section 13.4
1. s.push(*); pushes *, |*
s.pop(); pops *
stack is empty
s.push(-); pushes -, |s.push(c); pushes c, |-c
nextCh = s.top(); nextCh is c, stack is unchanged
if (s.empty())
cout << stack is empty << endl;
Stack s is not empty. Does not display message.

46

Answers to Odd Numbered Exercises

3. Algorithm for copyStack:


1. Allocate storage for a temporary stack.
2. While the existing stack is not empty
2.1
Retrieve and pop the next item from the existing stack.
2.2
Push the item onto a temporary stack.
3. While the temporary stack is not empty
3.1
Retrieve and pop the next item from the temporary stack.
3.2
Push the item onto the original stack and onto the copy stack.

Section 13.5
1. Insert Harris
Original Queue
McMann
Wilson
Carson

Queue After Insertion of Harris


McMann
Wilson
Carson
Harris

After insertion, front points to McMann and rear points to Harris.


Insert Smith
Original Queue
McMann
Wilson
Carson

Queue After Insertion of Smith


McMann
Wilson
Carson
Harris
Smith

After insertion, front points to McMann and rear points to Smith.


Remove one customer
Original Queue
McMann
Wilson
Carson

Queue After Removal of McMann


Wilson
Carson
Harris
Smith

After removal of McMann, front points to Wilson and rear points to Smith. There are four
passengers left.
3.
// Insert an element at the front of the queue
// Pre : none
// Post: The value x is inserted
//
at the front of the queue.

Answers to Odd Numbered Exercises

47

template<class queueElement>
void queue<queueElement>::rudeInsert
(const queueElement& e1)
// IN to insert
{
// Local data
queueNode* oldFront;

// pointer to old front

if (frontP == NULL)
{ // empty queue
frontP = new queueNode;
rearP = frontP;

// queue w/one element

}
else
{
oldFront = frontP;
frontP = new queueNode;
frontP->link = oldFront;

// save old front


// new first element
// connect up

}
frontP->item = e1; // insert at front
numItems++;
}

Section 13.6
1. The first tree is a binary search tree whereas the second is not.
Inorder traversal of first tree: 10, 15, 20, 40, 50, 55, 60
Inorder traversal of second tree: 25, 30, 45, 40, 50, 55, 60
In the left subtree of the node containing 50, one would expect to find key values that are less than 50
and greater than 40.
3.

25

/
15
/
10
\
12
b.

\
45
\
60
/
55

25
\ \
12 55
/ \ / \
10 15 45 60

48

Answers to Odd Numbered Exercises

c.

25
/
\
12 55
/ \ / \
10 15 45 60

d.

10
\
12
\
15
\
25
\
45
\
55
\
60

Answers to Odd Numbered Exercises

49

Trees (b) and (c) are the most efficient to search.


The binary search trees in (b) and (c) are full binary search trees. Every node, except the leaves, has a
left and a right subtree. Searching the tree is an O(log N) process.
For the binary search tree in (d), each node has an empty left subtree. Searching (d) is an O(N)
process just as in searching a linked list with the same keys.

Section 13.7
1. The public insert function has 1 argument and is called using dot notation. The private insert
function has 2 arguments.
3. 1. The node has 0 children; the node can be deleted.
2. The node has 1 child; its parent should connect to this nodes child, thereby deleting this node.
3. The node has 2 children; the item must be replaced by the next larger item that will be found in a
leaf of its right subtree. Delete the leaf node (Case 1).

Section 13.8
1. Excluding the pointer comparisons (testing for NULL):
a. With a target key of 50, two comparisons are necessary to find the target:
Key

Result

Subtree Taken

40

40 < 50

Right

50

50 == 50

None

b. With a target key of 55, four comparisons are necessary to find the target:

c.

Key

Result

Subtree Taken

40

40 < 55

Right

50

50 < 55

Right

60

60 > 55

Left

55

55 == 55

None

With a target key of 10, three comparisons are necessary to find the target:
Key

Result

Subtree Taken

40

40 > 10

Left

15

15 > 10

Left

10

10 == 10

None

d. With a target key of 65, three comparisons are necessary to determine that 65 is not present:
Key

Result

Subtree Taken

40

40 < 65

Right

50

50 < 65

Right

60

60 < 65

Right, empty

50

Answers to Odd Numbered Exercises

e.

f.

With a target key of 52, four comparisons are necessary to determine that 52 is not present:
Key

Result

Subtree Taken

40

40 < 52

Right

50

50 < 52

Right

60

60 > 52

Left

55

55 > 52

Left, empty

With a target key of 48, two comparisons are necessary to determine that 48 is not present:
Key

Result

Subtree Taken

40

40 < 48

Right

50

50 > 48

Left, empty

3. There will be no left subtree for each node, only a right subtree. The big-O notation for searching a
tree like this is O(N).

Chapter 14

Section 14.1
1. A running program can be pre-empted at any time by the hardware interrupt system allowing access
to the CPU in a predictable way that is independent of the programs that are running and adjustable
based on criteria such as priority.
3. Time sharing refers to allocating each system user a portion of the available CPU time thus sharing
the CPU time among multiple users. A time slice is the unit of time allocated to a system user during
their portion of the available CPU time.

Section 14.2
1. With the fork function.
3. With the execl function.

Section 14.3
1. Pipes may only be used with processes that are running on the same CPU and that have a common
ancestor.
3. With the dup2 function.

Section 14.4
1. With the pthread_create function.
3. With the pthread_mutex_lock and pthread_mutex_unlock functions.

S-ar putea să vă placă și