Data Structures and Other Objects Using C++ 4th Edition Solution Manual

Need to ace your assignments? Use Data Structures and Other Objects Using C++ 4th Edition Solution Manual for detailed, easy-to-understand solutions to textbook questions.

Olivia Parker
Contributor
4.1
58
5 months ago
Preview (8 of 26 Pages)
100%
Purchase to unlock

Page 1

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 1 preview image

Loading page image...

Chapter1:SolutionstoSampleExamQuestionsShortAnswerQuestions1.1.Useaprecondition/postconditioncontract.Forexample:doublenew_balance(doublebalance,doubleinterest_rate);//Precondition:Theparameterinterest_rateistheannualbank//accountinterestrate,forexample5.0for5%.Theparameter//balanceisanaccountbalancebeforeinterestisposted.//Postcondition:Thevaluereturnedbythefunctionisthenew//accountbalanceafterpostingoneyearofsimpleinterestat//therategivenbyinterest_rate.1.2.Apreconditionisastatementgivingtheconditionthatissupposedtobetruewhenafunctioniscalled.Apostconditionisastatementdescribingwhatwillbetruewhenafunctioncalliscompleted.1.3.Ifthepreconditionfails,thefunctioncanprintanerrormessageandhalttheprogram.1.4.Preconditionscannotalwaysbechecked.1.5.Ifyoucallafunctionandthepreconditionisfalse,thenthereisnotellingwhatmighthappen.Anythingcouldhappen,includingerasingtheentireharddrive.Ofcourse,thefunctionsthatwewritetrytoavoidsuchunpleasantbehavior,butthereisnoguarantee.1.6.voidexam(inti)//Precondition:iisnotequalto42.//Libraryfacilitiesused:assert.h{assert(i!=42);...1.7.lognistheapproximatenumberofdigitsinn(usingbase10logs).(Theexactformulaisfloor(logn)+1,usingbase10logsandthefloorfunctionwhichroundsarealnumberdowntothenextlowestinteger.)1.8.Evenaslowprocessorwillbeatafastprocessoriftheslowerprocessorusesafasteralgorithmandtheinputsizeislargeenough.1.9.ThefirstformulaisO(n).ThesecondandfourthformulasareO(n^2)(using^forexponentiation).ThethirdformulaisO(logn).1.10.SeetheMethod2analysisonpage17ofthetext.1.11.Mydebuggerletsmerunaprogramandstopitataspecifiedpointtoexaminethecurrentvaluesofvariables.Afterthis,Icanstepthroughtheprogramonelineatatime,continuingtokeepawatchonvariablevalues.OrIcancontinueexecutioninanormalway,specifyingalaterpointtostoptheprogram.MultipleChoiceQuestions:

Page 2

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 2 preview image

Loading page image...

Page 3

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 3 preview image

Loading page image...

1.1B1.6B1.11B1.16E1.2D1.7A1.12False1.17C1.3D1.8B1.13False1.18A1.4False1.9A1.14B1.19E1.5False1.10D1.15BChapter2:SolutionstoSampleExamQuestionsShortAnswerQuestions2.1.Assumingthatweareusingthenamespacemain_savitch_2A:throttlequiz;quiz.shut_off();cout<<quiz.flow();2.2.classthrottle{public:throttle();//Cthrottle(intsize);//Cvoidshut_off();voidshift(intamount);doubleflow()const;//Xboolis_on()const;//X...2.3.Ifyouwriteaclasswithnoconstructors,thenthecompilerautomaticallycreatesasimpledefaultconstructorcalledthe"automaticdefaultconstructor".Theautomaticdefaultconstructordoesn'tdomuchwork--itjustcallsthedefaultconstructorsforthemembervariablesthatareobjectsofsomeotherclass.2.4.Aninlinememberfunctionhasit'sentireimplementationgivenrightintheclassdefinition.Forexample,thethrottle'sshut_offmemberfunctionshownhere:classthrottle{public:throttle();throttle(intsize);voidshut_off(){position=0;}...2.5.Amacroguardconsistsofthree#compilerdirectivestoavoidtheaccidentalduplicateinclusionofsomedefintions.Forexample:#ifndefthrottle_H#definethrottle_H...#endif2.6.#include"throttle.h"usingnamespacemain_savitch_2A;orusingnamespacemain_savitch_2A::throttle;

Page 4

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 4 preview image

Loading page image...

2.7.Aconstreferenceparameterguaranteesthatafunction'simplementationdoesnotchangethevalueoftheparameter.Itmaybeusedwheneverthefunction'simplementationdoesnoteventrytochangeaparameter(andusuallywhentheparametermightbealargedatatyperatherthansomethingsmalllikeanint).Forexample:doublelength(constPoint&p)//Postcondition:Thereturnvalueisthedistanceofpfromtheorigin.{returnsqrt(p.get_x()*p.get_x()+p.get_y()*p.get_y());}2.8.xshouldbeavalueparameterifyoudonotwantthechangestochangetheactualargument.xshouldbeareferenceparameterifyoudowantthechangestochangetheactualargument.xcouldneverbeaconstreferenceparameterinthisexample(sincethebodyofthefunctionischangingx).2.9.Useaconstreferenceparameterwhenthefunction'simplementationdoesnotevenattempttochangethevalueoftheparameter.2.10.Useareferenceparameterwhenthefunction'simplementationdoeschangethevalueofaparameterandyouwantthechangetoaltertheactualargument.2.11.Thisisabitofatrickquestion,andI'mnotsurethatIwouldaskitonanexam.Thetrickistorealizethateventheconstmemberfunctioncanalterx.size(althoughitcannotalterthesizemembervariableoftheobjectthatactivatestheconstfunction).x=y;Legalinallthreeplaces.x.size=y.size;Notlegalinmainprogram,butlegalinamemberfunctionorafriendfunction.x.size=3;Notlegalinmainprogram,butlegalinamemberfunctionorafriendfunction.x.h(42);Legalinallthreeplaces.2.12.foofoo::operator+(constfoo&f1,constfoo&f2);Theargumentnamesf1andf2areunimportant.Usuallyf1andf2areconstreferenceparameters,buttheremaybesituationswherethatisnottrue.Thefunctionmayalsoneedtobeafriendfunction(ifitneedsaccesstothefooprivatemembers).2.13.Theoperator+mustbeafriendoftheclass.2.14.Youareimplementingaclassandyouwanttowriteanon-memberfunctionthatneedsaccesstotheclass'sprivatemembers.MultipleChoiceQuestions:2.1D2.6C2.11D2.2D2.7A2.3D2.8D2.4C2.9C

Page 5

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 5 preview image

Loading page image...

2.5B2.10DChapter3:SolutionstoSampleExamQuestionsShortAnswerQuestions3.1.Thevalue_typeisdefinedatthetopofthebagclassdefinition:classbag{typedefintvalue_type;...Itisbettertousethevalue_typetypedef(ratherthanjustusinganint)becauseitmakesitwriteanewbagclasswithadifferentkindofiteminthebags.3.2.Youneedavariabletokeeptrackofhowmuchofthepartially-filledarrayiscurrentlybeingused.3.3.Thereisonlyonecopyofthestaticmemberconstantfortheentireclass.Thisisdifferentthanordinarymembervariableswhereeachobjecthasit'sowncopyofthemembervariables.3.4.Thesize_tvariableicanneverholdanegativevalue,soanerroroccurswhen--iisexecutedwithiequaltozero.Atypicalerroristhatiwillactuallybesettothebiggestunsignedint.3.5.Notethatthecorrectloopmustrunibackward:for(i=99;i>=51;--i)data[i]=data[i-1];data[50]=42;3.6.Notethatthecorrectloopmustruniforward:for(i=51;i<=99;++i)data[i-1]=data[i];MultipleChoiceQuestions:3.1B3.6B3.11D3.2A3.7C3.12D3.3A3.8D3.13D3.4B3.9E3.14A3.5B3.10B3.15DChapter4:SolutionstoSampleExamQuestionsShortAnswerQuestions4.1.inti;p=newint[100];for(i=0;i<100;i++)p[i]=i;delete[]p;4.2.Abad_allocexceptionisthrown.

Page 6

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 6 preview image

Loading page image...

Note:InolderversionsofC++,afunctioncalledthenew_handlerwascalled.Normally,thenew_handlerthenprintsanerrormessageandhaltstheprogram.4.3.p1pointstoi(containing42)andp2pointstok(containing80).--------i|42|k|80|--------^^||--|----|--p1|.|p2|.|----------4.4.Thepointersstillpointtothesamevariables,butbothvariablesnowcontain80.--------i|80|k|80|--------^^||--|----|--p1|.|p2|.|----------4.5.Bothp1andp2nowpointtok:--------i|42|k|80|--------^^____________||/|---/----|-p1|.|p2|.|----------4.6.Theparameterisanarrayofdoublenumbers.Thefunction'simplementationdoesnotchangeanyvaluesinthearray.4.7.Theparameterpisaconstantpointer.Withinfoo,theinteger*pcannotbechanged.However,pitselfcanbechanged(makingitpointtoanotherinteger).4.8.Fortwobagsxandyandthestatementx=y,theautomaticassignmentoperatorwillsimplycopythemembervariablesfromytox.Sowewillendupwithbothx.dataandy.datapointingtothesamedynamicarray.4.9.Theapproachworkscorrectly,butitisslowifweaddmanyitemsaftertheinitialcapacityisreached.Theslownesscomesfromthefactthateachtimeweaddanewitem,anew(slightlylarger)dynamic

Page 7

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 7 preview image

Loading page image...

arrayisallocated,theitemsarecopiedfromtheoldarraytothenewarray,andtheoldarrayisreturnedtotheheap.Abettersolutionmightincreasethesizebyatleast50%,asshownhere:resize(used*1.5+1);4.10.voidbag::triple_capacity(){Item*new_array=newItem[capacity*3];size_ti;for(i=0;i<used;i++)new_array[i]=data[i];delete[]data;data=new_array;capacity=capacity*3;}4.11operator*4.12voidprintem(constpolynomial&amp;p){inti;for(i=1;i&lt;=10;++i)cout&lt;&lt;p.eval(double(i));}voidzapbig(polynomial&amp;p){p.assign_coef(0.0,p.degree());}4.13The[0]elementhasthevalue3.0.The[2]elementhasthevalue2.1.The[4]elementhasthevalue4.1.Theotherelementsarezero,andthecurrentdegreeis4.4.14Thereareseveralpossibleanswers,butthesimplestis:p.assign_coef(0.09,4);4.15doubleslope(constpolynomial&amp;p,doublex){returnp.derivative().eval(x);}MultipleChoiceQuestions:4.1D4.6C4.11B4.16C4.21D4.2D4.7C4.12A4.17C4.22C4.3A4.8A4.13D4.18D4.4D4.9A4.14B4.19A4.5C4.10Yes4.15B4.20CChapter5:SolutionstoSampleExamQuestionsShortAnswerQuestions5.1.head_ptr=newnode(entry,head_ptr);

Page 8

Data Structures and Other Objects Using C++ 4th Edition Solution Manual - Page 8 preview image

Loading page image...

5.2.Declareanode*variablecalledtempandmakeitequaltop-&gt;link();Changep-&gt;link()topointtothenextnode(temp->link()).Thendeletetemp.5.3.node*cursor;for(cursor=head_ptr;cursor!=NULL;cursor=cursor-&gt;link())cout&lt;&lt;cursor-&gt;data()&lt;&lt;endl;5.4.locate_ptr=locate_ptr-&gt;link();5.5.size_tcount_42s(constnode*head_ptr){size_tanswer=0;constnode*cursor;for(cursor=head_ptr;cursor!=NULL;cursor=cursor-&gt;link())if(cursor-&gt;data()==42)answer++;returnanswer;}5.6.boolhas_42(constnode*head_ptr){constnode*cursor;for(cursor=head_ptr;cursor!=NULL;cursor=cursor-&gt;link())if(cursor-&gt;data()==42)returntrue;returnfalse;}5.7.boolall_42s(constnode*head_ptr){constnode*cursor;for(cursor=head_ptr;cursor!=NULL;cursor=cursor-&gt;link())if(cursor-&gt;data()!=42)returnfalse;returntrue;}5.8.intsum(constnode*head_ptr){constnode*cursor;intanswer=0;for(cursor=head_ptr;cursor!=NULL;cursor=cursor-&gt;link())answer+=cursor-&gt;data();returnanswer;}5.9.intproduct(constnode*head_ptr){constnode*cursor;intanswer=1;
Preview Mode

This document has 26 pages. Sign in to access the full document!

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Document Details

Related Documents

View all