Answers odd self 6th edition C++

Embed Size (px)

Citation preview

  • 8/10/2019 Answers odd self 6th edition C++

    1/50

    Friedman/Koffman 6th

    Edition

    Answers to Odd-Numbered Exercises

    Chapter 1

    Section 1.1

    1. microcomputers (hand-held or palm, netbook, laptop, desktop)

    minicomputersmainframes and supercomputers

    3. The first electronic digital computer was designed in the late 1930s by Dr. John Atanasoff andClifford Berry. J. Presper Eckert and John Mauchley designed the ENIACthe earliest, large-scalegeneral-purpose electronic digital computer. The basis for the modern digital computer is credited toVon 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 letterwill be stored on a secondary storage device. Usually this will be the computers hard disk, but it maybe stored on a floppy disk or zip disk too. A software package that you purchase is installed on thehard disk. Very large files that are no longer needed would also go on a secondary storage device, butprobably not the hard disk.

    9. 354 + ( - 26) or 328

    Section 1.3

    1. a. Store the difference of gr oss and net in prof i t .

    b. Multiply 1. 8times cel s i us , add 32, and store the sum in f ahr en.

    c. Store per cent divided by 100. 0in f ract i on.

    d. Store sumplus xin sum.

    e. Add the product of ol dPr i nci pal times i nt er est to ol dPr i nci pal . Store the sum innewPrincipal. Another way to say this is: add i nt er est to 1. 0. Multiply ol dPr i nci pal bythis sum. Store the result in newPr i nci pal .

  • 8/10/2019 Answers odd self 6th edition C++

    2/50

    2 Answers to Odd Numbered Exercises

    f. Subtract 32.0 from f ahr en, multiply the difference by 5 and then divide the product by 9. Thisshould convert a temperature in degrees Fahrenheit (value of f ahr en) to degrees Celsius.

  • 8/10/2019 Answers odd self 6th edition C++

    3/50

    Answers to Odd Numbered Exercises 3

    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 fractionconsists 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 syntaxerrors. Syntax errors can be corrected by going back to the word processor or to the editor window inan Integrated Development Environment.

    3. It is possible that certain programming environments may leave the source program in memoryinstead of saving it to a disk. A source program could be lost if it is not explicitly saved to disk afterevery 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 thecompiler, is a syntax free machine language translation of the source program entered. The linkercombines additional object programs with the original object program to form the executableprogram. The final step involves the loaderloading 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 tostop 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 knowwill not send you a virus intentionally, but sometimes a friends computer will be controlled by ahacker 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 areviruses or worms. These malicious programs can execute when you open the attachment.

  • 8/10/2019 Answers odd self 6th edition C++

    4/50

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

    f l oat mi l es, / / i nput : di stance i n mi l es

    kms; / / out put : di st ance i n ki l omet er s

    3. The variable declarations tell the compiler how to allocate storage. Executable statements aretranslated into machine language. Compiler directives, comments, and usi ng namespacestatements are not translated into machine language.

    5. The symbol >> is the extraction operator. It is used to extract characters or their numeric values froma data file (or the keyboard) and store them in a memory cell. The symbol wei ght ;

    Section 2.2

    1. C++ reserved words cant be used as identifiers.

    3. C++ reserved words: f l oat , return

    Valid Identifiers: var, so_ i s_thi s , cout , xyz123, Bi l l , t hi s I sLong,under _scor e, r at e, i ncl ude, st ar t

    Invalid Identifiers: x=y*z, Prog#2, hyphen- at e, 123xyz, hel l o, 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 theprogrammer. Predefined types have data stores that are variables; class types have data stores that areobjects. A string is a class type.

    3. a. 0. 0345

    3456000

    345678

    b. 5. 678E3or 5. 678e3

    5. 6789E2or 5. 6789e2

    5. 67E- 3or 5. 67e- 3

  • 8/10/2019 Answers odd self 6th edition C++

    5/50

    Answers to Odd Numbered Exercises 5

    5. The area of a circle would be a f l oat . The number of cars passing through an intersection in anhour would be an i nt . A name would be stored in a st r i ngvariable. The first letter of a last namewould be stored in a char .

    7. The first declaration stores the character r in the variable col or which is of data type char .

    The second declaration stores the literal string r in the variable col or Swhich is of class typest r i ng.

    9. The first declaration declares nameas a type st r i ngvariable whose contents is not defined yet.The second declaration stores the literal string Obama in the string variable pr es. The thirddeclaration creates a type string constant FI RST_PRESthat will always store the literal stringWaShi ngton.

  • 8/10/2019 Answers odd self 6th edition C++

    6/50

    6 Answers to Odd Numbered Exercises

    Section 2.4

    1. Ent er t wo number s: 3.0 5.0 ( dat a ent er ed i n i t al i cs)

    a = - 2

    b = - 10

    Note: This assumes aand bare declared as type doubl eor f l oat .

    3. My name is: Doe, Jane

    I l i ve i n Ann Ar bor, MI and my zi p code i s 48109

    5. The library is i ostr eam.

    Section 2.5

    1. / * Thi s i s a comment ? * /

    / * Thi s one */

    / * seems l i ke a comment */

    / * doesn t i t * /

    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. i = a % b; i is assigned 3b. i = ( MAX_I - 990 / a); i is assigned 3

    c. i = a % y; invalid: ymust be type i nt

    d. i = ( 990 - MAX_I ) / a; i is assigned 3

    e. i = PI * a; i is assigned 9

    f. x = PI * y; xis assigned 3.14159

    g. x = PI / y; xis assigned 3.14159

    h. i = ( MAX_I - 990) % a i is assigned 1

    i. x = a % ( a / b) ; runtime error: cannot divide by 0

    j. i = a % 0; runtime error: cannot divide by 0

    k. i = b / 0; runtime error: cannot divide by 0l. i = a % ( MAX_I - 990) i is assigned 3

    m. x = a / y; i is assigned 3.0

    n. i = a % ( 990 - MAX_I ) ; syst em dependent , 3 or 3

    o. x = a / b; xis assigned 0

  • 8/10/2019 Answers odd self 6th edition C++

    7/50

    Answers to Odd Numbered Exercises 7

    7. a. whi t e = col or * 2. 5 / pur pl e; whi t e is assigned 1.66667

    b. gr een = col or / pur pl e; gr eenis assigned 0.666667

    c. or ange = col or / r ed; or angeis assigned 0

    d. bl ue = ( col or + st r aw) / ( crayon + 0. 3) ; bl ueis assigned 3

    e. l i me = r ed / col or + r ed % col or ; l i meis assigned 2f. pur pl e = st r aw / r ed * col or ; pur pl eis assigned 0

    Section 2.7

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

    Chapter 3Section 3.1

    1. Problem Output

    f l oat numGal l ons / / gal l ons of gas pur chased

    f l oat mi l esPer Gal l on / / amount of gas used up ever y mi l e

    Problem Input

    f l oat mi l es / / mi l es t he car can dr i ve

    f l oat gasCost / / f i nal gas bi l l

    f l oat cost Per Gal l on / / cost of a gal l on of gas

    Formulas

    number of miles =number of gallons miles per gallon

    cost of gas =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 numGal l ons * mi l esPerGal l onto mi l es

    5.1 Assign numGal l ons * cost Per Gal l onto gasCost

  • 8/10/2019 Answers odd self 6th edition C++

    8/50

    8 Answers to Odd Numbered Exercises

    3. Problem Input

    f l oat t r i pDi st ance / / mi l es t r avel ed dur i ng t he t r i p

    f l oat mi l esPer Gal l on / / amount of gas used up ever y mi l e

    f l oat cost Per Gal l on / / cost of a gal l on of gas

    Problem Output

    f l oat t r i pCost / / t otal cost of t he t r i p

    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

    f l oat numGal l ons / / number of gal l ons

    Algorithm Refinements

    4.1 Assign t r i pDi st ance / mi l esPer Gal l on to numGal l ons

    4.2 Assign numGal l ons * cost Per Gal l onto t r i pCost

    5. Program outline

    / / Comput es t he gr oss sal aryi nt mai n ( ){

    f l oat hour s / / hour s worked by empl oyee

    f l oat r at e / / hour l y pay r at e

    f l oat gr oss / / empl oyee s gr oss sal ar y

    / / Get t he hour s wor ked.

    / / Get hour l y r at e.

    / / Comput e gr oss sal ar y.

    / / Assign hours * rate to gross

    / / Di spl ay gr oss sal ar y.

    }

  • 8/10/2019 Answers odd self 6th edition C++

    9/50

    Answers to Odd Numbered Exercises 9

    Section 3.2

    1. a. sqr t ( u + v) * w * w

    b. l og( pow( x, y))

    c. sqr t ( pow( x- y, 3) )

    d. f abs(( a/ c)- ( w*z))

    3. It is system dependent. Some C++ versions will consider this a syntax error. Some will convert thereal argument to an integer (truncate the fractional part) and return the absolute value of the integer.

    Section 3.3

    1.

    3. Program design.

  • 8/10/2019 Answers odd self 6th edition C++

    10/50

    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 byanother 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 byother functions or programs. Functions with arguments are building blocks for constructing largerprograms.

    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

    Scal e yes yes

    Mai n yes yes

    num1 no yes

    num2 no yes

    x(f l oat parameter) yes no

    n(i nt parameter) yes no

    scal eFact or yes no

    Section 3.7

    1. line 1: The variable nameis declared as type st r i ng.

    line 2: The prompt name: is displayed. We typeJ ones***J ohn Boy

    line 3: The literal that was typed, excluding the newline character, is stored in name.line 4: nameis searched until the group *** is found. The position of the first item in this group

    is stored in the variable start , which is 5.

    line 5: 3 characters of the string are erased, the first is the character at the position indicated bystart , and the second and third are the characters that come after that. This method callresults in the literal *** being erased and everything after *** is shifted to the left to fillin the empty space.

    line 6: A , is inserted into the string at position 5. The characters starting with the secondletterJ , which was previously at postion 5, are shifted to the right by one position.

  • 8/10/2019 Answers odd self 6th edition C++

    11/50

    Answers to Odd Numbered Exercises 11

    line 7: The modified contents in nameis displayed: Jones, John Boy.

    3. whol eName = l ast Name + , + f i r st Name;

    Section 3.8

    1. The y-dimension is smaller than the x-dimension; i.e., the height of the window (and most screens) issmaller 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 t r ue

    x < y f al se

    x >= ( y x) t r ue

    x == ( y+x- y) t r ue

    a. Either xmust be < 5. 1or xmust be >= 5. 1so one of those conditions must be true and theresult will be true regardless of the values of x and y.

    b. If qis false, then both p && qand 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 resultwill 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 = 10the output is:

    l ess

    done

    for x = 20the output is:

    done

    b.O. K.

  • 8/10/2019 Answers odd self 6th edition C++

    12/50

    12 Answers to Odd Numbered Exercises

    3. a. t he is located at position 8 (value of posTar get ) and is replaced by that .t estSt r i ngbecomes Her e i s t hat st r i ng .

    b. Hereis located at position 0 (value of posTar get ) and replaced by There.t estSt r i ngbecomes Ther e i s t he st r i ng .

    c. Wher e is not located so the condition involving posTar get is false and the error message isdisplayed.

    Section 4.4

    1. i f ( x > y)

    {

    x = x + 10. 0;

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    13/50

    Answers to Odd Numbered Exercises 13

    3. Placing braces around the last two lines in the answer to Question 1 would cause the value of yto bedisplayed only when 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

  • 8/10/2019 Answers odd self 6th edition C++

    14/50

    14 Answers to Odd Numbered Exercises

    Section 4.8

    1. r ed

    bl ue

    yel l ow

    swi t ch ( col or )

    {

    case R : case r :

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    15/50

    Answers to Odd Numbered Exercises 15

    Section 5.2

    1.

    Count Data Value Data Value Data Value

    5 6 7

    Output Output Output

    0 1 1 1

    1 5 6 7

    2 25 36 49

    3 125 216 1296

    4 Exit loop Exit loop Exit loop

    This loop displays x0through x3for every xentered by the user.

    3. The segment should read:

    count = 0;

    sum = 0;

    whi l e ( count < 5)

    {

    cout > i t em;

    sum += i t em;

    count ++;

    }

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    16/50

    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. Cel si us

    - 5

    05

    10

    c. Cel si us

    - 5

    5

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

    5. ++i ;

    --j ;

    n = i * j ;

    m = i + j ;

    j - - ;

    p = i + j ;

    7. I j Output

    5 10 5 10

    4 8 4 8

    3 6 3 6

    2 4 2 4

    1 2 1 2

    Section 5.4

    1. suppl y = 990. 0

    3. Ent er i ni t i al oi l suppl y: 5000

    Ent er amount used t oday: 4000. 5

    Af t er r emoval of 4000. 5 gal l ons,

    number of gal l ons l ef t i s 999. 5.

    999. 5 gal l ons l ef t i n t ank.

    Warni ng - amount of oi l l ef t i s bel ow mi ni mum!

  • 8/10/2019 Answers odd self 6th edition C++

    17/50

    Answers to Odd Numbered Exercises 17

    5. n n >0 && pow( 2, n) < 1000 Output

    5 t r ue 5 32

    4 t r ue 4 16

    10 f al se

    The while loop exit occurs and 5is 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 di gi t Readremains false.

    b. next Char = 2 Both relational expressions are true.

    next Char = a The first relational expression is true but the second is false.

    c. i f ( ( 0

  • 8/10/2019 Answers odd self 6th edition C++

    18/50

    18 Answers to Odd Numbered Exercises

    Section 5.7

    1. Output

    a. 5

    10

    1520

    25

    30

    35

    40

    45

    50

    b.

    f or ( num = 5; num

  • 8/10/2019 Answers odd self 6th edition C++

    19/50

    Answers to Odd Numbered Exercises 19

    3. Outer 0

    I nner 0 0

    I nner 0 1

    I nner 0 2

    I nner 0 0Outer 1

    I nner 1 0

    I nner 1 1

    I nner 1 2

    I nner 1 1

    I nner 1 0

    Section 5.9

    1. sum = 0;

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    20/50

    20 Answers to Odd Numbered Exercises

    Chapter 6

    Section 6.11. t est( m, - 63, y, x, next ) ;

    Actual Argument Formal Parameter Description

    m a i nt , value

    - 63 b i nt , value

    y c f l oat , reference

    x d f l oat , reference

    next e char , reference

  • 8/10/2019 Answers odd self 6th edition C++

    21/50

    Answers to Odd Numbered Exercises 21

    t est ( 35, m*10, y, x, next ) ;

    Actual Argument Formal Parameter Description

    35 a i nt , value

    m * 10 b i nt , valuey c f l oat , reference

    x d f l oat , reference

    next e char , reference

    t est ( m, m, x, m, a ) ;

    Not correct because the fourth parameter should be type i nt . It should also be a variable, not acharacter literal.

    3. Invalid function calls:

    e. must use variable for call by reference

    g. a, bnot declared in mai ni. must use variable for call by reference

    k. too many arguments

    Calls requiring standard conversion:

    a. value of zis converted to i nt

    d. float value returned to mis converted to i nt . If mis used as INOUT, initial value of misconverted to f l oat .

    j. value of xis converted to i nt

    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 samedenominator. You do this by multiplying the first fraction by denom2 / denom2 and the secondfraction 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. x y z w

    5 3 7 9

    5 3 8 25 3 - 2 8

    - 2 8 - 2 8

    - 10 6 - 2 8

  • 8/10/2019 Answers odd self 6th edition C++

    22/50

    22 Answers to Odd Numbered Exercises

    b. sumDi f fcomputes the sum and difference of its first two arguments and places the answers inits third and fourth parameters. The input parameters cannot be modified, but sumDi f fchangesthe value of the output parameters, which are passed by reference.

    c. / / Pre: num1 and num2 ar e def i ned.

    / / Post : num3 and num4 cont ai n t he sum and di f f er ence/ / of num1 and num2.

  • 8/10/2019 Answers odd self 6th edition C++

    23/50

    Answers to Odd Numbered Exercises 23

    Section 6.3

    1.

    / / Pre: numI t ems and sum are def i ned; numI t ems must be > 0. 0

    / / Post : I f numI t ems i s posi t i ve, t he aver age ( var i abl e ave)i s

    / / comput ed as sum / numI t ems; other wi se ave i s set t o0. 0

    / / Ret ur ns: The aver age ( var i abl e ave) i f numI t ems i s posi t i ve;

    / / ot her wi se var i abl e ave i s set t o 0. 0

    voi d comput eAve ( i nt numI t ems, / / I N: number of dat a i t ems

    f l oat sum, / / I N: sum of dat a

    f l oat & ave) / / OUT: aver age of dat a

    {

    i f ( numI t ems < 1) {

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    24/50

    24 Answers to Odd Numbered Exercises

    Section 6.4

    1.

    Statement posCommaEffect

    MoneyToNumberSt r i ng moneyToNumberSt r i ngis passed

    ( st r i ng& - $5, 405, 123. 65) - $5, 405, 123. 65 by reference

    i f ( moneySt r i ng. at ( 0) == $ ) value is false

    el se i f ( moneySt r i ng. f i nd( - $) == 0) val ue i s t r ue

    moneySt r i ng. er ase( 1, 1) ; removes the - $

    posComma = moneySt r i ng. f i nd( , ) ; 2 posCommais assigned 2

    whi l e ( posComma >= 0 && loop while posComma >= 0and

    posComma < moneySt r i ng. l ength( ) ) =11 there are no more commas inmoneySt r i ng

    Section 6.5

    1. Ent er t he number of i t ems t o be pr ocessed: 10

    Funct i on comput eSum ent ered

    The number of i t ems i s 10

    The sum of t he dat a i s 100. 00

    The aver age of t he dat a i s 10. 00

    3. Black-box testing assumes the tester has no knowledge of the system code. The tester must enterrepresentative data sets and check the correctness of the output for each input sample. White-boxtesting assumes the tester knows how the system is coded. The tester must provide a data set for eachpossible execution path. Top-down testing involves testing the flow of control between a mainfunction and its subordinate functions, possibly using stubs for the functions that are not yetcompleted. 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 systemafter 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 thatdisplays the name of the function and returns a simple value if one is needed.

  • 8/10/2019 Answers odd self 6th edition C++

    25/50

    Answers to Odd Numbered Exercises 25

    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 resultn = 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. i nt gcd( i nt m, i nt n) {

    i f ( n > m)r eturn gcd( n, m) ;

    el se i f ( m % n == 0)r et ur n n;

    el sereturn gcd( n, m % n) ;

    }

    Chapter 7Section 7.1

    1. const i nt MAXI NT = 32767; valid

    const i nt MI NI NT = - MAXI NT; valid, MI NI NTis - 32767

    const char FI RST_FEMALE = Eve; invalid char constant

    const i nt MAX_SI ZE = 50. 5; invalid i nt constant

    const i nt MI N_SI ZE = maxsi ze - 10; invalid expression

    const i nt I D = 4FD6; invalid int constant

    const i nt KOFFMAN_AGE = 67; valid

    const i nt FRI EDMAN_AGE = z66; invalid int constant

    const f l oat PRI CE = $3, 335. 50; invalid f l oat constant

    const f l oat PRI CE = 3335. 50; valid

    const f l oat PRI CE = 3335. 50; invalid f l oat constant

  • 8/10/2019 Answers odd self 6th edition C++

    26/50

    26 Answers to Odd Numbered Exercises

    3. The difference between the #def i neand the const declaration is that the identifier used in the#def i nehas no storage associated with it. The #def i neis a compiler directive that tells thecompiler to replace one string of characters with another everywhere the first string of charactersappears in the source file. Using a const declaration involves placing the constant value in a storagelocation. The contents of this storage location cannot be changed during program execution.

    Generally a constant declaration is preferred in C++.

    Section 7.2

    1. 2151 (32767)

    3. For x = 6. 875the result is 6. 88.

    For x = - 6. 875 the result is 6. 87.

    i f ( x >= 0)

    x = f l oat ( i nt ( x * 100 + 0. 5) ) / 100. 0;

    el se

    x = f l oat ( i nt ( x * 100 0. 5) ) / 100. 0;

    5. a. 3.0 b. 12.9 c. 12.9 d. 13

  • 8/10/2019 Answers odd self 6th edition C++

    27/50

    Answers to Odd Numbered Exercises 27

    Section 7.3

    1. Note it is not really necessary to know the ASCII code. Each of these answers can be determinedwithout using the actual code values.

    a. i nt ( d ) i nt ( a )

    100 97 = 3b. char ( ( i nt ( M ) i nt ( A ) ) + i nt ( a ) )

    char ( ( 77- 65) + 97)

    char ( 109) = m

    c. i nt ( 7 ) i nt ( 0 )

    55 48 = 7

    d. char ( i nt ( 5 ) + 1)

    char ( 53 + 1)

    char( 54) = 6

    3. Type Value Explanation

    a. i sdi gi t ( a ) ; i nt f al se a is not the characterrepresentation of a digit.

    b. i sdi gi t ( 7 ) ; i nt t r ue 7 is the characterrepresentation of a digit.

    c. i sdi gi t ( 9) ; i nt f al se 9is not the characterrepresentation of a digit

    d. t oupper ( # ) ; char # # is not a letter.

    e. t ol ower ( A ) ; char a A is uppercase; returnscorresponding lowercase.

    f. t ol ower( p ) ; char p p is lowercase.

    g. di gi t ToNumber ( 0 ) i nt 0 Returns the numbercorresponding to 0

    Section 7.4

    Condition Complement

    1. a. x y | | x ! = 25

    b. ( x > y && x ! = 15) | | z 8 f l ag | | x y) ;

    This assign the value of the bool expression x > yto xBi gger . It is more efficient.

  • 8/10/2019 Answers odd self 6th edition C++

    28/50

    28 Answers to Odd Numbered Exercises

    Section 7.5

    1. The enumerator r edhas value 0, green has value 1, yellow has value 2, and blue has value 3.

    The type dayenumerators have values 0, 1, 2, . . . , 6. The type speci al Char s

    enumerators have values \ b , \ a , \ n , \ r , \ t , \ v (8, 7, 10, 13, 9, 11).

    3. a. enum l ogi cal {t r ue, f al se}; invalid: t rueand f al seare values of typebool .

    b. enum l et t er s {A, B, C}; valid

    enum t wol et t er s {A, B}; invalid: an identifier may not be used morethan once in any enumeration within the samescope of definition.

    c. enum day {sun, mon, t ue,wed, t hu, f r i , sat };

    valid

    enum weekDay {mon, t ue, wed,t hu, f r i }; invalid: see reason in Part b above

    enum weekEnd {sat , sun}; invalid: see reason in Part b above

    d. enum t r af f i cLi ght {r ed,yel l ow, gr een};

    valid

    i nt gr een; 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 be1. 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 wouldbe 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. ci n >> next ; skips over white space. Any blank characters in the input would not be counted.The while loop wouldnt terminate on newlines.

    3. ci n >> n >> n >> x >> c >> c >> c >> c >> n >> c;

    5. If the innermost ci n. get were omitted, the program would execute forever as no new datacharacters 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 cwhich is not numeric, therefore, the value of m is not defined.

  • 8/10/2019 Answers odd self 6th edition C++

    29/50

    Answers to Odd Numbered Exercises 29

    Section 8.2

    1. The eis read in the loop in function copyLi ne. It is written to the output file. The s is read nextand written to the output file. The . is read next and written to the output file. The is readnext, causing loop exit. is written to the output file. Control passes back to main.

    li neCount is incremented. Since end-of-file is true, the loop in mai nis exited. Statistics aredisplayed 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 aredebugging 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 beskipped when reading the next employees first name. A blank line at the end would cause thewhile loop to execute an extra time.

    3. getline(eds, name, \n);

    eds >> hours >> r at e;

    or if youwanted to read data into f i r st Nameand l ast Name:

    get l i ne( eds, f i rst Name, ) ;

    get Li ne( eds, l ast Name, \ n ) ;

    eds >> hour s >> r at e;

    5. Open input file oneOpen the output fileSet payroll to 0while not at the end of input file 1

    Read the employee name and hourly rate from file 1Set found to falseOpen input file 2while not found and not at the end of input file 2

    Read the employee name and hours worked from file 2if the names are the same

    Calculate the employees salary and add it to payrollSet found to true

    Write the employees name and salary to the output fileend of inner loopif not found

    Display a message that employees hours worked are missingClose input file 2

    end of outer loopDisplay the total payrollClose all files

  • 8/10/2019 Answers odd self 6th edition C++

    30/50

    30 Answers to Odd Numbered Exercises

    Section 8.4

    1. To write the name and salary on separate lines use the following statement:

    pds

  • 8/10/2019 Answers odd self 6th edition C++

    31/50

    Answers to Odd Numbered Exercises 31

    Section 9.3

    1. size1.

    3. / / Pr e: a1, a2 ar e def i ned./ / Post : cont ent s of a1 ar e exchanged wi t h the cont ent s of a2.

    i nt exchange

    ( i nt & a1, / / i t em t o exchange wi t h a2

    i nt & a2) / / i t em t o exchange wi t h a1

    {

    i nt t emp; / / st or es ( saves) cont ent s of a1 pr i or t o movi ng

    / / cont ent s of a2 i nt o a1

    t emp = a1;

    a1 = a2;

    a2 = t emp;

    } / / end exchange

    / / Pr e: a[ i ] and b[ i ] ( 0

  • 8/10/2019 Answers odd self 6th edition C++

    32/50

    32 Answers to Odd Numbered Exercises

    {

    f or ( i nt i = 0;

    i < si ze 1 && a[ i ] == b[ i ] ;

    i ++) ;

    r et ur n a[ i ] == b[ i ] ;

    } / / end sameAr r ay

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

    Section 9.4

    1. In r eadScor es, the i nt array scores must be changed to f l oat . Local data SENTI NELandt empScore must be changed from i nt to f l oat .

    3. The number of scores to read could be different from MAX_SI ZE(the declared size), so the functionshould read this number into secti onSi zefrom the data file and compare it to MAX_SI ZE. If it islarger than MAX_SI ZE, reset secti onSi zeto MAX_SI ZEand display a warning that onlyMAX_SI ZEscores can be read the rest will be ignored. This is all to be done before the while-loop.If secti onSi zeis smaller or less than MAX_SI ZEthen execute the while-loop. The value forsect i onSi ze should be the first value in the data file and should be the only value on the firstline.

    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 t ar get is returned to the calling function.

    3. We could use a function f i ndI ndexOf Maxto arrange the data items in the array in descendingorder. We should also change the variable mi nSubto maxSubto improve readability.

    5. Before the call to the function exchange, we could check to see if mi nSub == i . Callexchangeonly if these two values are not equal.

    i f ( i ! = mi nSub)

    exchange( i t ems[ mi nSub] , i t ems[ i ] ) ;

    This i f - statement always increases the number of comparisons by 1 for each pass but can decreasethe number of exchanges.

    Section 9.6

    1. a. Executes ntimes for each i, or n2times; O(n2).

    b. Executes 2 times for each i, or 2ntimes; O(n).

    c. Executes ntimes for each i, or n2times; O(n2).

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

  • 8/10/2019 Answers odd self 6th edition C++

    33/50

    Answers to Odd Numbered Exercises 33

    Section 9.7

    1.a. 45

    b. cout

  • 8/10/2019 Answers odd self 6th edition C++

    34/50

    34 Answers to Odd Numbered Exercises

    To call this function to display an Employee struct, simply state:pr i ntEmpl oyee( oneEmpl oyee) ;

    Section 9.10

    1. a. gender attribute of second employee

    b. invalid

    c. the last employee (a struct)

    d. invalid

    e. invalid

    f. invalid

    g. the last employees name

    h. invalid

    3. a. company[ 0] . nameb. company[ 1] . i d

    c. company[ 1] . name

    d. company[ 0] . i d

    Section 9.11

    1.a. char dayName[ ] = Sunday;

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    35/50

    Answers to Odd Numbered Exercises 35

  • 8/10/2019 Answers odd self 6th edition C++

    36/50

    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 aparticular object of this class using dot notation.

    3. a. count er c1( 20) ;

    b. c1. setCount ( 15) ;

    c. c1. decr ement ( ) ;

    d. c1. decr ement ( ) ;

    e. decr ement ( ) ;

    Section 10.2

    1. The scope resolution operator : : is used as a prefix to the function name in each member functionheader. 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. Theargument of the second constructor can be used to set the initial state of the new object. The compilercan determine which overloaded constructor function to use based on the presence or absence of anactual argument.

    Section 10.3

    1. count s[ 2] . set Count ( 5) ;

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    37/50

    Answers to Odd Numbered Exercises 37

    3. Replace the body of function subt r act with return

    f 1. add( f 2. negat e( ) ) ; . This statement uses method negat eto negate fraction f 2and thenadds this result to fraction f 1using function add.

  • 8/10/2019 Answers odd self 6th edition C++

    38/50

    38 Answers to Odd Numbered Exercises

    Section 10.6

    1.

    3. To form a rectangle class, substitute the attributes wi dt hand l engt h (type f l oat ) for theattribute r adi us . Replace member function set Radi uswith set Di mensi ons. The function

    set Di mensi ons would have two arguments, representing the width and length of a rectangle.Replace member function get Radi us with two accessor functions: get Wi dthand get Length.Replace di spl ayCi r cl ewith di spl ayRect angl e. The bodies of the new member functionswould process the new attributes. Functions comput eAr eaand comput ePer i met er would dothe calculations for a rectangle instead of a circle. The five member functions that set and retrieve theobjects coordinates and color would be unchanged.

    5. It is a local constant in function si mpl eSt r i ng: : 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 si mpl eSt r i ngare to behidden from the driver function, while the member function wr i t eSt r i nghas access to the classdata members. So the for loop in the driver function uses the public member function get Lengt h,while the fo r loop in the member function wr i t eSt r i ng uses l engt h.

    Section 10.8

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

    Chapter 11

    Section 11.1

    1. dummy a, b, c;

    f l oat num1, num2, n1, n2, sum;

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    39/50

    Answers to Odd Numbered Exercises 39

    ci n >> num1 >> num2;

    a. set I t em( num1) ;

    b. set I t em( num2) ;

    c. set I t em( a. get I t em( ) + b. get I t em( ) ) ;

    sum = c. get I t em( ) ; cout

  • 8/10/2019 Answers odd self 6th edition C++

    40/50

    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 largerthan the array element they follow.

    3. Change the function body to:{f or ( i nt i = 0; i < si ze; i ++)

    i f ( el ement s[ i ] == t ar get )return i ;

    r et ur n - 1;}

    Section 11.4

    1. The advantage of the current approach is that the cont act Li st class is not restricted to using ani ndexLi st for data storage in a cont act Li st object. The private data member cont act s could be changed to some other data type. It also enables the client to call member functions for ageneral cont act Li st object rather than using member functions specific to the i ndexLi st class.

    3. 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 functionselectOp, the prefix addressBook. should be removed before each member function of contactListcalled in selectOp. The reason for the approach taken is that the actual interaction that takes placeinteractively with the program user should be determined within the client program, not within thecontactList class.

    Section 11.5

    1. In the definition of friend operator >>, all three occurrences of operators >in the bodyhave a stream as the left operand and a string object as the right operand. C++ has defined >>and

  • 8/10/2019 Answers odd self 6th edition C++

    41/50

    Answers to Odd Numbered Exercises 41

    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

  • 8/10/2019 Answers odd self 6th edition C++

    42/50

    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

  • 8/10/2019 Answers odd self 6th edition C++

    43/50

    Answers to Odd Numbered Exercises 43

    3. power( 4, 5)

    mis 4

    nis 5

    5

  • 8/10/2019 Answers odd self 6th edition C++

    44/50

    44 Answers to Odd Numbered Exercises

    r et ur n 0;

    el se i f ( power == 0)

    r et ur n 1;

    el se i f ( power < 0)

    r et ur n 1. 0 / base; el se

    r et ur n base * power Rai ser ( base, power - 1) ;

    }

    3. If the stopping condition for the Fibonacci number function were just ( n == 1) , the function wouldcall itself indefinitely. This occurs because not testing for ( n == 2) allows n to become less thanthe stopping value of 1, for example, n2= 0 when nis 2. Since the stopping value of 1is passedover and can never be reached, 2is continually subtracted from n, and the function continuesindefinitely.

    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 chainof 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 vol ts member of the struct pointed to by qto the vol t s member of the structpointed to by p.

    c. The contents of the struct pointed to by qis 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 cur r ent field cannot be assigned an integer value.

    g. Invalid; pcannot be assigned an integer.

    h. Invalid.

    3. a. ( *p) . cur r ent = CA; e. ( *p) . cur r ent = HT;

    b. ( *p) . vol t s = ( *q) . vol t s ; f. ( *p) . cur r ent = ( *q) . vol t s;

  • 8/10/2019 Answers odd self 6th edition C++

    45/50

    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 thatcould use it.

    Section 13.31. a. Assigns the l i nkfield of the struct pointed to by r to point to the same node as p. Node pointed

    to by qis deleted from this new circular list of 2 nodes.

    b. Assigns NULLto the l i nkfield of the struct pointed to by p, thereby disconnecting this nodefrom the rest of the list.

    c. Assigns the l i nkfield of the struct pointed to by pto point to the node pointed to by r . The listis unchanged.

    d. Causes the l i nk field of the struct pointed to by pto point to the node pointed to by the linkfield of the node pointed to by q, NULL. Effectively disconnects the rest of the list from the nodepointed to by p.

    e. Assigns pto 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 wor dfield t he from the struct pointed to by r to the wor dfield of the node that p

    points to.

    g. Assigns the count field of the struct pointed to by pto the same value as the count field of thestruct pointed to by q(ps count field is assigned the value 3).

    h. Assigns the l i nkfield of the struct pointed to by r to NULLby following the chain of pointersstarting from p. The node pointed to by qis disconnected from the rest of the list.

    i. Creates a new node and stores its address in the l i nkfield of the struct pointed to by q.Initializes the fields of the newly created node to zzz, 0, and NULLfor wor d, count , andl i nk. 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 havebeen processed.

    3. Assume the pointer to the node to be removed is a list iterator named pt r and the list is referencedby l . Use the statement:

    l . r emove( *pt r ) ;

    Section 13.4

    1. s. push( * ) ; pushes *, | *

    s. pop( ) ; pops * st ack i s empt y

    s . push( - ) ; pushes - , | -s. push( c ) ; pushes c, | - c

    next Ch = s. t op( ) ; nextCh i s c, st ack i s unchanged

    i f ( s. empt y( ) )

    cout

  • 8/10/2019 Answers odd self 6th edition C++

    46/50

    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 Queue After Insertion of Harris

    McMann McMann

    Wilson WilsonCarson Carson

    Harris

    After insertion, f r ont points to McMann and r ear points to Harris.

    Insert Smith

    Original Queue Queue After Insertion of Smith

    McMann McMann

    Wilson Wilson

    Carson Carson

    HarrisSmith

    After insertion, f r ont points to McMann and r ear points to Smith.

    Remove one customer

    Original Queue Queue After Removal of McMann

    McMann Wilson

    Wilson Carson

    Carson Harris

    Smith

    After removal of McMann, f r ont points to Wilson and r ear points to Smith. There are fourpassengers left.

    3.

    / / I nser t an el ement at t he f r ont of t he queue

    / / Pr e : none

    / / Post : The val ue x i s i nser t ed

    / / at t he f r ont of t he queue.

  • 8/10/2019 Answers odd self 6th edition C++

    47/50

    Answers to Odd Numbered Exercises 47

    t empl at e

    voi d queue: : r udeI nser t

    ( const queueEl ement & e1) / / I N t o i nser t

    {

    / / Local dat aqueueNode* ol dFront ; / / poi nt er t o ol d f r ont

    i f ( f r ont P == NULL)

    { / / empt y queue

    f r ont P = new queueNode;

    r ear P = f r ont P; / / queue w/ one el ement

    }

    el se

    {

    ol dFront = f r ont P; / / save ol d f r ont

    f r ont P = new queueNode; / / new f i r st el ement

    f r ont P- >l i nk = ol dFr ont ; / / connect up

    }

    f r ont P- >i t em = e1; / / i nser t at f r ont

    numI t ems++;

    }

    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, 60Inorder 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 50and greater than 40.

    3.

    a 25/ \

    15 45/ \

    10 60

    \ /12 55

    b. 25\ \

    12 55/ \ / \

    10 15 45 60

  • 8/10/2019 Answers odd self 6th edition C++

    48/50

    48 Answers to Odd Numbered Exercises

    c. 25/ \

    12 55/ \ / \

    10 15 45 60

    d. 10\

    12

    \

    15

    \

    25

    \

    45

    \

    55

    \

    60

  • 8/10/2019 Answers odd self 6th edition C++

    49/50

    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 aleft 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 i nser t function has 1 argument and is called using dot notation. The private i nser tfunction 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 aleaf 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:

    Key Result Subtree Taken

    40 40 < 55 Right

    50 50 < 55 Right

    60 60 > 55 Left

    55 55 == 55 None

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

  • 8/10/2019 Answers odd self 6th edition C++

    50/50

    50 Answers to Odd Numbered Exercises

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

    f. 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 atree 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 accessto 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 sharingthe CPU time among multiple users. A time slice is the unit of time allocated to a system user duringtheir portion of the available CPU time.

    Section 14.2

    1. With the fo rkfunction.

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

    3. With the dup2function.

    Section 14.4

    1. With the pt hr ead_cr eat efunction.