• 3.97 MB
  • 2022-04-22 11:48:16 发布

C How to Program) (H.M.Deitel 著) 清华大学出版社 课后答案

  • 676页
  • 当前文档由用户上传发布,收益归属用户
  1. 1、本文档共5页,可阅读全部内容。
  2. 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
  3. 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
  4. 文档侵权举报电话:19940600175。
'课后答案网,用心为你服务!大学答案---中学答案---考研答案---考试答案最全最多的课后习题参考答案,尽在课后答案网(www.khdaw.com)!Khdaw团队一直秉承用心为大家服务的宗旨,以关注学生的学习生活为出发点,旨在为广大学生朋友的自主学习提供一个分享和交流的平台。爱校园(www.aixiaoyuan.com)课后答案网(www.khdaw.com)淘答案(www.taodaan.com) 课后答案网www.khdaw.comInstructor’sManualforCHowtoProgram,4/eDeitel&Deitel©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comContents1IntroductiontoComputers,theInternetandtheWorldWideWeb12IntroductiontoCProgramming53StructuredProgramDevelopmentinC194CProgramControl555CFunctions976CArrays1697Pointers2338CCharactersandStrings2839CFormattedInput/Output31910Structures,Unions,BitManipulationsandEnumerations33311CFileProcessing35312DataStructures375 课后答案网www.khdaw.comII13ThePreprocessor44114OtherCTopics44715C++asa“BetterC”45716C++ClassesandDataAbstraction46317C++Classes:PartII48518C++OperatorOverloading49319C++Inheritance49920C++VirtualFunctionsandPolymorphism51121C++StreamInput/Output51922C++Templates53723C++ExceptionHandling:Solution54324IntroductiontoJavaApplicationsandApplets54725BeyondC&C++:Operators,Methods&ArraysinJava55726JavaObject-BasedProgramming58527JavaObject-OrientedProgramming60328JavaGraphicsandJava2D61729JavaGraphicalUserInterfaceComponents63330JavaMultimedia:Images,Animation,andAudio661 课后答案网www.khdaw.com1IntroductiontoComputers,theInternetandtheWorldWideWeb:SolutionsSOLUTIONS1.3Categorizeeachofthefollowingitemsaseitherhardwareorsoftware:a)CPUANS:hardware.b)CcompilerANS:software.c)ALUANS:hardware.d)CpreprocessorANS:software.e)inputunitANS:hardware.f)awordprocessorprogramANS:software.1.4Whymightyouwanttowriteaprograminamachine-independentlanguageinsteadofamachine-dependentlanguage?Whymightamachine-dependentlanguagebemoreappropriateforwritingcertaintypesofprograms?ANS:Machineindependentlanguagesareusefulforwritingprogramstobeexecutedonmultiplecomputerplatforms.Machinedependentlanguagesareappropriateforwritingprogramstobeexecutedonasingleplatform.Machinedependentlanguagestendtoexploittheefficienciesofaparticularmachine.1.5Translatorprogramssuchasassemblersandcompilersconvertprogramsfromonelanguage(referredtoasthesourcelan-guage)toanotherlanguage(referredtoastheobjectlanguage).Determinewhichofthefollowingstatementsaretrueandwhicharefalse:a)Acompilertranslateshigh-levellanguageprogramsintoobjectlanguage.ANS:True.b)Anassemblertranslatessourcelanguageprogramsintomachinelanguageprograms.ANS:True.c)Acompilerconvertssourcelanguageprogramsintoobjectlanguageprograms.ANS:False.d)High-levellanguagesaregenerallymachine-dependent.ANS:False.e)Amachinelanguageprogramrequirestranslationbeforetheprogramcanberunonacomputer.ANS:False.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com2IntroductiontoComputers,theInternetandtheWorldWideWeb:SolutionsChapter11.6Fillintheblanksineachofthefollowingstatements:a)Devicesfromwhichusersaccesstimesharingcomputersystemsareusuallycalled.ANS:terminals.b)Acomputerprogramthatconvertsassemblylanguageprogramstomachinelanguageprogramsiscalled.ANS:anassembler.c)Thelogicalunitofthecomputerthatreceivesinformationfromoutsidethecomputerforusebythecomputeriscalled.ANS:Theinputunit.d)Theprocessofinstructingthecomputertosolvespecificproblemsiscalled.ANS:computerprogramming.e)WhattypeofcomputerlanguageusesEnglish-likeabbreviationsformachinelanguageinstructions?.ANS:ahigh-levellanguage.f)Whichlogicalunitofthecomputersendsinformationthathasalreadybeenprocessedbythecomputertovariousde-vicessothattheinformationmaybeusedoutsidethecomputer?.ANS:Theoutputunit.g)Thegeneralnameforaprogramthatconvertsprogramswritteninacertaincomputerlanguageintomachinelanguageis.ANS:compiler.h)Whichlogicalunitofthecomputerretainsinformation?.ANS:memoryunitandsecondarystorageunit.i)Whichlogicalunitofthecomputerperformscalculations?.ANS:arithmeticandlogicalunit.j)Whichlogicalunitofthecomputermakeslogicaldecisions?.ANS:arithmeticandlogicalunitk)Thecommonlyusedabbreviationforthecomputer"scontrolunitis.ANS:CPU.l)Thelevelofcomputerlanguagemostconvenienttotheprogrammerforwritingprogramsquicklyandeasilyis.ANS:high-levellanguage.m)Theonlylanguagethatacomputercandirectlyunderstandiscalledthatcomputer"s.ANS:machinelanguage.n)Whichlogicalunitofthecomputercoordinatestheactivitiesofalltheotherlogicalunits?.ANS:centralprocessingunit.1.7Statewhethereachofthefollowingistrueorfalse.Iffalse,explainyouranswer.a)Machinelanguagesaregenerallymachinedependent.ANS:True.Machinelanguagesarecloselyrelatedtothehardwareofaparticularmachine.b)Timesharingtrulyrunsseveraluserssimultaneouslyonacomputer.ANS:False.TimesharingsystemssplitCPUtimeamongstseveraluserssothattheusersappeartobeoperatingsimulta-neouslyc)Likeotherhigh-levellanguages,Cisgenerallyconsideredtobemachineindependent.ANS:True.Cprogramscanbewrittenonmostmachines,andwithsomecare,Cprogramscanbewrittenononemachineandrunonmanymachineswithfewchangesornochanges.1.8Discussthemeaningofeachofthefollowingnames:a)stdinANS:Thisreferstothestandardinputdevice.Thestandardinputdeviceisnormallyconnectedtothekeyboardb)stdoutANS:Thisreferstothestandardoutputdevice.Thestandardoutputdeviceisnormallyconnectedtothecomputerscreen.c)stderrANS:Thisreferstothestandarderrordevice.Errormessagesarenormallysenttothisdevicewhichistypicallyconnectedtothecomputerscreen.1.9Whyissomuchattentiontodayfocusedonobject-orientedprogrammingingeneralandC++inparticular?ANS:Object-orientedprogrammingenablestheprogrammertobuildreusablesoftwarecomponentsthatmodelitemsintherealworld.Buildingsoftwarequickly,correctly,andeconomicallyhasbeenanelusivegoalinthesoftwareindustry.Themodular,object-orienteddesignandimplementationapproachhasbeenfoundtoincreaseproductivity10to100timesoverconventionalprogramminglanguageswhilereducingdevelopmenttime,errors,andcost.C++isusedforobject-ori-entedprogrammingbecauseitisasupersetoftheCprogramminglanguageandCiswidelyused.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter1IntroductiontoComputers,theInternetandtheWorldWideWeb:Solutions31.10Whichprogramminglanguageisbestdescribedbyeachofthefollowing?a)DevelopedbyIBMforscientificandengineeringapplications.ANS:FORTRANb)Developedspecificallyforbusinessapplications.ANS:COBOLc)Developedforteachingstructuredprogramming.ANS:Pascald)Namedaftertheworld’sfirstcomputerprogrammer.ANS:Adae)Developedtofamiliarizenoviceswithprogrammingtechniques.ANS:BASICf)Specificallydevelopedtohelpprogrammersmigrateto.NET.ANS:C#g)KnownasthedevelopmentlanguageofUNIX.ANS:Ch)Formedprimarilybyaddingobject-orientedprogrammingtoC.ANS:C++i)SucceededinitiallybecauseofitsabilitytocreateWebpageswithdynamiccontent.ANS:Java©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com4IntroductiontoComputers,theInternetandtheWorldWideWeb:SolutionsChapter1©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com2IntroductiontoCProgramming:SolutionsSOLUTIONS:2.7Identifyandcorrecttheerrorsineachofthefollowingstatements(Note:theremaybemorethanoneerrorperstatement):a)scanf("d",value);ANS:scanf(“%d”,&value);b)printf("Theproductof%dand%dis%d"n,x,y);ANS:printf(“Theproductof%dand%dis%dn”,x,y,z);c)firstNumber+secondNumber=sumOfNumbersANS:sumOfNumbers=firstNumber+secondNumber;d)if(number=>largest)largest==number;ANS:if(number>=largerst)largest=number;e)*/Programtodeterminethelargestofthreeintegers/*ANS:/*Programtodeterminethelargestofthreeintegers*/f)Scanf("%d",anInteger);ANS:scanf(“%d”,&anInteger);g)printf("Remainderof%ddividedby%disn",x,y,x%y);ANS:printf(“Remainderof%fdividedby%dis%dn”,x,y,x%y);h)if(x=y);printf(%disequalto%dn",x,y);ANS:if(x==y)printf(“%disequalto%dn”,x,y);i)print("Thesumis%dn,"x+y);ANS:printf(“Thesumis%dn”,x+y);j)Printf("Thevalueyouenteredis:%dn,&value);ANS:printf(“Thevalueyouenteredis:%dn”,value);2.8Fillintheblanksineachofthefollowing:a)areusedtodocumentaprogramandimproveitsreadability.ANS:comments.b)Thefunctionusedtodisplayinformationonthescreenis.ANS:printf.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com6IntroductiontoCProgramming:SolutionsChapter2c)ACstatementthatmakesadecisionis.ANS:if.d)Calculationsarenormallyperformedbystatements.ANS:assignment.e)Thefunctioninputsvaluesfromthekeyboard.ANS:scanf.2.9WriteasingleCstatementorlinethataccomplisheseachofthefollowing:a)Printthemessage“Entertwonumbers.”ANS:printf(“Entertwonumbersn”);b)Assigntheproductofvariablesbandctovariablea.ANS:a=b*c;c)Statethataprogramperformsasamplepayrollcalculation(i.e.,usetextthathelpstodocumentaprogram).ANS:/*Samplepayrollcalculationprogram*/d)Inputthreeintegervaluesfromthekeyboardandplacethesevaluesinintegervariablesa,bandc.ANS:scanf(“%d%d%d”,&a,&b,&c);2.10Statewhichofthefollowingaretrueandwhicharefalse.Iffalse,explainyouranswer.a)Coperatorsareevaluatedfromlefttoright.ANS:False.Someoperatorsareevaluatedlefttorightandothersareevaluatedfromrighttoleftdependingontheirasso-ciativity(seeAppendixC).b)Thefollowingareallvalidvariablenames:_under_bar_,m928134,t5,j7,her_sales,his_account_total,a,b,c,z,z2.ANS:True.c)Thestatementprintf("a=5;");isatypicalexampleofanassignmentstatement.ANS:False.Thestatementprintsa=5;onthescreen.d)Avalidarithmeticexpressioncontainingnoparenthesesisevaluatedfromlefttoright.ANS:False.Multiplication,division,andmodulusareallevaluatedfirstfromlefttoright,thenadditionandsubtractionareevaluatedfromlefttoright.e)Thefollowingareallinvalidvariablenames:3g,87,67h2,h22,2h.ANS:False.Thosebeginningwithanumberareinvalid.2.11Fillintheblanksineachofthefollowing:a)Whatarithmeticoperationsareonthesamelevelofprecedenceasmultiplication?.ANS:division,modulus.b)Whenparenthesesarenested,whichsetofparenthesesisevaluatedfirstinanarithmeticexpression?.ANS:Theinnermostpairofparenthesis.c)Alocationinthecomputer"smemorythatmaycontaindifferentvaluesatvarioustimesthroughouttheexecutionofaprogramiscalleda.ANS:variable.2.12What,ifanything,printswheneachofthefollowingCstatementsisperformed?Ifnothingprints,thenanswer“nothing.”Assumex=2andy=3.a)printf("%d",x);ANS:2b)printf("%d",x+x);ANS:4c)printf("x=");ANS:x=d)printf("x=%d",x);ANS:x=2e)printf("%d=%d",x+y,y+x);ANS:5=5f)z=x+y;ANS:Nothing.Valueofx+yisassignedtoz.g)scanf("%d%d",&x,&y);ANS:Nothing.Twointegervaluesarereadintothelocationofxandthelocationofy.h)/*printf("x+y=%d",x+y);*/ANS:Nothing.Thisisacomment.i)printf("n");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter2IntroductiontoCProgramming:Solutions7ANS:Anewlinecharacterisprinted,andthecursorispositionedatthebeginningofthenextlineonthescreen.2.13Which,ifany,ofthefollowingCstatementscontainvariablesinvolvedindestructiveread-in?a)scanf("%d%d%d%d%d",&b,&c,&d,&e,&f);b)p=i+j+k+7;c)printf("Destructiveread-in");d)printf("a=5");ANS:(a).2.14Giventheequationy=ax3+7,whichofthefollowing,ifany,arecorrectCstatementsforthisequation?a)y=a*x*x*x+7;b)y=a*x*x*(x+7);c)y=(a*x)*x*(x+7);d)y=(a*x)*x*x+7;e)y=a*(x*x*x)+7;f)y=a*x*(x*x+7);ANS:(a),(d),and(e).2.15StatetheorderofevaluationoftheoperatorsineachofthefollowingCstatementsandshowthevalueofxaftereachstate-mentisperformed.a)x=7+3*6/2-1;ANS:*isfirst,/issecond,+isthird,and-isfourth.Valueofxis15.b)x=2%2+2*2-2/2;ANS:%isfirst,*issecond,/isthird,+isfourth,-isfifth.Valueofxis3.c)x=(3*9*(3+(9*3/(3))));ANS:564231.Valueofxis338.2.16Writeaprogramthataskstheusertoentertwonumbers,obtainsthetwonumbersfromtheuserandprintsthesum,product,difference,quotientandremainderofthetwonumbers.ANS:1/*Exercise2.16Solution*/2#include34intmain()5{6intx;/*definefirstnumber*/7inty;/*definesecondnumber*/89printf("Entertwonumbers:");/*promptuser*/10scanf("%d%d",&x,&y);/*readvaluesfromkeyboard*/1112/*outputresults*/13printf("Thesumis%dn",x+y);14printf("Theproductis%dn",x*y);15printf("Thedifferenceis%dn",x-y);16printf("Thequotientis%dn",x/y);17printf("Themodulusis%dn",x%y);1819return0;/*indicatesuccessfultermination*/2021}/*endmain*/Entertwonumbers:205Thesumis25Theproductis100Thedifferenceis15Thequotientis4Themodulusis0©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com8IntroductiontoCProgramming:SolutionsChapter22.17Writeaprogramthatprintsthenumbers1to4onthesameline.Writetheprogramusingthefollowingmethods.a)Usingoneprintfstatementwithnoconversionspecifiers.b)Usingoneprintfstatementwithfourconversionspecifiers.c)Usingfourprintfstatements.ANS:1/*Exercise2.17Solution*/2#include34intmain()5{6printf("1234nn");/*parta*/78printf("%d%d%d%dnn",1,2,3,4);/*partb*/910printf("1");/*partc*/11printf("2");12printf("3");13printf("4n");1415return0;/*indicatessuccessfultermination*/1617}/*endmain*/1234123412342.18Writeaprogramthataskstheusertoentertwointegers,obtainsthenumbersfromtheuser,thenprintsthelargernumberfollowedbythewords“islarger.”Ifthenumbersareequal,printthemessage“Thesenumbersareequal.”Useonlythesingle-selectionformoftheifstatementyoulearnedinthischapter.ANS:1/*Exercise2.18Solution*/2#include34intmain()5{6intx;/*definefirstnumber*/7inty;/*definesecondnumber*/89printf("Entertwonumbers:");/*prompt*/10scanf("%d%d",&x,&y);/*readtwointegers*/1112/*comparethetwonumbers*/13if(x>y){14printf("%dislargern",x);15}/*endif*/1617if(x34intmain()5{6inta;/*definefirstinteger*/7intb;/*definesecondinteger*/8intc;/*definethirdinteger*/9intsmallest;/*smallestinteger*/10intlargest;/*largestinteger*/1112printf("Inputthreedifferentintegers:");/*promptuser*/13scanf("%d%d%d",&a,&b,&c);/*readthreeintegers*/1415/*outputsum,averageandproductofthethreeintegers*/16printf("Sumis%dn",a+b+c);17printf("Averageis%dn",(a+b+c)/3);18printf("Productis%dn",a*b*c);1920smallest=a;/*assumefirstnumberisthesmallest*/2122if(blargest){/*isblarger?*/35largest=b;36}/*endif*/3738if(c>largest){/*isclarger?*/39largest=c;40}/*endif*/4142printf("Largestis%dn",largest);4344return0;/*indicatesuccessfultermination*/4546}/*endmain*/2.20Writeaprogramthatreadsintheradiusofacircleandprintsthecircle’sdiameter,circumferenceandarea.Usetheconstantvalue3.14159forp.Performeachofthesecalculationsinsidetheprintfstatement(s)andusetheconversionspecifier%f.[Note:Inthischapter,wehavediscussedonlyintegerconstantsandvariables.InChapter3wewilldiscussfloating-pointnumbers,i.e.,valuesthatcanhavedecimalpoints.]ANS:1/*Exercise2.20Solution*/2#include34intmain()5{6intradius;/*circleradius*/78printf("Inputthecircleradius:");/*promptuser*/9scanf("%d",&radius);/*readintegerradius*/1011/*calculateandoutputdiameter,circumferenceandarea*/12printf("nThediameteris%dn",2*radius);13printf("Thecircumferenceis%fn",2*3.14159*radius);14printf("Theareais%fn",3.14159*radius*radius);1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/Inputthecircleradius:9Thediameteris18Thecircumferenceis56.548620Theareais254.468790©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter2IntroductiontoCProgramming:Solutions112.21Writeaprogramthatprintsabox,anoval,anarrowandadiamondasfollows:***********************************************************************************ANS:1/*Exercise2.21Solution*/2#include34intmain()5{6printf("**************n");7printf("*********n");8printf("***********n");9printf("*******n");10printf("*******n");11printf("*******n");12printf("*******n");13printf("*******n");14printf("**************n");1516return0;/*indicatessuccessfultermination*/1718}/*endmain*/2.22Whatdoesthefollowingcodeprint?printf("*n**n***n****n*****n");ANS:***************2.23Writeaprogramthatreadsinfiveintegersandthendeterminesandprintsthelargestandthesmallestintegersinthegroup.Useonlytheprogrammingtechniquesyouhavelearnedinthischapter.ANS:1/*Exercise2.23Solution*/2#include34intmain()5{6intlargest;/*largestinteger*/7intsmallest;/*smallestinteger*/8intint1;/*defineint1foruserinput*/9intint2;/*defineint2foruserinput*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com12IntroductiontoCProgramming:SolutionsChapter210intint3;/*defineint3foruserinput*/11inttemp;/*temporaryintegerforswapping*/1213printf("Input5integers:");/*promptuserandread5ints*/14scanf("%d%d%d%d%d",&largest,&smallest,&int1,&int2,&int3);1516if(smallest>largest){/*makecomparisons*/17temp=largest;18largest=smallest;19smallest=temp;20}/*endif*/2122if(int1>largest){23largest=int1;24}/*endif*/2526if(int1largest){31largest=int2;32}/*endif*/3334if(int2largest){39largest=int3;40}/*endif*/4142if(int334intmain()5{6intinteger;/*integerinputbyuser*/78printf("Inputaninteger:");/*prompt*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter2IntroductiontoCProgramming:Solutions139scanf("%d",&integer);/*readinteger*/1011/*testifintegeriseven*/12if(integer%2==0){13printf("%disanevenintegern",integer);14}/*endif*/1516/*testifintegerisodd*/17if(integer%2!=0){18printf("%disanoddintegern",integer);19}/*endif*/2021return0;/*indicatesuccessfultermination*/2223}/*endmain*/Inputaninteger:7878isanevenintegerInputaninteger:7979isanoddinteger2.25Printyourinitialsinblocklettersdownthepage.Constructeachblockletteroutoftheletteritrepresentsasshownbelow.PPPPPPPPPPPPPPPPPJJJJJJJJJJJJDDDDDDDDDDDDDDDDDDDDANS:1/*Exercise2.25Solution*/2#include34intmain()5{6printf("PPPPPPPPPn");7printf("PPn");8printf("PPn");9printf("PPn");10printf("PPn");11printf("n");12printf("JJn");13printf("Jn");14printf("Jn");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com14IntroductiontoCProgramming:SolutionsChapter215printf("Jn");16printf("JJJJJJJn");17printf("n");18printf("DDDDDDDDDn");19printf("DDn");20printf("DDn");21printf("DDn");22printf("DDDDDn");2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/2.26Writeaprogramthatreadsintwointegersanddeterminesandprintsifthefirstisamultipleofthesecond.[Hint:Usetheremainderoperator.]ANS:1/*Exercise2.26Solution*/2#include34intmain()5{6intinteger1;/*firstinteger*/7intinteger2;/*secondinteger*/89printf("Inputtwointegers:");/*promptuser*/10scanf("%d%d",&integer1,&integer2);/*readtwointegers*/1112/*useremainderoperator*/13if(integer1%integer2==0){14printf("%disamultipleof%d",integer1,integer2);15printf("byafactorof%dn",integer1/integer2);16}/*endif*/1718if(integer1%integer2!=0){19printf("%disnotamultipleof%dn",integer1,integer2);20}/*endif*/2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/Inputtwointegers:881188isamultipleof11byafactorof8Inputtwointegers:7775777isnotamultipleof5©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter2IntroductiontoCProgramming:Solutions152.27Displaythefollowingcheckerboardpatternwitheightprintfstatementsandthendisplaythesamepatternwithasfewprintfstatementsaspossible.****************************************************************ANS:1/*Exercise2.27Solution*/2#include34intmain()5{6printf("Witheightprintf()statements:n");78printf("********n");9printf("********n");10printf("********n");11printf("********n");12printf("********n");13printf("********n");14printf("********n");15printf("********n");1617printf("nNowwithoneprintf()statement:n");1819printf("********n********n"20"********n********n"21"********n********n"22"********n********n");2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/Witheightprintf()statements:****************************************************************Nowwithoneprintf()statement:****************************************************************©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com16IntroductiontoCProgramming:SolutionsChapter22.28Distinguishbetweenthetermsfatalerrorandnon-fatalerror.Whymightyouprefertoexperienceafatalerrorratherthananon-fatalerror?ANS:Afatalerrorcausestheprogramtoterminateprematurely.Anonfatalerroroccurswhenthelogicoftheprogramisincorrect,andtheprogramdoesnotworkproperly.Afatalerrorispreferredfordebuggingpurposes.Afatalerrorimme-diatelyletsyouknowthereisaproblemwiththeprogram,whereasanonfatalerrorcanbesubtleandpossiblygounde-tected.2.29Here’sapeekahead.Inthischapteryoulearnedaboutintegersandthetypeint.Ccanalsorepresentuppercaseletters,lowercaselettersandaconsiderablevarietyofspecialsymbols.Cusessmallintegersinternallytorepresenteachdifferentcharacter.Thesetofcharactersacomputerusesandthecorrespondingintegerrepresentationsforthosecharactersiscalledthatcomputer’scharacterset.YoucanprinttheintegerequivalentofuppercaseAforexample,byexecutingthestatementprintf("%d","A");WriteaCprogramthatprintstheintegerequivalentsofsomeuppercaseletters,lowercaseletters,digitsandspecialsymbols.Asaminimum,determinetheintegerequivalentsofthefollowing:ABCabc012$*+/andtheblankcharacter.ANS:1/*Exercise2.29Solution*/2#include34intmain()5{6charintEquivalent;/*letter,digitorcharacter*/78printf("Inputaletter,digit,orcharacter:");/*prompt*/9scanf("%c",&intEquivalent);/*readuserinput*/1011printf("%c"sintegerequivalentis%dn",intEquivalent,12intEquivalent);1314return0;/*indicatesuccessfultermination*/1516}/*endmain*/Inputaletter,digit,orcharacter:%%"sintegerequivalentis37Inputaletter,digit,orcharacter:yy"sintegerequivalentis121Inputaletter,digit,orcharacter:00"sintegerequivalentis482.30Writeaprogramthatinputsonefive-digitnumber,separatesthenumberintoitsindividualdigitsandprintsthedigitssep-aratedfromoneanotherbythreespaceseach.[Hint:Usecombinationsofintegerdivisionandtheremainderoperation.]Forexam-ple,iftheusertypesin42139,theprogramshouldprint42139©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter2IntroductiontoCProgramming:Solutions17ANS:1/*Exercise2.30Solution*/2#include34intmain()5{6intnumber;/*numberinputbyuser*/7inttemp1;/*firsttemporaryinteger*/8inttemp2;/*secondtemporaryinteger*/910printf("Enterafive-digitnumber:");/*promptuser*/11scanf("%d",&number);/*readinteger*/1213printf("%d",number/10000);/*printleft-mostdigit*/14temp2=number%10000;1516printf("%d",temp2/1000);17temp1=temp2%1000;1819printf("%d",temp1/100);20temp2=temp1%100;2122printf("%d",temp2/10);23temp1=temp2%10;2425printf("%dn",temp1);/*printright-mostdigit*/2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/Enterafive-digitnumber:23456234562.31Usingonlythetechniquesyoulearnedinthischapter,writeaprogramthatcalculatesthesquaresandcubesofthenumbersfrom0to10andusestabstoprintthefollowingtableofvalues:numbersquarecube000111248392741664525125636216749343864512981729101001000ANS:1/*Exercise2.31Solution*/2#include34intmain()5{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com18IntroductiontoCProgramming:SolutionsChapter26intcount=0;/*initializecounttozero*/78/*calculatethesquareandcubeforthenumbers0to10*/9printf("nnumbertsquaretcuben");10printf("%dt%dt%dn",count,count*count,11count*count*count);1213count=count+1;/*incrementcountby1*/14printf("%dt%dt%dn",count,count*count,15count*count*count);1617count=count+1;18printf("%dt%dt%dn",count,count*count,19count*count*count);2021count=count+1;22printf("%dt%dt%dn",count,count*count,23count*count*count);2425count=count+1;26printf("%dt%dt%dn",count,count*count,27count*count*count);2829count=count+1;30printf("%dt%dt%dn",count,count*count,31count*count*count);3233count=count+1;34printf("%dt%dt%dn",count,count*count,35count*count*count);3637count=count+1;38printf("%dt%dt%dn",count,count*count,39count*count*count);4041count=count+1;42printf("%dt%dt%dn",count,count*count,43count*count*count);4445count=count+1;46printf("%dt%dt%dn",count,count*count,47count*count*count);4849count=count+1;50printf("%dt%dt%dn",count,count*count,51count*count*count);5253return0;/*indicatesuccessfultermination*/5455}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com3StructuredProgramDevelopmentinC:SolutionsSOLUTIONS3.11Identifyandcorrecttheerrorsineachofthefollowing[Note:Theremaybemorethanoneerrorineachpieceofcode]:a)if(age>=65);printf("Ageisgreaterthanorequalto65n");elseprintf("Ageislessthan65n");ANS:if(age>=65)/*;removed*/printf(“Ageisgreaterthanorequalto65n”);elseprintf(“Ageislessthan65n”);b)intx=1,total;while(x<=10){total+=x;++x;}ANS:intx=1,total=0;while(x<=10){total+=x;++x;}c)While(x<=100)total+=x;++x;ANS:while(x<=100){total+=x;++x;}d)while(y>0){printf("%dn",y);++y;}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com20StructuredProgramDevelopmentinC:SolutionsChapter3ANS:while(y>0){printf(“%dn”,y);--y;}3.12Fillintheblanksineachofthefollowing:a)Thesolutiontoanyprobleminvolvesperformingaseriesofactionsinaspecific.ANS:order.b)Asynonymforprocedureis.ANS:algorithmc)Avariablethataccumulatesthesumofseveralnumbersisa.ANS:total.d)Theprocessofsettingcertainvariablestospecificvaluesatthebeginningofaprogramiscalled.ANS:initialization.e)Aspecialvalueusedtoindicate“endofdataentry”iscalleda,a,aoravalue.ANS:sentinelvalue,dummyvalue,signalvalue,flagvalue.f)Aisagraphicalrepresentationofanalgorithm.ANS:flowchart.g)Inaflowchart,theorderinwhichthestepsshouldbeperformedisindicatedbysymbols.ANS:arrow(flowline).h)Theterminationsymbolindicatestheandofeveryalgorithm.ANS:beginning,end.i)Rectanglesymbolscorrespondtocalculationsthatarenormallyperformedbystatementsandinput/outputoperationsthatarenormallyperformedbycallstotheandstandardlibraryfunctions.ANS:assignment,printf,scanf.j)Theitemwritteninsideadecisionsymboliscalleda.ANS:condition.3.13Whatdoesthefollowingprogramprint?1#include23intmain()4{5intx=1,total=0,y;67while(x<=10){8y=x*x;9printf("%dn",y);10total+=y;11++x;12}1314printf("Totalis%dn",total);1516return0;17}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions21149162536496481100Totalis3853.14Writeasinglepseudocodestatementthatindicateseachofthefollowing:a)Displaythemessage"Entertwonumbers".ANS:print“entertwonumbers”b)Assignthesumofvariablesx,y,andztovariablep.ANS:p=x+y+zc)Thefollowingconditionistobetestedinanif…elseselectionstatement:Thecurrentvalueofvariablemisgreaterthantwicethecurrentvalueofvariablev.ANS:ifmisgreaterthantwicevdothis...elsedothis...d)Obtainvaluesforvariabless,r,andtfromthekeyboard.ANS:inputs,inputr,inputt3.15Formulateapseudocodealgorithmforeachofthefollowing:a)Obtaintwonumbersfromthekeyboard,computethesumofthenumbersanddisplaytheresult.ANS:InputthefirstnumberInputthesecondnumberAddthetwonumbersOutputthesumb)Obtaintwonumbersfromthekeyboard,anddetermineanddisplaywhich(ifeither)isthelargerofthetwonumbers.ANS:InputthefirstnumberfromthekeyboardInputthesecondnumberfromthekeyboardIfthefirstnumberisgreaterthanthesecondnumberprintitElseifthesecondnumberisgreaterthanthefirstnumberprintitElseprintamessagestatingthatthenumbersareequalc)Obtainaseriesofpositivenumbersfromthekeyboard,anddetermineanddisplaythesumofthenumbers.Assumethattheusertypesthesentinelvalue-1toindicate“endofdataentry.”ANS:InputavaluefromthekeyboardWhiletheinputvalueisnotequalto-1addthenumbertotherunningtotalinputthenextnumberPrintthesum3.16Statewhichofthefollowingaretrueandwhicharefalse.Ifastatementisfalse,explainwhy.a)ExperiencehasshownthatthemostdifficultpartofsolvingaproblemonacomputerisproducingaworkingCpro-gram.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com22StructuredProgramDevelopmentinC:SolutionsChapter3ANS:False.Thealgorithmisthehardestofsolvingaproblem.b)Asentinelvaluemustbeavaluethatcannotbeconfusedwithalegitimatedatavalue.ANS:True.c)Flowlinesindicatetheactionstobeperformed.ANS:False.Flowlinesindicatetheorderinwhichstepsareperformed.d)Conditionswritteninsidedecisionsymbolsalwayscontainarithmeticoperators(i.e.,+,-,*,/,and%).ANS:False.Theynormallycontainconditionaloperators.e)Intop-down,stepwiserefinement,eachrefinementisacompleterepresentationofthealgorithm.ANS:True.ForExercises3.17to3.21,performeachofthesesteps:1.Readtheproblemstatement.2.Formulatethealgorithmusingpseudocodeandtop-down,stepwiserefinement.3.WriteaCprogram.4.Test,debug,andexecutetheCprogram.3.17Driversareconcernedwiththemileageobtainedbytheirautomobiles.Onedriverhaskepttrackofseveraltankfulsofgas-olinebyrecordingmilesdrivenandgallonsusedforeachtankful.Developaprogramthatwillinputthemilesdrivenandgallonsusedforeachtankful.Theprogramshouldcalculateanddisplaythemilespergallonobtainedforeachtankful.Afterprocessingallinputinformation,theprogramshouldcalculateandprintthecombinedmilespergallonobtainedforalltankfuls.Hereisasampleinput/outputdialog:.Enterthegallonsused(-1toend):12.8Enterthemilesdriven:287Themiles/gallonforthistankwas22.421875Enterthegallonsused(-1toend):10.3Enterthemilesdriven:200Themiles/gallonforthistankwas19.417475Enterthegallonsused(-1toend):5Enterthemilesdriven:120Themiles/gallonforthistankwas24.000000Enterthegallonsused(-1toend):-1Theoverallaveragemiles/gallonwas21.601423ANS:2)Top:Determinetheaveragemiles/gallonforeachtankofgas,andtheoverallmiles/gallonforanarbitrarynumberoftanksofgasFirstrefinement:InitializevariablesInputthegallonsusedandthemilesdriven,andcalculateandprintthemiles/gallonforeachtankofgas.Keeptrackofthetotalmilesandthetotalgallons.Calculateandprinttheoverallaveragemiles/gallon.Secondrefinement:InitializetotalGallonstozero.InitializetotalMilestozero.Inputthegallonsusedforthefirsttank.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions23Whilethesentinelvalue(-1)hasnotbeenenteredforthegallonsAddgallonstotherunningtotalintotalGallonsInputthemilesdrivenforthecurrenttankAddmilestotherunningtotalintotalMilesCalculateandprintthemiles/gallonInputthegallonsusedforthenexttankSettotalAveragetototalMilesdividedbytotalGallons.printtheaveragemiles/gallon3)1/*Exercise3.17Solution*/2#include34intmain()5{6doublegallons;/*gallonsusedforcurrenttank*/7doublemiles;/*milesdrivenforcurrenttank*/8doubletotalGallons=0.0;/*totalgallonsused*/9doubletotalMiles=0.0;/*totalmilesdriven*/10doubletotalAverage;/*averagemiles/gallon*/1112/*getgallonsusedforfirsttank*/13printf("Enterthegallonsused(-1toend):");14scanf("%lf",&gallons);1516/*loopuntilsentinelvaluereadfromuser*/17while(gallons!=-1.0){18totalGallons+=gallons;/*addcurrenttankgallonstototal*/1920printf("Enterthemilesdriven:");/*getmilesdriven*/21scanf("%lf",&miles);22totalMiles+=miles;/*addcurrenttankmilestototal*/2324/*displaymilespergallonforcurrenttank*/25printf("TheMiles/Gallonforthistankwas%fnn",26miles/gallons);2728/*getnexttank"sgallons*/29printf("Enterthegallonsused(-1toend):");30scanf("%lf",&gallons);31}/*endwhile*/3233/*calculateaveragemilespergallonoveralltanks*/34totalAverage=totalMiles/totalGallons;35printf("nTheoverallaverageMiles/Gallonwas%fn",totalAverage);3637return0;/*indicatesuccessfultermination*/3839}/*endmain*/3.18DevelopaCprogramthatwilldetermineifadepartmentstorecustomerhasexceededthecreditlimitonachargeaccount.Foreachcustomer,thefollowingfactsareavailable:1.Accountnumber2.Balanceatthebeginningofthemonth3.Totalofallitemschargedbythiscustomerthismonth4.Totalofallcreditsappliedtothiscustomer"saccountthismonth5.Allowedcreditlimit©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com24StructuredProgramDevelopmentinC:SolutionsChapter3Theprogramshouldinputeachofthesefacts,calculatethenewbalance(=beginningbalance+charges–credits),anddeter-mineifthenewbalanceexceedsthecustomer"screditlimit.Forthosecustomerswhosecreditlimitisexceeded,theprogramshoulddisplaythecustomer"saccountnumber,creditlimit,newbalanceandthemessage“Creditlimitexceeded.”Hereisasampleinput/outputdialog:Enteraccountnumber(-1toend):100Enterbeginningbalance:5394.78Entertotalcharges:1000.00Entertotalcredits:500.00Entercreditlimit:5500.00Account:100Creditlimit:5500.00Balance:5894.78CreditLimitExceeded.Enteraccountnumber(-1toend):200Enterbeginningbalance:1000.00Entertotalcharges:123.45Entertotalcredits:321.00Entercreditlimit:1500.00Enteraccountnumber(-1toend):300Enterbeginningbalance:500.00Entertotalcharges:274.73Entertotalcredits:100.00Entercreditlimit:800.00Enteraccountnumber(-1toend):-1ANS:2)Top:Determineifeachofanarbitrarynumberofdepartmentstorecustomershasexceededthecreditlimitonachargeaccount.Firstrefinement:Inputtheaccountnumber,beginningbalance,totalcharges,totalcredits,andcreditlimitforacustomer,calculatethecustomer’snewbalanceanddetermineifthebalanceexceedsthecreditlimit.Thenprocessthenextcus-tomer.Secondrefinement:Inputthefirstcustomer’saccountnumber.Whilethesentinelvalue(-1)hasnotbeenenteredfortheaccountnumberInputthecustomer’sbeginningbalanceInputthecustomer’stotalchargesInputthecustomer’stotalcreditsInputthecustomer’screditlimitCalculatethecustomer’snewbalanceIfthebalanceexceedsthecreditlimitPrinttheaccountnumberPrintthecreditlimitPrintthebalancePrint“CreditLimitExceeded”Inputthenextcustomer’saccountnumber.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions253)1/*Exercise3.18Solution*/2#include34intmain()5{6intaccountNumber;/*currentaccount"snumber*/7doublebalance;/*currentaccount"sstartingbalance*/8doublecharges;/*currentaccount"stotalcharges*/9doublecredits;/*currentaccount"stotalcredits*/10doublelimit;/*currentaccount"screditlimit*/1112/*getaccountnumber*/13printf("nEnteraccountnumber(-1toend):");14scanf("%d",&accountNumber);1516/*loopuntilsentinelvaluereadfromuser*/17while(accountNumber!=-1){18printf("Enterbeginningbalance:");19scanf("%lf",&balance);2021printf("Entertotalcharges:");22scanf("%lf",&charges);2324printf("Entertotalcredits:");25scanf("%lf",&credits);2627printf("Entercreditlimit:");28scanf("%lf",&limit);2930balance+=charges-credits;/*calculatebalance*/3132/*ifbalanceisoverlimit,displayaccountnumber33withcreditlimitandbalancetotwodigitsofprecision*/34if(balance>limit){35printf("%s%dn%s%.2fn%s%.2fn%sn",36"Account:",accountNumber,"Creditlimit:",limit,37"Balance:",balance,"CreditLimitExceeded.");38}/*endif*/3940/*promptfornextaccount*/41printf("nEnteraccountnumber(-1toend):");42scanf("%d",&accountNumber);43}/*endwhile*/4445return0;/*indicatesuccessfultermination*/4647}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com26StructuredProgramDevelopmentinC:SolutionsChapter33.19Onelargechemicalcompanypaysitssalespeopleonacommissionbasis.Thesalespeoplereceive$200perweekplus9%oftheirgrosssalesforthatweek.Forexample,asalespersonwhosells$5000worthofchemicalsinaweekreceives$200plus9%of$5000,oratotalof$650.Developaprogramthatwillinputeachsalesperson"sgrosssalesforlastweekandwillcalculateanddisplaythatsalesperson"searnings.Processonesalesperson"sfiguresatatime.Hereisasampleinput/outputdialog:Entersalesindollars(-1toend):5000.00Salaryis:$650.00Entersalesindollars(-1toend):1234.56Salaryis:$311.11Entersalesindollars(-1toend):1088.89Salaryis:$298.00Entersalesindollars(-1toend):-1ANS:2)Top:Foranarbitrarynumberofsalespeople,determineeachsalesperson’searningsforthelastweek.Firstrefinement:Inputthesalesperson’ssalesfortheweek,calculateandprintthesalesperson’swagesfortheweek,thenprocessthenextsalesperson.Secondrefinement:Inputthefirstsalesperson’ssalesindollars.Whilethesentinelvalue(-1)hasnotbeenenteredforthesalesCalculatethesalesperson’swagesfortheweekPrintthesalesperson’swagesfortheweekInputthenextsalesperson’ssalesindollars3)1/*Exercise3.19Solution*/2#include34intmain()5{6doublesales;/*grossweeklysales*/7doublewage;/*commissionedearnings*/89/*getfirstsales*/10printf("Entersalesindollars(-1toend):");11scanf("%lf",&sales);1213/*loopuntilsentinelvaluereadfromuser*/14while(sales!=-1.0){15wage=200.0+0.09*sales;/*calculatewage*/1617/*displaysalary*/18printf("Salaryis:$%.2fnn",wage);1920/*promptfornextsales*/21printf("Entersalesindollars(-1toend):");22scanf("%lf",&sales);23}/*endwhile*/2425return0;/*indicatesuccessfultermination*/2627}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions273.20Thesimpleinterestonaloaniscalculatedbytheformulainterest=principal*rate*days/365;Theprecedingformulaassumesthatrateistheannualinterestrate,andthereforeincludesthedivisionby365(days).Developaprogramthatwillinputprincipal,rateanddaysforseveralloans,andwillcalculateanddisplaythesimpleinterestforeachloan,usingtheprecedingformula.Hereisasampleinput/outputdialog:Enterloanprincipal(-1toend):1000.00Enterinterestrate:.1Entertermoftheloanindays:365Theinterestchargeis$100.00Enterloanprincipal(-1toend):1000.00Enterinterestrate:.08375Entertermoftheloanindays:224Theinterestchargeis$51.40Enterloanprincipal(-1toend):10000.00Enterinterestrate:.09Entertermoftheloanindays:1460Theinterestchargeis$3600.00Enterloanprincipal(-1toend):-1ANS:2)Top:Foranarbitrarynumberofloansdeterminethesimpleinterestforeachloan.Firstrefinement:Inputtheprincipaloftheloan,theinterestrate,andthetermoftheloan,calculateandprintthesimpleinterestfortheloan,andprocessthenextloan.Secondrefinement:inputthefirstloanprincipalindollars.Whilethesentinelvalue(-1)hasnotbeenenteredfortheloanprincipalInputtheinterestrateInputthetermoftheloanindaysCalculatethesimpleinterestfortheloanPrintthesimpleinterestfortheloanInputtheloanprincipalforthenextloan3)1/*Exercise3.20Solution*/2#include34intmain()5{6doubleprincipal;/*loanprincipal*/7doublerate;/*interestrate*/8doubleinterest;/*interestcharge*/9intterm;/*lengthofloanindays*/1011/*getloanprincipal*/12printf("Enterloanprincipal(-1toend):");13scanf("%lf",&principal);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com28StructuredProgramDevelopmentinC:SolutionsChapter31415/*loopuntilsentinelvalueisreadfromuser*/16while(principal!=-1.0){17printf("Enterinterestrate:");/*getrate*/18scanf("%lf",&rate);1920printf("Entertermoftheloanindays:");/*getterm*/21scanf("%d",&term);2223/*calculateinterestcharge*/24interest=principal*rate*term/365.0;25printf("Theinterestchargeis$%.2fnn",interest);2627/*getnextloanprincipal*/28printf("Enterloanprincipal(-1toend):");29scanf("%lf",&principal);30}/*endwhile*/3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/3.21Developaprogramthatwilldeterminethegrosspayforeachofseveralemployees.Thecompanypays“straight-time”forthefirst40hoursworkedbyeachemployeeandpays“time-and-a-half”forallhoursworkedinexcessof40hours.Youaregivenalistoftheemployeesofthecompany,thenumberofhourseachemployeeworkedlastweekandthehourlyrateofeachemployee.Yourprogramshouldinputthisinformationforeachemployee,andshoulddetermineanddisplaytheemployee"sgrosspay.Hereisasampleinput/outputdialog:Enternumberofhoursworked(-1toend):39Enterhourlyrateoftheworker($00.00):10.00Salaryis$390.00Enternumberofhoursworked(-1toend):40Enterhourlyrateoftheworker($00.00):10.00Salaryis$400.00Enternumberofhoursworked(-1toend):41Enterhourlyrateoftheworker($00.00):10.00Salaryis$415.00Enternumberofhoursworked(-1toend):-1ANS:2)Top:Foranarbitrarynumberofemployees,determinethegrosspayforeachemployee.Firstrefinement:Inputthenumberofhoursworkedfortheemployee,entertheemployee’shourlywage,calculateandprinttheemployee’sgrosspay,andprocessthenextemployee.Secondrefinement:Inputthefirstemployee’snumberofhoursworked.Whilethesentinelvalue(-1)hasnotbeenenteredforthehoursworkedInputtheemployee’shourlywageCalculatetheemployee’sgrosspaywithovertimeforhoursover40Printtheemployee’sgrosspayInputthenumberofhoursworkedforthenextcomputer©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions293)1/*Exercise3.21Solution*/2#include34intmain(void)5{6doublehours;/*totalhoursworked*/7doublerate;/*hourlypayrate*/8doublesalary;/*grosspay*/910/*getfirstemployee"shoursworked*/11printf("Enternumberofhoursworked(-1toend):");12scanf("%lf",&hours);1314/*loopuntilsentinelvaluereadfromuser*/15while(hours!=-1.0){1617/*gethourlyrate*/18printf("Enterhourlyrateoftheworker($00.00):");19scanf("%lf",&rate);2021/*ifemployeeworkedlessthan40hours*/22if(hours<=40){23salary=hours*rate;24}/*endif*/25else{/*compute"time-and-a-half"pay*/26salary=40.0*rate+(hours-40.0)*rate*1.5;27}/*endelse*/2829/*displaygrosspay*/30printf("Salaryis$%.2lfnn",salary);3132/*promptfornextemployee"sdata*/33printf("Enternumberofhoursworked(-1toend):");34scanf("%lf",&hours);35}/*endwhile*/3637return0;/*indicatesuccessfultermination*/3839}/*endmain*/3.22Writeaprogramthatdemonstratesthedifferencebetweenpredecrementingandpostdecrementingusingthedecrementop-erator--.ANS:1/*Exercise3.22Solution*/2#include34intmain()5{6intc;/*definectousedecrementoperator*/78c=5;9printf("%dn",c);10printf("%dn",--c);/*predecrement*/11printf("%dnn",c);12©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com30StructuredProgramDevelopmentinC:SolutionsChapter313c=5;14printf("%dn",c);15printf("%dn",c--);/*postdecrement*/16printf("%dnn",c);1718return0;/*indicatesuccessfultermination*/1920}/*endmain*/5445543.23Writeaprogramthatutilizesloopingtoprintthenumbersfrom1to10side-by-sideonthesamelinewith3spacesbetweeneachnumber.ANS:1/*Exercise3.23Solution*/2#include34intmain()5{6inti=0;/*initializei*/78/*loopwhileiislessthan11*/9while(++i<11){10printf("%d",i);11}/*endwhile*/1213return0;/*indicatesuccessfultermination*/1415}/*endmain*/123456789103.24Theprocessoffindingthelargestnumber(i.e.,themaximumofagroupofnumbers)isusedfrequentlyincomputerappli-cations.Forexample,aprogramthatdeterminesthewinnerofasalescontestwouldinputthenumberofunitssoldbyeachsales-person.Thesalespersonwhosellsthemostunitswinsthecontest.Writeapseudocodeprogramandthenaprogramthatinputsaseriesof10numbers,anddeterminesandprintsthelargestofthenumbers.[Hint:Yourprogramshouldusethreevariablesasfol-lows]:counter:Acountertocountto10(i.e.,tokeeptrackofhowmanynumbershavebeeninputandtodeterminewhenall10numbershavebeenprocessed)number:Thecurrentnumberinputtotheprogramlargest:ThelargestnumberfoundsofarANS:InputthefirstnumberdirectlyintothevariablelargestIncrementcounterto2©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions31Whilecounterislessthanorequalto10inputanewvariableintothevariablenumberIfnumberisgreaterthanlargestreplacelargestwithnumberIncrementcounterPrintthevalueofthelargest(whileconditionfalsewhencounteris11)1/*Exercise3.24Solution*/2#include34intmain()5{6intcounter;/*counterfor10repetitions*/7intnumber;/*currentnumberinput*/8intlargest;/*largestnumberfoundsofar*/910/*getfirstnumber*/11printf("Enterthefirstnumber:");12scanf("%d",&largest);13counter=2;1415/*loop9moretimes*/16while(counter<=10){17printf("Enternextnumber:");/*getnextnumber*/18scanf("%d",&number);1920/*ifcurrentnumberinputisgreaterthanlargestnumber,21updatelargest*/22if(number>largest){23largest=number;24}/*endif*/2526counter++;27}/*endwhile*/2829printf("Largestis%dn",largest);/*displaylargestnumber*/3031return0;/*indicatesuccessfultermination*/3233}/*endmain*/Enterthefirstnumber:7Enternextnumber:37Enternextnumber:78Enternextnumber:2Enternextnumber:437Enternextnumber:72Enternextnumber:1Enternextnumber:4Enternextnumber:36Enternextnumber:100Largestis437©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com32StructuredProgramDevelopmentinC:SolutionsChapter33.25Writeaprogramthatutilizesloopingtoprintthefollowingtableofvalues:N10*N100*N1000*N11010010002202002000330300300044040040005505005000660600600077070070008808008000990900900010100100010000Thetabcharacter,t,maybeusedintheprintfstatementtoseparatethecolumnswithtabs.ANS:1/*Exercise3.25Solution*/2#include34intmain()5{6intn=0;/*counter*/78/*displaytableheaders*/9printf("tNtt10*Ntt100*Ntt1000*Nnn");1011/*loop10times*/12while(++n<=10){1314/*calculateanddisplaytablevalues*/15printf("t%-2dtt%-5dtt%-5dtt%-6dn",16n,10*n,100*n,1000*n);17}/*endwhile*/1819return0;/*indicatesuccessfultermination*/2021}/*endmain*/3.26Writeaprogramthatutilizesloopingtoproducethefollowingtableofvalues:AA+2A+4A+6357968101291113151214161815171921©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions33ANS:1/*Exercise3.26Solution*/2#include34intmain()5{6inta=3;/*counter*/78/*displaytableheaders*/9printf("AtA+2tA+4tA+6nn");1011/*loop5times*/12while(a<=15){1314/*calculateanddisplaytablevalues*/15printf("%dt%dt%dt%dn",a,a+2,a+4,a+6);16a+=3;17}/*endwhile*/1819return0;/*indicatesuccessfultermination*/2021}/*endmain*/3.27UsinganapproachsimilartoExercise3.24,findthetwolargestvaluesofthe10numbers.[Note:Youmayinputeachnum-beronlyonce.]ANS:1/*Exercise3.27Solution*/2#include34intmain()56{7intcounter;/*counterfor10repetitions*/8intnumber;/*currentnumberinput*/9intlargest;/*largestnumberfound*/10intsecondLargest=0;/*secondlargestnumberfound*/1112printf("Enterthefirstnumber:");/*getfirstnumber*/13scanf("%d",&largest);14counter=2;1516/*loop9moretimes*/17while(counter<=10){18printf("Enternextnumber:");/*promptfornextnumber*/19scanf("%d",&number);2021/*ifcurrentnumberisgreaterthanlargest*/22if(number>largest){2324/*updatesecondlargestwithpreviouslargest*/25secondLargest=largest;2627/*updatelargestwithcurrentnumber*/28largest=number;29}/*endif*/30else{31©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com34StructuredProgramDevelopmentinC:SolutionsChapter332/*ifnumberisbetweensecondLargestandlargest*/33if(number>secondLargest){34secondLargest=number;35}/*endif*/3637}/*endelse*/3839++counter;40}/*endwhile*/4142/*displaylargesttwonumbers*/43printf("Largestis%dn",largest);44printf("Secondlargestis%dn",secondLargest);4546return0;/*indicatesuccessfultermination*/4748}/*endmain*/Enterthefirstnumber:100Enternextnumber:102Enternextnumber:83Enternextnumber:3883Enternextnumber:328Enternextnumber:28Enternextnumber:839Enternextnumber:2398Enternextnumber:182Enternextnumber:0Largestis3883Secondlargestis23983.28ModifytheprograminFigure3.10tovalidateitsinputs.Onanyinput,ifthevalueenteredisotherthan1or2,keeploopinguntiltheuserentersacorrectvalue.ANS:1/*Exercise3.28Solution*/2#include34intmain()5{6intpasses=0;/*numberofpasses*/7intfailures=0;/*numberoffailures*/8intstudent=1;/*studentcounter*/9intresult;/*oneexamresult*/1011/*process10studentsusingcounter-controlledloop*/12while(student<=10){1314/*promptuserforinputandobtainvaluefromuser*/15printf("Enterresult(1=pass,2=fail):");16scanf("%d",&result);1718/*loopuntilvalidinput*/19while(result!=1&&result!=2){20printf("InvalidresultnEnterresult(1=pass,2=fail):");21scanf("%d",&result);22}/*endinnerwhile*/23©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions3524/*ifresult1,incrementpasses*/25if(result==1){26++passes;27}/*endif*/28else{/*ifresultisnot1,incrementfailures*/29++failures;30}/*endelse*/3132++student;33}/*endwhile*/3435printf("Passed%dnFailed%dn",passes,failures);3637/*ifmorethaneightstudentspassed,print"raisetuition"*/38if(passes>=8){39printf("Raisetuitionn");40}/*endif*/4142return0;/*indicatesuccessfultermination*/4344}/*endmain*/Enterresult(1=pass,2=fail):1Enterresult(1=pass,2=fail):2Enterresult(1=pass,2=fail):3InvalidresultEnterresult(1=pass,2=fail):4InvalidresultEnterresult(1=pass,2=fail):2Enterresult(1=pass,2=fail):2Enterresult(1=pass,2=fail):2Enterresult(1=pass,2=fail):1Enterresult(1=pass,2=fail):1Enterresult(1=pass,2=fail):1Enterresult(1=pass,2=fail):1Enterresult(1=pass,2=fail):1Passed6Failed43.29Whatdoesthefollowingprogramprint?1#include23/*functionmainbeginsprogramexecution*/4intmain()5{6intcount=1;/*initializecount*/78while(count<=10){/*loop10times*/910/*outputlineoftext*/11printf("%sn",count%2?"****":"++++++++");12count++;/*incrementcount*/13}/*endwhile*/1415return0;/*indicateprogramendedsuccessfully*/1617}/*endfunctionmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com36StructuredProgramDevelopmentinC:SolutionsChapter3ANS:****++++++++****++++++++****++++++++****++++++++****++++++++3.30Whatdoesthefollowingprogramprint?1#include23/*functionmainbeginsprogramexecution*/4intmain()5{6introw=10;/*initializerow*/7intcolumn;/*definecolumn*/89while(row>=1){/*loopuntilrow<1*/10column=1;/*setcolumnto1asiterationbegins*/1112while(column<=10){/*loop10times*/13printf("%s",row%2?"<":">");/*output*/14column++;/*incrementcolumn*/15}/*endinnerwhile*/1617row--;/*decrementrow*/18printf("n");/*beginnewoutputline*/19}/*endouterwhile*/2021return0;/*indicateprogramendedsuccessfully*/2223}/*endfunctionmain*/ANS:>>>>>>>>>><<<<<<<<<<>>>>>>>>>><<<<<<<<<<>>>>>>>>>><<<<<<<<<<>>>>>>>>>><<<<<<<<<<>>>>>>>>>><<<<<<<<<<©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions373.31(DanglingElseProblem)Determinetheoutputforeachofthefollowingwhenxis9andyis11andwhenxis11andyis9.NotethatthecompilerignorestheindentationinaCprogram.Also,thecompileralwaysassociatesanelsewiththepreviousifunlesstoldtodootherwisebytheplacementofbraces{}.Because,onfirstglance,theprogrammermaynotbesurewhichifanelsematch-es,thisisreferredtoasthe“danglingelse”problem.Wehaveeliminatedtheindentationfromthefollowingcodetomaketheproblemmorechallenging.[Hint:Applyindentationconventionsyouhavelearned.]a)if(x<10)if(y>10)printf("*****n");elseprintf("#####n");printf("$$$$$n");ANS:x=9,y=11*****$$$$$x=11,y=9$$$$$b)if(x<10){if(y>10)printf("*****n");}else{printf("#####n");printf("$$$$$n");}ANS:x=9,y=11*****x=11,y=9#####$$$$$3.32(AnotherDanglingElseProblem)Modifythefollowingcodetoproducetheoutputshown.Useproperindentationtechniques.Youmightnotmakeanychangesotherthaninsertingbraces.Thecompilerignorestheindentationinaprogram.Wehaveeliminatedtheindentationfromthefollowingcodetomaketheproblemmorechallenging.[Note:Itispossiblethatnomodificationisnecessary.]if(y==8)if(x==5)printf("@@@@@n");elseprintf("#####n");printf("$$$$$n");printf("&&&&&n");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com38StructuredProgramDevelopmentinC:SolutionsChapter3a)Assumingx=5andy=8,thefollowingoutputisproduced.@@@@@$$$$$&&&&&ANS:if(y==8){if(x==5)printf(“@@@@@n”);elseprintf(“#####n”);printf(“$$$$$n”);printf(“&&&&&n”);}b)Assumingx=5andy=8,thefollowingoutputisproduced.@@@@@ANS:if(y==8)if(x==5)printf(“@@@@@n”);else{printf(“#####n”);printf(“$$$$$n”);printf(“&&&&&n”);}c)Assumingx=5andy=8,thefollowingoutputisproduced.@@@@@&&&&&ANS:if(y==8)if(x==5)printf(“@@@@@n”);else{printf(“#####n”);printf(“$$$$$n”);}printf(“&&&&&n”);d)Assumingx=5andy=7,thefollowingoutputisproduced.[Note:Thelastthreeprintfstatementsareallpartofacompoundstatement.#####$$$$$&&&&&©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions39ANS:if(y==8){if(x==5)printf(“@@@@@n”);}else{printf(“#####n”);printf(“$$$$$n”);printf(“&&&&&n”);}3.33Writeaprogramthatreadsinthesideofasquareandthenprintsthatsquareoutofasterisks.Yourprogramshouldworkforsquaresofallsidesizesbetween1and20.Forexample,ifyourprogramreadsasizeof4,itshouldprint****************ANS:1/*Exercise3.33Solution*/2#include34intmain()5{6intside;/*sidecounter*/7inttemp;/*temporaryinteger*/8intasterisk;/*asteriskcounter*/910printf("Enterthesquareside:");/*getsizeofsquare*/11scanf("%d",&side);1213temp=side;1415/*loopthroughrowsofsquare*/16while(side-->0){17asterisk=temp;1819/*loopthroughcolumnsofsquare*/20while(asterisk-->0){21printf("*");22}/*endinnerwhile*/2324putchar("n");25}/*endouterwhile*/2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com40StructuredProgramDevelopmentinC:SolutionsChapter33.34ModifytheprogramyouwroteinExercise3.33sothatitprintsahollowsquare.Forexample,ifyourprogramreadsasizeof5,itshouldprint****************ANS:1/*Exercise3.34Solution*/2#include34intmain()5{6intside;/*sidecounter*/7introwPosition;/*rowcounter*/8intsize;/*lengthofside*/910printf("Enterthesquareside:");/*promptforsidelength*/11scanf("%d",&side);1213size=side;/*setsizecountertolengthofside*/1415/*loopsidenumberoftimes*/16while(side>0){17rowPosition=size;/*setrowcountertolengthofsize*/1819/*looprowPositionnumberoftimes*/20while(rowPosition>0){2122/*ifsideorrowcounteris1orsizeprintan"*"*/23if(size==side){24printf("*");25}/*endif*/26elseif(side==1){27printf("*");28}/*endelseif*/29elseif(rowPosition==1){30printf("*");31}/*endelseif*/32elseif(rowPosition==size){33printf("*");34}/*endelseif*/35else{/*otherwise,printaspace*/36printf("");37}/*endelse*/3839--rowPosition;/*decrementrowcounter*/40}/*endinnerwhile*/4142printf("n");/*newlinefornextrow*/43--side;/*decrementsidecounter*/44}/*endouterwhile*/4546return0;/*indicatesuccessfultermination*/4748}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions413.35Apalindromeisanumberoratextphrasethatreadsthesamebackwardsasforwards.Forexample,eachofthefollowingfive-digitintegersarepalindromes:12321,55555,45554and11611.Writeaprogramthatreadsinafive-digitintegeranddeter-mineswhetherornotitisapalindrome.[Hint:Usethedivisionandremainderoperatorstoseparatethenumberintoitsindividualdigits.]ANS:1/*Exercise3.35Solution*/2#include34intmain()5{6intnumber;/*inputnumber*/7inttemp1;/*firsttemporaryinteger*/8inttemp2;/*secondtemporaryinteger*/9intfirstDigit;/*firstdigitofinput*/10intsecondDigit;/*seconddigitofinput*/11intfourthDigit;/*fourthdigitofinput*/12intfifthDigit;/*fifthdigitofinput*/1314printf("Enterafive-digitnumber:");/*getnumber*/15scanf("%d",&number);1617temp1=number;1819/*determinefirstdigitbyintegerdivisionby10000*/20firstDigit=temp1/10000;21temp2=temp1%10000;2223/*determineseconddigitbyintegerdivisionby1000*/24secondDigit=temp2/1000;25temp1=temp2%1000;2627temp2=temp1%100;2829/*determinefourthdigitbyintegerdivisionby10*/30fourthDigit=temp2/10;31temp1=temp2%10;3233fifthDigit=temp1;3435/*iffirstandfifthdigitsareequal*/36if(firstDigit==fifthDigit){3738/*ifsecondandfourthdigitsareequal*/39if(secondDigit==fourthDigit){4041/*numberisapalindrome*/42printf("%disapalindromen",number);43}/*endif*/44else{/*numberisnotapalindrome*/45printf("%disnotapalindromen",number);46}/*endelse*/4748}/*endif*/49else{/*numberisnotapalindrome*/50printf("%disnotapalindromen",number);51}/*endelse*/5253return0;/*indicatesuccessfultermination*/5455}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com42StructuredProgramDevelopmentinC:SolutionsChapter3Enterafive-digitnumber:1818118181isapalindromeEnterafive-digitnumber:1673816738isnotapalindrome3.36Inputanintegercontainingonly0sand1s(i.e.,a“binary”integer)andprintitsdecimalequivalent.[Hint:Usetheremainderanddivisionoperatorstopickoffthe“binary”number’sdigitsoneatatimefromrighttoleft.Justasinthedecimalnumbersysteminwhichtherightmostdigithasapositionalvalueof1,andthenextdigitlefthasapositionalvalueof10,then100,then1000,etc.,inthebinarynumbersystemtherightmostdigithasapositionalvalueof1,thenextdigitlefthasapositionalvalueof2,then4,then8,etc.Thusthedecimalnumber234canbeinterpretedas4*1+3*10+2*100.Thedecimalequivalentofbinary1101is1*1+0*2+1*4+1*8or1+0+4+8or13.]ANS:1/*Exercise3.36Solution*/2#include34intmain()5{6intbinary;/*currentvalueofbinarynumber*/7intnumber;/*inputbinarynumber*/8intdecimal=0;/*currentvalueofdecimalnumber*/9inthighBit=16;/*valueofhighestbit*/10intfactor=10000;/*factorof10topickoffdigits*/1112/*promptforbinaryinput*/13printf("Enterabinarynumber(5digitsmaximum):");14scanf("%d",&binary);1516number=binary;/*saveinnumberforfinaldisplay*/1718/*loop5timesusingpowersof2*/19while(highBit>=1){2021/*updatedecimalvaluewithdecimalvaluecorresponding22tocurrenthighestbinarybit*/23decimal+=binary/factor*highBit;2425/*reducehighbitbyfactorof2,i.e.,26moveonebittotheright*/27highBit/=2;2829/*reducebinarynumbertoeliminatecurrenthighestbit*/30binary%=factor;3132/*reducefactorbypowerof10,i.e.,33moveonebittotheright*/34factor/=10;35}/*endwhile*/3637/*displaydecimalvalue*/38printf("Thedecimalequivalentof%dis%dn",number,decimal);3940return0;/*indicatesuccessfultermination*/4142}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions43Enterabinarynumber(5digitsmaximum):10111Thedecimalequivalentof10111is23Enterabinarynumber(5digitsmaximum):1101Thedecimalequivalentof1101is133.37Howcanyoudeterminehowfastyourowncomputerreallyoperates?Writeaprogramwithawhileloopthatcountsfrom1to300,000,000by1s.Everytimethecountreachesamultipleof100,000,000printthatnumberonthescreen.Useyourwatchtotimehowlongeachmillionrepetitionsofthelooptakes.ANS:1/*Exercise3.37Solution*/2#include34intmain()5{6longintcount=1;/*counter*/78/*loopto300,000,000*/9while(count<=300000000){1011if(count%100000000==0){12printf("Multipleis%dn",count/100000000);13}/*endif*/1415++count;/*incrementcount*/16}/*endwhile*/1718return0;/*indicatesuccessfultermination*/1920}/*endmain*/Multipleis1Multipleis2Multipleis33.38Writeaprogramthatprints100asterisks,oneatatime.Aftereverytenthasterisk,yourprogramshouldprintanewlinecharacter.(Hint:Countfrom1to100.Usetheremainderoperatortorecognizeeachtimethecounterreachesamultipleof10.)ANS:1/*Exercise3.38Solution*/2#include34intmain()5{6intcount=0;/*counter*/78/*loopto100*/9while(++count<=100)1011/*printanewlineafterevery10thasterisk*/12count%10==0?printf("*n"):printf("*");1314return0;/*indicatesuccessfultermination*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com44StructuredProgramDevelopmentinC:SolutionsChapter31516}/*endmain*/****************************************************************************************************3.39Writeaprogramthatreadsanintegeranddeterminesandprintshowmanydigitsintheintegerare7s.ANS:1/*Exercise3.39Solution*/2#include34intmain()5{6intnumber;/*userinput*/7intnumCopy;/*copyofnumber*/8intfactor=10000;/*setfactortopickoffdigits*/9intdigit;/*individualdigitofnumber*/10intsevens=0;/*sevenscounter*/1112printf("Entera5-digitnumber:");/*getnumberfromuser*/13scanf("%d",&number);1415numCopy=number;1617/*loopthrougheachofthe5digits*/18while(factor>=1){19digit=numCopy/factor;/*pickoffnextdigit*/2021if(digit==7){/*ifdigitequals7,incrementsevens*/22++sevens;23}/*endif*/2425numCopy%=factor;26factor/=10;27}/*endwhile*/2829/*outputnumberofsevens*/30printf("Thenumber%ldhas%dseven(s)initn",number,sevens);3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/Entera5-digitnumber:17737Thenumber17737has3seven(s)init©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions45Entera5-digitnumber:11727Thenumber11727has2seven(s)init3.40Writeaprogramthatdisplaysthefollowingcheckerboardpattern****************************************************************Yourprogrammustuseonlythreeoutputstatements,oneofeachofthefollowingforms:printf("*");printf("");printf("n");ANS:1/*Exercise3.40Solution*/2#include34intmain()5{6intside=8;/*sidecounter*/7introw;/*rowcounter*/8intmod;/*remainder*/910/*loop8times*/11while(side>=1){12row=8;/*resetrowcounter*/13mod=side%2;1415/*loop8times*/16while(row>=1){1718/*ifoddrow,beginwithaspace*/19if(mod!=0){20printf("");21mod=0;22}/*endif*/2324printf("*");25--row;26}/*endwhile*/2728printf("n");/*gotonextline*/29--side;30}/*endwhile*/3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com46StructuredProgramDevelopmentinC:SolutionsChapter33.41Writeaprogramthatkeepsprintingthemultiplesoftheinteger2,namely2,4,8,16,32,64,etc.Yourloopshouldnotterminate(i.e.,youshouldcreateaninfiniteloop).Whathappenswhenyourunthisprogram?ANS:Programexecutionterminateswhenlargestintegerisexceeded(i.e.,theloopcontinuationtestfailswhenthemax-imumvalueforanintegerisexceeded.Ona4-bytesystem,thelargestintegervalueis2147483647andanythingabovethatisrepresentedbyanegativenumber,whichfailstheloopcontinuationtest).1/*Exercise3.41Solution*/2#include34intmain()5{6intmultiple=1;/*counter*/78/*infiniteloop*/9while(multiple>0){1011/*calculatethenextpoweroftwo*/12multiple*=2;13printf("%dn",multiple);14}/*endwhile*/1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/248163264128256512102420484096819216384327686553613107226214452428810485762097152419430483886081677721633554432671088641342177282684354565368709121073741824-21474836483.42Writeaprogramthatreadstheradiusofacircle(asafloatvalue)andcomputesandprintsthediameter,thecircumferenceandthearea.Usethevalue3.14159forp.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions47ANS:1/*Exercise3.42Solution*/2#include34intmain()5{6floatradius;/*inputradius*/7floatpi=3.14159;/*valueforpi*/89printf("Entertheradius:");/*getradiusvalue*/10scanf("%f",&radius);1112/*computeanddisplaydiameter*/13printf("Thediameteris%.2fn",radius*2);1415/*computeanddisplaycircumference*/16printf("Thecircumferenceis%.2fn",2*pi*radius);1718/*computeanddisplayarea*/19printf("Theareais%.2fn",pi*radius*radius);2021return0;/*indicatesuccessfultermination*/2223}/*endmain*/Entertheradius:4.7Thediameteris9.40Thecircumferenceis29.53Theareais69.403.43Whatiswrongwiththefollowingstatement?Rewritethestatementtoaccomplishwhattheprogrammerwasprobablytry-ingtodo.printf("%d",++(x+y));ANS:printf(“%d”,1+x+y);3.44Writeaprogramthatreadsthreenonzerofloatvaluesanddeterminesandprintsiftheycouldrepresentthesidesofatri-angle.ANS:1/*Exercise3.44Solution*/2#include34intmain()5{6doublea;/*firstnumber*/7doubleb;/*secondnumber*/8doublec;/*thirdnumber*/910/*input3numbers*/11printf("Enterthreedoubleingpointnumbers:");12scanf("%lf%lf%lf",&a,&b,&c);1314/*usePythagoreanTheorem*/15if(c*c==a*a+b*b){16printf("Thethreenumberscouldbesidesofatrianglen");17}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com48StructuredProgramDevelopmentinC:SolutionsChapter318else{19printf("Thethreenumbersprobably");20printf("arenotthesidesofatrianglen");21}/*endif*/2223return0;/*indicatesuccessfultermination*/2425}/*endmain*/Enterthreedoubleingpointnumbers:5.73.62.2ThethreenumbersprobablyarenotthesidesofatriangleEnterthreedoubleingpointnumbers:3.04.05.0Thethreenumberscouldbesidesofatriangle3.45Writeaprogramthatreadsthreenonzerointegersanddeterminesandprintsiftheycouldbethesidesofarighttriangle.ANS:1/*Exercise3.45Solution*/2#include34intmain()5{6inta;/*firstnumber*/7intb;/*secondnumber*/8intc;/*thirdnumber*/910/*inputthreenumbers*/11printf("Enterthreeintegers:");12scanf("%d%d%d",&a,&b,&c);1314/*usePythagoreanTheorem*/15if(c*c==a*a+b*b){16printf("Thethreeintegersarethesidesof");17printf("arighttrianglen");18}/*endif*/19else{20printf("Thethreeintegersarenotthesides");21printf("ofarighttrianglen");22}/*endelse*/2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/Enterthreeintegers:345ThethreeintegersarethesidesofarighttriangleEnterthreeintegers:941Thethreeintegersarenotthesidesofarighttriangle©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions493.46Acompanywantstotransmitdataoverthetelephone,buttheyareconcernedthattheirphonesmaybetapped.Alloftheirdataistransmittedasfour-digitintegers.Theyhaveaskedyoutowriteaprogramthatwillencrypttheirdatasothatitmaybetrans-mittedmoresecurely.Yourprogramshouldreadafour-digitintegerandencryptitasfollows:Replaceeachdigitbytheremainderafter(thesumofthatdigitplus7)isdividedby10.Then,swapthefirstdigitwiththethird,andswaptheseconddigitwiththefourth.Thenprinttheencryptedinteger.Writeaseparateprogramthatinputsanencryptedfour-digitintegeranddecryptsittoformtheoriginalnumber.ANS:1/*Exercise3.46PartAsolution*/2#include34intmain()5{6intfirst;/*firstdigitreplacement*/7intsecond;/*seconddigitreplacement*/8intthird;/*thirddigitreplacement*/9intfourth;/*fourthdigitreplacement*/10intdigit;/*inputnumber*/11inttemp1;/*temporarilyholddigit*/12inttemp2;/*temporarilyholddigit*/13intencryptedNumber;/*resultingencryptednumber*/1415/*promptforinput*/16printf("Enterafourdigitnumbertobeencrypted:");17scanf("%d",&digit);1819temp1=digit;2021/*retrieveeachdigitandreplacewith22(sumofdigitand7)mod10*/23first=(temp1/1000+7)%10;24temp2=temp1%1000;2526second=(temp2/100+7)%10;27temp1=temp2%100;2829third=(temp1/10+7)%10;30temp2=temp1%10;3132fourth=(temp2+7)%10;3334/*swapfirstandthird*/35temp1=first;36first=third*1000;/*multiplyby1000for1stdigitcomponent*/37third=temp1*10;/*multiplyby10for3rddigitcomponent*/3839/*swapsecondandfourth*/40temp1=second;41second=fourth*100;/*multiplyby100for2nddigitcomponent*/42fourth=temp1*1;4344/*addcomponentstoobtainencryptednumber*/45encryptedNumber=first+second+third+fourth;4647/*displayencryptednumber*/48printf("Encryptednumberis%dn",encryptedNumber);4950return0;/*indicatesuccessfultermination*/5152}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com50StructuredProgramDevelopmentinC:SolutionsChapter3Enterafourdigitnumbertobeencrypted:5678Encryptednumberis45231/*Exercise3.46PartBSolution*/2#include34intmain()5{6intfirst;/*firstdecrypteddigit*/7intsecond;/*seconddecrypteddigit*/8intthird;/*thirddecrypteddigit*/9intfourth;/*fourthdecrypteddigit*/10intdecrypted;/*decryptednumber*/11inttemp1;/*temporarilyholddigit*/12inttemp2;/*temporarilyholddigit*/13intencryptedNumber;/*inputnumber*/1415/*promptforinput*/16printf("Enterafourdigitencryptednumber:");17scanf("%d",&encryptedNumber);1819temp1=encryptedNumber;2021/*retrieveeachdigitanddecryptby22(sumofdigitand3)mod10*/23first=(temp1/1000);24temp2=temp1%1000;2526second=(temp2/100);27temp1=temp2%100;2829third=(temp1/10);30temp2=temp1%10;3132fourth=temp2;3334temp1=(first+3)%10;35first=(third+3)%10;36third=temp1;3738temp1=(second+3)%10;39second=(fourth+3)%10;40fourth=temp1;4142/*addcomponentstoobtaindecryptednumber*/43decrypted=(first*1000)+(second*100)+44(third*10)+fourth;4546/*displaydecryptednumber*/47printf("Decryptednumberis%dn",decrypted);4849return0;/*indicatesuccessfultermination*/5051}/*endmain*/Enterafourdigitencryptednumber:4523Decryptednumberis5678©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions511.1Thefactorialofanonnegativeintegerniswrittenn!(pronounced“nfactorial”)andisdefinedasfollows:n!=n·(n-1)·(n-2)·…·1(forvaluesofngreaterthanorequalto1)andn!=1(forn=0).Forexample,5!=5·4·3·2·1,whichis120.a)Writeaprogramthatreadsanonnegativeintegerandcomputesandprintsitsfactorial.ANS:1/*Exercise3.47PartASolution*/2#include34intmain()5{6intn;/*currentmultiplicationfactor*/7intnumber=-1;/*inputnumber*/8unsignedfactorial=1;/*resultingfactorial*/910/*loopuntilvalidinput*/11do{12printf("Enterapositiveinteger:");13scanf("%d",&number);14}while(number<0);/*enddo...while*/1516n=number;1718/*computefactorial*/19while(n>=0){2021if(n==0){22factorial*=1;23}/*endif*/24else{25factorial*=n;26}/*endelse*/2728--n;29}/*endwhile*/3031/*displayfactorial*/32printf("%d!is%un",number,factorial);3334return0;/*indicatesuccessfultermination*/3536}/*endmain*/Enterapositiveinteger:55!is120Enterapositiveinteger:99!is362880Enterapositiveinteger:-8Enterapositiveinteger:00!is1©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com52StructuredProgramDevelopmentinC:SolutionsChapter3b)Writeaprogramthatestimatesthevalueofthemathematicalconstantebyusingtheformula:111e=1++++---------------¼1!2!3!ANS:1/*Exercise3.47PartBSolution*/2#include34intmain()5{6intn=0;/*loopcounterforaccuracy*/7intfact=1;/*currentnfactorial*/8intaccuracy=10;/*degreeofaccuracy*/9doublee=0;/*currentestimatedvalueofe*/1011/*loopuntildegreeofaccuracy*/12while(n<=accuracy){1314if(n==0){15fact*=1;16}/*endif*/17else{18fact*=n;19}/*endelse*/2021e+=1.0/fact;22++n;23}/*endwhile*/2425printf("eis%fn",e);/*displayestimatedvalue*/2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/eis2.718282xc)Writeaprogramthatcomputesthevalueofebyusingtheformula23xxxxe=1++++---------------¼1!2!3!ANS:1/*Exercise3.47PartCSolution*/2#include34intmain()5{6intn=0;/*counter*/7intaccuracy=15;/*degreeofaccuracy*/8intx=3;/*exponent*/9inttimes=0;/*counter*/10intcount;/*copyofn*/11doublee=1.0;/*eraisedtothexpower*/12doubleexp=0.0;/*xraisedtothenpower*/13doublefact=1.0;/*nfactorial*/14©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter3StructuredProgramDevelopmentinC:Solutions5315/*loopwhilelessthandegreeofaccuracy*/16while(n<=accuracy){17count=n;1819/*updaten!*/20if(n==0){21fact*=1.0;22}/*endif*/23else{24fact*=n;25}/*endelse*/2627while(times=1,x++)printf("%dn",x);ANS:Finforshouldbelowercase.Theinfiniteloopcanbecorrectedbyswitchingthe1andthe100andchangingtherelationaloperatorto<=.Semicolonsareneededbetweentheforconditions,notcommaoperators.for(x=1;x<=100;x++)printf(“%dn”,x);b)Thefollowingcodeshouldprintwhetheragivenintegerisoddoreven:switch(value%2){case0:printf("Evenintegern");case1:printf("Oddintegern");}ANS:Abreakisneededforcase0,otherwisebothstatementswillbeprintedout.switch(value%2){case0:printf(“Evenintegern”);break;case1:printf(“Oddintegern”);c)Thefollowingcodeshouldinputanintegerandacharacterandprintthem.Assumetheusertypesasinput100A.scanf("%d",&intVal);charVal=getchar();printf("Integer:%dnCharacter:%cn",intVal,charVal);ANS:charValwillreadthereturncharacterwhentheusertypesinintValandhitsreturn.Tocorrectthis,scanfshouldbeusedtoreadincharVal.scanf(“%d”,&intVal);scanf(“n%c”,&charVal);printf(“Integer:%dnCharacter:%cn”,intVal,charVal);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com56CProgramControl:SolutionsChapter4d)for(x=.000001;x<=.0001;x+=.000001)printf("%.7fn",x);ANS:Floatingpointnumbersshouldneverbeusedinloopsduetoimprecision.Thisimprecisionoftencausesinfiniteloopstooccur.Tocorrectthis,anintegervariableshouldbeusedintheforloop.e)Thefollowingcodeshouldoutputtheoddintegersfrom999to1:for(x=999;x>=1;x+=2)printf("%dn",x);ANS:loopshouldbedecrementingnotincrementing.for(x=999;x>=1;x-=2)printf(“%dn”,x);f)Thefollowingcodeshouldoutputtheevenintegersfrom2to100:counter=2;Do{if(counter%2==0)printf("%dn",counter);counter+=2;}While(counter<100);ANS:DinDoshouldbelowercase.WinWhileshouldbelowercase.Therangeof2to100needstobeprinted,sotherelationaloperator=2;x-=3)printf("%dn",x);ANS:12,9,6,34.7Writeforstatementsthatprintthefollowingsequencesofvalues:a)1,2,3,4,5,6,7ANS:for(i=1;i<=7;i++)printf(“%d”,i);b)3,8,13,18,23ANS:/*incrementsof5*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions57for(i=3;i<=23;i+=5)printf(“%d”,i);c)20,14,8,2,-4,-10ANS:/*decrementsof6*/for(i=20;i>=-10;i-=6)printf(“%d”,i);d)19,27,35,43,51ANS:/*incrementsof8*/for(i=19;i<=51;i+=8)printf(“%d“,i);4.8Whatdoesthefollowingprogramdo?1#include23/*functionmainbeginsprogramexecution*/4intmain()5{6intx;7inty;8inti;9intj;1011/*promptuserforinput*/12printf("Entertwointegersintherange1-20:");13scanf("%d%d",&x,&y);/*readvaluesforxandy*/1415for(i=1;i<=y;i++){/*countfrom1toy*/1617for(j=1;j<=x;j++){/*countfrom1tox*/18printf("@");/*output@*/19}/*endinnerfor*/2021printf("n");/*beginnewline*/22}/*endouterfor*/2324return0;/*indicateprogramendedsuccessfully*/2526}/*endfunctionmain*/ANS:Enterintegersintherange1-20:34@@@@@@@@@@@@4.9Writeaprogramthatsumsasequenceofintegers.Assumethatthefirstintegerreadwithscanfspecifiesthenumberofvaluesremainingtobeentered.Yourprogramshouldreadonlyonevalueeachtimescanfisexecuted.Atypicalinputsequencemightbe5100200300400500wherethe5indicatesthatthesubsequentfivevaluesaretobesummed.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com58CProgramControl:SolutionsChapter4ANS:1/*Exercise4.9Solution*/2#include34intmain(void)5{6intsum=0;/*currentsum*/7intnumber;/*numberofvalues*/8intvalue;/*currentvalue*/9inti;/*counter*/1011/*displayprompt*/12printf("Enterthenumberofvalues"13"tobeprocessed:");14scanf("%d",&number);/*inputnumberofvalues*/1516/*loopnumbertimes*/17for(i=1;i<=number;i++){18printf("Enteravalue:");19scanf("%d",&value);20sum+=value;/*addtosum*/21}/*endfor*/2223/*displaysum*/24printf("Sumofthe%dvaluesis%dn",number,sum);2526return0;/*indicatesuccessfultermination*/2728}/*endmain*/Enterthenumberofvaluestobeprocessed:5Enteravalue:10Enteravalue:15Enteravalue:20Enteravalue:25Enteravalue:30Sumofthe5valuesis1004.10Writeaprogramthatcalculatesandprintstheaverageofseveralintegers.Assumethelastvaluereadwithscanfisthesentinel9999.Atypicalinputsequencemightbe10811799999indicatingthattheaverageofallthevaluespreceding9999istobecalculated.ANS:1/*Exercise4.10Solution*/2#include34intmain(void)5{6intvalue;/*currentvalue*/7intcount=0;/*numberofvalues*/8inttotal=0;/*sumofintegers*/910/*displayprompt*/11printf("Enteraninteger(9999toend):");12scanf("%d",&value);13©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions5914/*loopwhilesentinelvaluenotreadfromuser*/15while(value!=9999){16total+=value;/*updatetotal*/17++count;1819/*getnextvalue*/20printf("Enternextinteger(9999toend):");21scanf("%d",&value);22}/*endwhile*/2324/*showaverageifmorethan0valuesentered*/25if(count!=0){26printf("nTheaverageis:%.2fn",(double)total/count);27}/*endif*/28else{29printf("nNovalueswereentered.n");30}/*endelse*/3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/Enteraninteger(9999toend):1Enternextinteger(9999toend):2Enternextinteger(9999toend):3Enternextinteger(9999toend):4Enternextinteger(9999toend):5Enternextinteger(9999toend):6Enternextinteger(9999toend):9999Theaverageis:3.504.11Writeaprogramthatfindsthesmallestofseveralintegers.Assumethatthefirstvaluereadspecifiesthenumberofvaluesremaining.ANS:1/*Exercise4.11Solution*/2#include34intmain(void)5{6intnumber;/*numberofintegers*/7intvalue;/*valueinputbyuser*/8intsmallest;/*smallestnumber*/9inti;/*counter*/1011/*promptuserfornumberofintegers*/12printf("Enterthenumberofintegerstobeprocessed:");13scanf("%d",&number);1415/*promptuserforaninteger*/16printf("Enteraninteger:");17scanf("%d",&smallest);1819/*loopuntiluserhasenteredallintegers*/20for(i=2;i<=number;i++){21printf("Enternextinteger:");/*getnextinteger*/22scanf("%d",&value);23©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com60CProgramControl:SolutionsChapter424/*ifvalueissmallerthansmallest*/25if(value34intmain(void)5{6inti;/*counter*/7intsum=0;/*currentsumofintegers*/89/*loopthroughevenintegersupto30*/10for(i=2;i<=30;i+=2){11sum+=i;/*additosum*/12}/*endfor*/1314printf("Sumoftheevenintegersfrom2to30is:%dn",sum);1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/Sumoftheevenintegersfrom2to30is:2404.13Writeaprogramthatcalculatesandprintstheproductoftheoddintegersfrom1to15.ANS:1/*Exercise4.13Solution*/2#include34intmain(void)5{6longi;/*counter*/7longproduct=1;/*currentproduct*/8©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions619/*loopthroughoddintegersupto15*/10for(i=3;i<=15;i+=2){11product*=i;/*updateproduct*/12}/*endfor*/1314printf("Productoftheoddintegersfrom1to15is:%ldn",product);1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/Productoftheoddintegersfrom1to15is:20270254.14Thefactorialfunctionisusedfrequentlyinprobabilityproblems.Thefactorialofapositiveintegern(writtenn!andpro-nounced“nfactorial”)isequaltotheproductofthepositiveintegersfrom1ton.Writeaprogramthatevaluatesthefactorialsoftheintegersfrom1to5.Printtheresultsintabularformat.Whatdifficultymightpreventyoufromcalculatingthefactorialof20?ANS:1/*Exercise4.14Solution*/2#include34intmain(void)5{6inti;/*outercounter*/7intj;/*innercounter*/8intfactorial;/*currentfactorialvalue*/910printf("XtFactorialofXn");/*displaytableheaders*/1112/*computethefactorialfor1to5*/13for(i=1;i<=5;i++){14factorial=1;1516/*calculatefactorialofcurrentnumber*/17for(j=1;j<=i;j++){18factorial*=j;19}/*endinnerfor*/2021printf("%dt%dn",i,factorial);22}/*endouterfor*/2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/XFactorialofX11223642451204.15ModifythecompoundinterestprogramofSection4.6torepeatitsstepsforinterestratesof5percent,6percent,7percent,8percent,9percent,and10percent.Useaforlooptovarytheinterestrate.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com62CProgramControl:SolutionsChapter4ANS:1/*Exercise4.15Solution*/2#include3#include45intmain(void)6{7intyear;/*yearcounter*/8intrate;/*interestrate*/9doubleamount;/*amountondeposit*/10doubleprincipal=1000.0;/*startingprincipal*/1112/*loopthroughinterestrates5%to10%*/13for(rate=5;rate<=10;rate++){1415/*displaytableheaders*/16printf("InterestRate:%fn",rate/100.0);17printf("%s%21sn","Year","Amountondeposit");1819/*calculateamountondepositforeachoftenyears*/20for(year=1;year<=10;year++){2122/*calculatenewamountforspecifiedyear*/23amount=principal*pow(1+(rate/100.0),year);2425/*outputonetablerow*/26printf("%4d%21.2fn",year,amount);27}/*endfor*/2829printf("n");30}/*endfor*/3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions63InterestRate:0.050000YearAmountondeposit11050.0021102.5031157.6341215.5151276.2861340.1071407.1081477.4691551.33101628.89...InterestRate:0.080000YearAmountondeposit11080.0021166.4031259.7141360.4951469.3361586.8771713.8281850.9391999.00102158.92...InterestRate:0.100000YearAmountondeposit11100.0021210.0031331.0041464.1051610.5161771.5671948.7282143.5992357.95102593.744.16Writeaprogramthatprintsthefollowingpatternsseparatelyonebelowtheother.Useforloopstogeneratethepatterns.Allasterisks(*)shouldbeprintedbyasingleprintfstatementoftheformprintf("*");(thiscausestheasteriskstoprintsidebyside).Hint:Thelasttwopatternsrequirethateachlinebeginwithanappropriatenumberofblanks.](A)(B)(C)(D)*****************************************************************************************************************************************************************************************************************************************ANS:1/*Exercise4.16Solution*/2#include34intmain(void)5{6introw;/*rowcounter*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com64CProgramControl:SolutionsChapter47intcol;/*columncounter*/8intspace;/*spacescounter*/910/*PatternA,loop10timesforrows*/11for(row=1;row<=10;row++){1213/*printrowasterisks*/14for(col=1;col<=row;col++){15printf("*");16}/*endfor*/1718printf("n");19}/*endfor*/2021printf("n");2223/*PatternB,loop10timesforrows24rowcountsdowntocorrespondtonumberofasterisks*/25for(row=10;row>=1;row--){2627/*printrowasterisks*/28for(col=1;col<=row;col++){29printf("*");30}/*endfor*/3132printf("n");33}/*endfor*/3435printf("n");3637/*PatternC,loop10timesforrows38rowcountsdowntocorrespondtonumberofasterisks*/39for(row=10;row>=1;row--){4041/*print(10-row)numberofprecedingspaces*/42for(space=1;space<=10-row;space++){43printf("");44}/*endfor*/4546/*printrowasterisks*/47for(col=1;col<=row;col++){48printf("*");49}/*endfor*/5051printf("n");52}/*endfor*/5354printf("n");5556/*PatternD,loop10timesforrows*/57for(row=1;row<=10;row++){5859/*print(10-row)numberofprecedingspaces*/60for(space=1;space<=10-row;space++){61printf("");62}/*endfor*/6364/*printrowasterisks*/65for(col=1;col<=row;col++){66printf("*");67}/*endfor*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions656869printf("n");70}/*endfor*/7172printf("n");7374return0;/*indicatesuccessfultermination*/7576}/*endmain*/4.17Collectingmoneybecomesincreasinglydifficultduringperiodsofrecession,socompaniesmaytightentheircreditlimitstopreventtheiraccountsreceivable(moneyowedtothem)frombecomingtoolarge.Inresponsetoaprolongedrecession,onecom-panyhascutitscustomer"screditlimitsinhalf.Thus,ifaparticularcustomerhadacreditlimitof$2000,thiscustomer’screditlimitisnow$1000.Ifacustomerhadacreditlimitof$5000,thiscustomer"screditlimitisnow$2500.Writeaprogramthatanalyzesthecreditstatusofthreecustomersofthiscompany.Foreachcustomeryouaregiven:a)Thecustomer’saccountnumberb)Thecustomer’screditlimitbeforetherecessionc)Thecustomer’scurrentbalance(i.e.,theamountthecustomerowesthecompany).Yourprogramshouldcalculateandprintthenewcreditlimitforeachcustomerandshoulddetermine(andprint)whichcus-tomershavecurrentbalancesthatexceedtheirnewcreditlimits.ANS:1/*Exercise4.17Solution*/2#include34intmain(void)5{6intaccount;/*currentaccountnumber*/7inti;/*counter*/8doublelimit;/*currentcreditlimit*/9doublebalance;/*currentbalance*/10doublenewLimit;/*newcreditlimit*/1112/*loopthreetimes*/13for(i=1;i<=3;i++){1415/*getaccountnumber,creditlimitandbalance*/16printf("nEnteraccount,limit,balance:");17scanf("%d%lf%lf",&account,&limit,&balance);1819newLimit=limit/2.0;/*calculatenewlimit*/20printf("Newcreditlimitforaccount%dis%.2fn",account,newLimit);2122/*ifbalanceisgreaterthannewcreditlimit*/23if(balance>newLimit){24printf("Limitexceededforaccount%dn",account);25}/*endif*/2627}/*endfor*/2829return0;/*indicatesuccessfultermination*/3031}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com66CProgramControl:SolutionsChapter4Enteraccount,limit,balance:1004000.002136.87Newcreditlimitforaccount100is2000.00Limitexceededforaccount100Enteraccount,limit,balance:20010500.004927.39Newcreditlimitforaccount200is5250.00Enteraccount,limit,balance:3001000.00750.00Newcreditlimitforaccount300is500.00Limitexceededforaccount3004.18Oneinterestingapplicationofcomputersisdrawinggraphsandbarcharts(sometimescalled“histograms”).Writeapro-gramthatreadsfivenumbers(eachbetween1and30).Foreachnumberread,yourprogramshouldprintalinecontainingthatnum-berofadjacentasterisks.Forexample,ifyourprogramreadsthenumberseven,itshouldprint*******.ANS:1/*Exercise4.18Solution*/2#include34intmain(void)5{6inti;/*outercounter*/7intj;/*innercounter*/8intnumber;/*currentnumber*/910printf("Enter5numbersbetween1and30:");1112/*loop5times*/13for(i=1;i<=5;i++){14scanf("%d",&number);1516/*printasteriskscorrespondingtocurrentinput*/17for(j=1;j<=number;j++){18printf("*");19}/*endfor*/2021printf("n");22}/*endfor*/2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/Enter5numbersbetween1and30:28513247*****************************************************************************©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions674.19Amailorderhousesellsfivedifferentproductswhoseretailpricesareshowninthefollowingtable:ProductnumberRetailprice1$2.982$4.503$9.984$4.495$6.87Writeaprogramthatreadsaseriesofpairsofnumbersasfollows:a)Productnumberb)QuantitysoldforonedayYourprogramshoulduseaswitchstatementtohelpdeterminetheretailpriceforeachproduct.Yourprogramshouldcalculateanddisplaythetotalretailvalueofallproductssoldlastweek.ANS:1/*Exercise4.19Solution*/2#include34intmain(void)5{6intproduct;/*currentproductnumber*/7intquantity;/*quantityofcurrentproductsold*/8doubletotal=0.0;/*currenttotalretailvalue*/910/*promptforinput*/11printf("Enterpairsofitemnumbersandquantities.n");12printf("Enter-1fortheitemnumbertoendinput.n");13scanf("%d",&product);1415/*loopwhilesentinelvaluenotreadfromuser*/16while(product!=-1){17scanf("%d",&quantity);1819/*determineproductnumberandcorrespondingretailprice*/20switch(product){2122case1:23total+=quantity*2.98;/*updatetotal*/24break;2526case2:27total+=quantity*4.50;/*updatetotal*/28break;2930case3:31total+=quantity*9.98;/*updatetotal*/32break;3334case4:35total+=quantity*4.49;/*updatetotal*/36break;3738case5:39total+=quantity*6.87;/*updatetotal*/40break;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com68CProgramControl:SolutionsChapter44142default:43printf("Invalidproductcode:%dn",product);44printf("Quantity:%dn",quantity);45}/*endswitch*/4647scanf("%d",&product);/*getnextinput*/48}/*endwhile*/4950/*displaytotalretailvalue*/51printf("Thetotalretailvaluewas:%.2fn",total);5253return0;/*indicatesuccessfultermination*/5455}/*endmain*/Enterpairsofitemnumbersandquantities.Enter-1fortheitemnumbertoendinput.112131415161Invalidproductcode:6Quantity:111-1Thetotalretailvaluewas:31.804.20Completethefollowingtruthtablesbyfillingineachblankwith0or1ANS:.Condition1Condition2Condition1&&Condition20000nonzero0nonzero00nonzerononzero1Condition1Condition2Condition1||Condition20000nonzero1nonzero01nonzerononzero1Condition1!Condition101nonzero0©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions694.21RewritetheprogramofFig.4.2sothattheinitializationofthevariablecounterisdoneinthedefinitioninsteadoftheforstatement.ANS:1/*Exercise4.21Solution*/2#include34intmain(void)5{6intcounter=1;/*initializecounter*/78/*leavefirststatementempty*/9for(;counter<=10;counter++){10printf("%dn",counter);11}/*endfor*/1213return0;/*indicatesuccessfultermination*/1415}/*endmain*/123456789104.22ModifytheprogramofFig.4.7sothatitcalculatestheaveragegradefortheclass.ANS:1/*Exercise4.22Solution*/2#include34intmain(void)5{6intgrade;/*currentgrade*/7intaCount=0;/*totalagrades*/8intbCount=0;/*totalbgrades*/9intcCount=0;/*totalcgrades*/10intdCount=0;/*totaldgrades*/11intfCount=0;/*totalfgrades*/12doubleaverageGrade;/*averagegradeforclass*/1314/*promptuserforgrades*/15printf("Enterthelettergrades.n");16printf("EntertheEOFcharactertoendinput.n");1718/*loopwhilenotendoffile*/19while((grade=getchar())!=EOF){2021/*determinewhichgradewasinput*/22switch(grade){2324case"A":/*gradewasuppercaseA*/25case"a":/*gradewaslowercasea*/26++aCount;/*updategradeAcounter*/27break;/*exitswitch*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com70CProgramControl:SolutionsChapter42829case"B":/*gradewasuppercaseB*/30case"b":/*gradewaslowercaseb*/31++bCount;/*updategradeBcounter*/32break;/*exitswitch*/3334case"C":/*gradewasuppercaseC*/35case"c":/*gradewaslowercasec*/36++cCount;/*updategradeCcounter*/37break;/*exitswitch*/3839case"D":/*gradewasuppercaseC*/40case"d":/*gradewaslowercasec*/41++dCount;/*updategradeCcounter*/42break;/*exitswitch*/4344case"F":/*gradewasuppercaseC*/45case"f":/*gradewaslowercasec*/46++fCount;/*updategradeCcounter*/47break;/*exitswitch*/4849case"n":/*ignorenewlines,*/50case"t":/*tabs,*/51case"":/*andspacesininput*/52break;/*exitswitch*/5354default:/*catchallothercharacters*/55printf("Incorrectlettergradeentered.");56printf("Enteranewgrade.n");57break;/*optional,willexitswitchanyway*/58}/*endswitch*/5960}/*endwhile*/6162/*outputtotalsforeachgrade*/63printf("nThetotalsforeachlettergradeare:n");64printf("A:%dn",aCount);65printf("B:%dn",bCount);66printf("C:%dn",cCount);67printf("D:%dn",dCount);68printf("F:%dn",fCount);6970/*calculateaveragegrade*/71averageGrade=72(4*aCount+3*bCount+2*cCount+dCount)/73(aCount+bCount+cCount+dCount+fCount);7475/*outputappropriatemessageforaveragegrade*/76if(averageGrade>3.4){77printf("AveragegradeisAn");78}/*endif*/79elseif(averageGrade>2.4){80printf("AveragegradeisBn");81}/*endelseif*/82elseif(averageGrade>1.4){83printf("AveragegradeisCn");84}/*endelseif*/85elseif(averageGrade>0.4){86printf("AveragegradeisDn");87}/*endelseif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions7188else{89printf("AveragegradeisFn");90}/*endelse*/9192return0;/*indicatesuccessfultermination*/9394}/*endmain*/Enterthelettergrades.EntertheEOFcharactertoendinput.ABBBCDFCCCDDDCBBAABCCC^ZThetotalsforeachlettergradeare:A:3B:6C:8D:4F:1AveragegradeisC4.23ModifytheprogramofFig.4.6sothatitusesonlyintegerstocalculatethecompoundinterest.[Hint:Treatallmonetaryamountsasintegralnumbersofpennies.Then“break”theresultintoitsdollarportionandcentsportionbyusingthedivisionandremainderoperations,respectively.Insertaperiod.]ANS:1/*Exercise4.23Solution*/2#include3#include45intmain(void)6{7intyear;/*yearcounter*/8intamount;/*amountondeposit,inpennies*/9intdollars;/*dollarportionofamount*/10intcents;/*centsportionofamount*/11intprincipal=100000;/*startingprincipal,inpennies($1000)*/12doublerate=.05;/*interestrate*/1314/*displayheadersfortable*/15printf("%s%21sn","Year","Amountondeposit");1617/*loop10times*/18for(year=1;year<=10;year++){1920/*determinenewamount(inpennies)*/21amount=principal*pow(1.0+rate,year);2223/*determinecentsportionofamount(lasttwodigits)*/24cents=amount%100;2526/*determinedollarsportionofamount*/27/*integerdivisiontruncatesdecimalplaces*/28dollars=amount/100;2930/*displayyear,dollarportionfollowedbyperiod*/31printf("%4d%18d.",year,dollars);32©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com72CProgramControl:SolutionsChapter433/*displaycentsportion*/34/*ifcentsportiononly1digit,insert0*/35if(cents<10){36printf("0%dn",cents);37}/*endif*/38else{39printf("%dn",cents);40}/*endelse*/4142}/*endfor*/4344return0;/*indicatesuccessfultermination*/4546}/*endmain*/YearAmountondeposit11050.0021102.5031157.6241215.5051276.2861340.0971407.1081477.4591551.32101628.894.24Assumei=1,j=2,k=3andm=2.Whatdoeseachofthefollowingstatementsprint?a)printf("%d",i==1);ANS:1b)printf("%d",j==3);ANS:0c)printf("%d",i>=1&&j<4);ANS:1d)printf("%d",m<=99&&k=i||k==m);ANS:1f)printf("%d",k+m=k);ANS:0g)printf("%d",!m);ANS:0h)printf("%d",!(j-m));ANS:1i)printf("%d",!(k>m));ANS:0j)printf("%d",!(j>k));ANS:14.25Printatableofdecimal,binary,octal,andhexadecimalequivalents.Ifyouarenotfamiliarwiththesenumbersystems,readAppendixEfirstifyouwouldliketoattemptthisexercise.ANS:seeExercise4.34Solution4.26Calculatethevalueofpfromtheinfiniteseries44444p=4–---+++---–------–------¼357911Printatablethatshowsthevalueofpapproximatedbyonetermofthisseries,bytwoterms,bythreeterms,etc.Howmanytermsofthisseriesdoyouhavetousebeforeyoufirstget3.14?3.141?3.1415?3.14159?©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions73ANS:3.14occursatanaccuracyof627,3.141occursatanaccuracyof2458,3.1415occursatanaccuracyaround147,000,and3.14159occursatanaccuracyaround319,000.1/*Exercise4.26Solution*/2#include34intmain(void)5{6longdoublepi=0.0;/*approximatedvalueforpi*/7longdoublenum=4.0;/*numerator*/8longdoubledenom=1.0;/*denominatorofcurrentterm*/9longintloop;/*loopcounter*/10longintaccuracy;/*numberofterms*/1112accuracy=400000;/*setdecimalaccuracy*/1314/*displaytableheaders*/15printf("Accuracysetat:%ldn",accuracy);16printf("termttpin");1718/*loopthrougheachterm*/19for(loop=1;loop<=accuracy;loop++){2021/*ifodd-numberedterm,addcurrentterm*/22if(loop%2!=0){23pi+=num/denom;24}/*endif*/25else{/*ifeven-numberedterm,subtractcurrentterm*/26pi-=num/denom;27}/*endelse*/2829/*displaynumberoftermsandapproximated30valueforpiwith8digitsofprecision*/31printf("%ldtt%Lfn",loop,pi);3233denom+=2.0;/*updatedenominator*/3435}/*endfor*/3637return0;/*indicatesuccessfultermination*/3839}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com74CProgramControl:SolutionsChapter4Accuracysetat:400000termpi14.00000022.66666733.46666742.89523853.33968362.976046...9953.1425989963.1405899973.1425969983.1405919993.142594...3999983.1415903999993.1415954000003.1415904.27(PythagoreanTriples)Arighttrianglecanhavesidesthatareallintegers.ThesetofthreeintegervaluesforthesidesofarighttriangleiscalledaPythagoreantriple.Thesethreesidesmustsatisfytherelationshipthatthesumofthesquaresoftwoofthesidesisequaltothesquareofthehypotenuse.FindallPythagoreantriplesforside1,side2,andthehypotenuseallnolargerthan500.Useatriple-nestedforloopthatsimplytriesallpossibilities.Thisisanexampleof“bruteforce”computing.Itisnotaesthet-icallypleasingtomanypeople.Buttherearemanyreasonswhythesetechniquesareimportant.First,withcomputingpowerin-creasingatsuchaphenomenalpace,solutionsthatwouldhavetakenyearsorevencenturiesofcomputertimetoproducewiththetechnologyofjustafewyearsagocannowbeproducedinhours,minutesorevenseconds.Recentmicroprocessorchipscanprocessabillioninstructionspersecond!Second,asyouwilllearninmoreadvancedcomputersciencecourses,therearelargenumbersofinterestingproblemsforwhichthereisnoknownalgorithmicapproachotherthansheerbruteforce.Weinvestigatemanykindsofproblem-solvingmethodologiesinthisbook.Wewillconsidermanybruteforceapproachestovariousinterestingproblems.ANS:1/*Exercise4.27Solution*/2#include34intmain(void)5{6intcount=0;/*numberoftriplesfound*/7longintside1;/*side1valuecounter*/8longintside2;/*side2valuecounter*/9longinthypotenuse;/*hypotenusevaluecounter*/10longinthyptSquared;/*hypotenusesquared*/11longintsidesSquared;/*sumofsquaresofsides*/1213/*side1valuesrangefrom1to500*/14for(side1=1;side1<=500;side1++){1516/*side2valuesrangefromcurrentside1to500*/17for(side2=1;side2<=500;side2++){1819/*hypotenusevaluesrangefromcurrentside2to500*/20for(hypotenuse=1;hypotenuse<=500;hypotenuse++){2122/*calculatesquareofhypotenusevalue*/23hyptSquared=hypotenuse*hypotenuse;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions752425/*calculatesumofsquaresofsides*/26sidesSquared=side1*side1+side2*side2;2728/*ifhypotenusesquared=side1squared+side2squared,29Pythagoreantriple*/30if(hyptSquared==sidesSquared){3132/*displaytriple*/33printf("%ld%ld%ldn",side1,side2,hypotenuse);34++count;/*updatecount*/35}/*endif*/3637}/*endfor*/3839}/*endfor*/4041}/*endfor*/4243/*displaytotalnumberoftriplesfound*/44printf("Atotalof%dtripleswerefound.n",count);4546return0;/*indicatesuccessfultermination*/4748}/*endmain*/345435512136810724258610...47693485480314814808848848010849248014050048344485Atotalof772tripleswerefound.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com76CProgramControl:SolutionsChapter44.28Acompanypaysitsemployeesasmanagers(whoreceiveafixedweeklysalary),hourlyworkers(whoreceiveafixedhour-lywageforuptothefirst40hourstheyworkand“time-and-a-half”—i.e.,1.5timestheirhourlywage—forovertimehoursworked),commissionworkers(whoreceivea$250plus5.7%oftheirgrossweeklysales),orpieceworkers(whoreceiveafixedamountofmoneyperitemforeachoftheitemstheyproduce—eachpieceworkerinthiscompanyworksononlyonetypeofitem).Writeaprogramtocomputetheweeklypayforeachemployee.Youdonotknowthenumberofemployeesinadvance.Eachtypeofem-ployeehasitsownpaycode:Managershavepaycode1,hourlyworkershavecode2,commissionworkershavecode3andpiece-workershavecode4.Useaswitchtocomputeeachemployee’spaybasedonthatemployee’spaycode.Withintheswitch,prompttheuser(i.e.,thepayrollclerk)toentertheappropriatefactsyourprogramneedstocalculateeachemployee’spaybasedonthatemployee’spaycode.ANS:1/*Exercise4.28Solution*/2#include34intmain(void)5{6intpayCode;/*currentemployee"spaycode*/7intmanagers=0;/*totalnumberofmanagers*/8inthWorkers=0;/*totalnumberofhourlyworkers*/9intcWorkers=0;/*totalnumberofcommissionworkers*/10intpWorkers=0;/*totalnumberofpieceworkers*/11intpieces;/*currentpieceworker"snumberofpieces*/12doublemSalary;/*manager"ssalary*/13doublehSalary;/*hourlyworker"ssalary*/14doublecSalary;/*commissionworker"ssalary*/15doublepSalary;/*pieceworker"ssalary*/16doublehours;/*totalhoursworked*/17doubleotPay;/*overtimepay*/18doubleotHours;/*overtimehours*/19doublepay;/*currentemployee"sweeklypay*/2021/*promptforfirstemployeeinput*/22printf("Enterpaycode(-1toend):");23scanf("%d",&payCode);2425/*loopwhilesentinelvaluenotreadfromuser*/26while(payCode!=-1){2728/*switchtoappropriatecomputationaccordingtopaycode*/29switch(payCode){3031/*paycode1correspondstomanager*/32case1:3334/*promptforweeklysalary*/35printf("Managerselected.n");36printf("Enterweeklysalary:");37scanf("%lf",&mSalary);3839/*manager"spayisweeklysalary*/40printf("Themanager"spayis$%.2fn",mSalary);4142++managers;/*updatetotalnumberofmanagers*/43break;/*exitswitch*/4445/*paycode2correspondstohourlyworker*/46case2:4748/*promptforhourlysalary*/49printf("Hourlyworkerselected.n");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions7750printf("Enterthehourlysalary:");51scanf("%lf",&hSalary);5253/*promptfornumberofhoursworked*/54printf("Enterthetotalhoursworked:");55scanf("%lf",&hours);5657/*payfixedforupto40hours,1.5forhoursover40*/58if(hours>40.0){5960/*calculateOThoursandtotalpay*/61otHours=hours-40.0;62otPay=hSalary*1.5*otHours+hSalary*40.0;6364printf("Workerhasworked%.1fovertimehours.n",otHours);65printf("Workerspayis$%.2fn",otPay);66}/*endif*/67else{/*noovertime*/68pay=hSalary*hours;69printf("Worker"spayis$%.2fn",pay);70}/*endelse*/7172++hWorkers;/*updatetotalnumberofhourlyworkers*/73break;/*exitswitch*/7475/*paycode3correspondstocommissionworker*/76case3:7778/*promptforgrossweeklysales*/79printf("Commissionworkerselected.n");80printf("Entergrossweeklysales:");81scanf("%lf",&cSalary);8283/*pay$250plus5.7%ofgrossweeklysales*/84pay=250.0+0.057*cSalary;85printf("CommissionWorker"spayis$%.2fn",pay);8687++cWorkers;/*updatetotalnumberofcommissionworkers*/88break;/*exitswitch*/8990/*paycode4correspondstopieceworker*/91case4:9293/*promptfornumberofpieces*/94printf("Pieceworkerselected.nEnternumberofpieces:");95scanf("%d",&pieces);9697/*promptforwageperpiece*/98printf("Enterwageperpiece:");99scanf("%lf",&pSalary);100101pay=pieces*pSalary;/*computepay*/102printf("PieceWorker"spayis$%.2fn",pay);103104++pWorkers;/*updatetotalnumberofpieceworkers*/105break;/*exitswitch*/106107/*defaultcase*/108default:109printf("Invalidpaycode.n");110break;111}/*endswitch*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com78CProgramControl:SolutionsChapter4112113/*promptfornextemployeeinput*/114printf("nEnterpaycode(-1toend):");115scanf("%d",&payCode);116}/*endwhile*/117118/*displaytotalcountsforeachtypeofemployee*/119printf("n");120printf("Totalnumberofmanagerspaid:%dn",managers);121printf("Totalnumberofhourlyworkerspaid:%dn",hWorkers);122printf("Totalnumberofcommissionworkerspaid:%dn",cWorkers);123printf("Totalnumberofpieceworkerspaid:%dn",pWorkers);124125return0;/*indicatesuccessfultermination*/126127}/*endmain*/Enterpaycode(-1toend):4Pieceworkerselected.Enternumberofpieces:200Enterwageperpiece:20PieceWorker"spayis$4000.00Enterpaycode(-1toend):-1Totalnumberofmanagerspaid:0Totalnumberofhourlyworkerspaid:0Totalnumberofcommissionworkerspaid:0Totalnumberofpieceworkerspaid:1Enterpaycode(-1toend):1Managerselected.Enterweeklysalary:2500Themanager"spayis$2500.00Enterpaycode(-1toend):2Hourlyworkerselected.Enterthehourlysalary:10.50Enterthetotalhoursworked:75Workerhasworked35.0overtimehours.Workerspayis$971.25Enterpaycode(-1toend):3Commissionworkerselected.Entergrossweeklysales:9000CommissionWorker"spayis$763.00Enterpaycode(-1toend):4Pieceworkerselected.Enternumberofpieces:200Enterwageperpiece:20PieceWorker"spayis$4000.00Enterpaycode(-1toend):-1Totalnumberofmanagerspaid:1Totalnumberofhourlyworkerspaid:1Totalnumberofcommissionworkerspaid:1Totalnumberofpieceworkerspaid:1©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions794.29(DeMorgan’sLaws)Inthischapter,wediscussedthelogicaloperators&&,||,and!.DeMorgan’sLawscansometimesmakeitmoreconvenientforustoexpressalogicalexpression.Theselawsstatethattheexpression!(condition1&&condition2)islogicallyequivalenttotheexpression(!condition1||!condition2).Also,theexpression!(condition1||condition2)islogicallyequivalenttotheexpression(!condition1&&!condition2).UseDeMorgan’sLawstowriteequivalentexpressionsforeachofthefollowing,andthenwriteaprogramtoshowthatboththeoriginalexpressionandthenewexpressionineachcaseareequivalent.a)!(x<5)&&!(y>=7)b)!(a==b)||!(g!=5)c)!((x<=8)&&(y>4))d)!((i>4)||(j<=6))ANS:1/*Exercise4.29Solution*/2#include34intmain(void)5{6intx=10;/*definecurrentvariablevalue*/7inty=1;/*definecurrentvariablevalue*/8inta=3;/*definecurrentvariablevalue*/9intb=3;/*definecurrentvariablevalue*/10intg=5;/*definecurrentvariablevalue*/11intY=1;/*definecurrentvariablevalue*/12inti=2;/*definecurrentvariablevalue*/13intj=9;/*definecurrentvariablevalue*/1415/*displayvariablevalues*/16printf("currentvariablevaluesare:n");17printf("x=%d,y=%d,a=%d,",x,y,a);18printf("b=%dn",b);19printf("g=%d,Y=%d,i=%d,",g,Y,i);20printf("j=%dnn",j);2122/*parta*/23if((!(x<5)&&!(y>=7))==(!((x<5)||(y>=7)24))){25printf("!(x<5)&&!(y>=7)isequivalentto"26"!((x<5)||(y>=7))n");27}/*endif*/28else{29printf("!(x<5)&&!(y>=7)isnotequivalentto"30"!((x<5)||(y>=7))n");31}/*endelse*/3233/*partb*/34if((!(a==b)||!(g!=5))==(!((a==b)&&(g!=5)35))){36printf("!(a==b)||!(g!=5)isequivalentto"37"!((a==b)&&(g!=5))n");38}/*endif*/39else{40printf("!(a==b)||!(g!=5)isnotequivalentto"41"!((a==b)&&(g!=5))n");42}/*endelse*/4344/*partc*/45if(!((x<=8)&&(Y>4))==(!(x<=8)||!(Y>4)46)){47printf("!((x<=8)&&(Y>4))isequivalentto"48"(!(x<=8)||!(Y>4))n");49}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com80CProgramControl:SolutionsChapter450else{51printf("!((x<=8)&&(Y>4))isnotequivalentto"52"(!(x<=8)||!(Y>4))n");53}/*endelse*/5455/*partd*/56if(!((i>4)||(j<=6))==(!(i>4)&&!(j<=6)57)){58printf("!((i>4)||(j<=6))isequivalentto"59"(!(i>4)&&!(j<=6))n");60}/*endif*/61else{62printf("!((i>4)||(j<=6))isnotequivalentto"63"(!(i>4)&&!(j<=6))n");64}/*endelse*/6566return0;/*indicatesuccessfultermination*/6768}/*endmain*/currentvariablevaluesare:x=10,y=1,a=3,b=3g=5,Y=1,i=2,j=9!(x<5)&&!(y>=7)isequivalentto!((x<5)||(y>=7))!(a==b)||!(g!=5)isequivalentto!((a==b)&&(g!=5))!((x<=8)&&(Y>4))isequivalentto(!(x<=8)||!(Y>4))!((i>4)||(j<=6))isequivalentto(!(i>4)&&!(j<=6))4.30RewritetheprogramofFig.4.7byreplacingtheswitchstatementwithanestedif…elsestatement;becarefultodealwiththedefaultcaseproperly.Thenrewritethisnewversionbyreplacingthenestedif…elsestatementwithaseriesofifstatements;here,too,becarefultodealwiththedefaultcaseproperly(thisismoredifficultthaninthenestedif…elseversion).Thisexercisedemonstratesthatswitchisaconvenienceandthatanyswitchstatementcanbewrittenwithonlysingle-selectionstatements.1/*Exercise4.30PartASolution*/2#include34intmain(void)5{6intgrade;/*currentgrade*/7intaCount=0;/*totalAgrades*/8intbCount=0;/*totalBgrades*/9intcCount=0;/*totalCgrades*/10intdCount=0;/*totalDgrades*/11intfCount=0;/*totalFgrades*/1213/*promptuserforgrades*/14printf("Enterthelettergrades.");15printf("EntertheEOFcharactertoendinput:n");1617/*whileEOFnotenteredbyuser*/18while((grade=getchar())!=EOF){1920/*Updatecountforappropriategrade*/21if(grade=="A"||grade=="a"){22++aCount;23}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions8124elseif(grade=="B"||grade=="b"){25++bCount;26}/*endelseif*/27elseif(grade=="C"||grade=="c"){28++cCount;29}/*endelseif*/30elseif(grade=="D"||grade=="d"){31++dCount;32}/*endelseif*/33elseif(grade=="F"||grade=="f"){34++fCount;35}/*endelseif*/36elseif(grade=="n"||grade==""){37;/*emptybody*/38}/*endelseif*/39else{40printf("Incorrectlettergradeentered.");41printf("Enteranewgrade.n");42}/*endelse*/4344}/*endwhile*/4546/*displaytotalsforeachgrade*/47printf("nTotalsforeachlettergradewere:n");48printf("A:%dn",aCount);49printf("B:%dn",bCount);50printf("C:%dn",cCount);51printf("D:%dn",dCount);52printf("F:%dn",fCount);5354return0;/*indicatesuccessfultermination*/5556}/*endmain*/Enterthelettergrades.EntertheEOFcharactertoendinput:AcbdeIncorrectlettergradeentered.Enteranewgrade.f^ZTotalsforeachlettergradewere:A:1B:1C:1D:1F:11/*Exercise4.30PartBSolution*/2#include34intmain(void)5{6intgrade;/*currentgrade*/7intaCount=0;/*totalAgrades*/8intbCount=0;/*totalBgrades*/9intcCount=0;/*totalCgrades*/10intdCount=0;/*totalDgrades*/11intfCount=0;/*totalFgrades*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com82CProgramControl:SolutionsChapter41213/*promptuserforgrades*/14printf("Enterthelettergrades.");15printf("EntertheEOFcharactertoendinput:n");1617/*whileEOFnotenteredbyuser*/18while((grade=getchar())!=EOF){1920/*updatecountforappropriategrade*/21if(grade=="A"||grade=="a"){22++aCount;23}/*endif*/2425if(grade=="B"||grade=="b"){26++bCount;27}/*endif*/2829if(grade=="C"||grade=="c"){30++cCount;31}/*endif*/3233if(grade=="D"||grade=="d"){34++dCount;35}/*endif*/3637if(grade=="F"||grade=="f"){38++fCount;39}/*endif*/4041if(grade=="n"||grade==""){42;/*emptybody*/43}/*endif*/4445/*default*/46if(grade!="a"&&grade!="A"&&47grade!="B"&&grade!="b"&&48grade!="c"&&grade!="C"&&49grade!="d"&&grade!="d"&&50grade!="f"&&grade!="F"&&51grade!="n"&&grade!=""){5253printf("Incorrectlettergradeentered.");54printf("Enteranewgrade.n");55}/*endif*/5657}/*endwhile*/5859/*displaytotalsforeachgrade*/60printf("nTotalsforeachlettergradewere:n");61printf("A:%dn",aCount);62printf("B:%dn",bCount);63printf("C:%dn",cCount);64printf("D:%dn",dCount);65printf("F:%dn",fCount);6667return0;/*indicatesuccessfultermination*/6869}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions83Enterthelettergrades.EntertheEOFcharactertoendinput:AbcsIncorrectlettergradeentered.Enteranewgrade.df^ZTotalsforeachlettergradewere:A:1B:1C:1D:1F:14.31Writeaprogramthatprintsthefollowingdiamondshape.Youmayuseprintfstatementsthatprinteitherasingleasterisk(*)orasingleblank.Maximizeyouruseofrepetition(withnestedforstatements)andminimizethenumberofprintfstatements.*****************************************ANS:1/*Exercise4.31Solution*/2#include34intmain(void)5{6intline;/*linecounter*/7intspace;/*spacecounter*/8intasterisk;/*asteriskcounter*/910/*tophalf*/11for(line=1;line<=9;line+=2){1213/*printprecedingspaces*/14for(space=(9-line)/2;space>0;space--){15printf("");16}/*endfor*/1718/*printasterisks*/19for(asterisk=1;asterisk<=line;asterisk++){20printf("*");21}/*endfor*/2223printf("n");24}/*endfor*/2526/*bottomhalf*/27for(line=7;line>=0;line-=2){2829/*printprecedingspaces*/30for(space=(9-line)/2;space>0;space--){31printf("");32}/*endfor*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com84CProgramControl:SolutionsChapter43334/*printasterisks*/35for(asterisk=1;asterisk<=line;asterisk++){36printf("*");37}/*endfor*/3839printf("n");40}/*endfor*/4142return0;/*indicatesuccessfultermination*/4344}/*endmain*/4.32ModifytheprogramyouwroteinExercise4.31toreadanoddnumberintherange1to19tospecifythenumberofrowsinthediamond.Yourprogramshouldthendisplayadiamondoftheappropriatesize.ANS:1/*Exercise4.32Solution*/2#include34intmain(void)5{6intline;/*linecounter*/7intspace;/*spacecounter*/8intasterisk;/*asteriskcounter*/9intsize;/*numberofrowsindiamond*/1011/*promptfordiamondsize*/12printf("Enteranoddnumberforthediamondsize(1-19):n");13scanf("%d",&size);1415/*tophalf*/16for(line=1;line<=size-2;line+=2){1718/*printprecedingspaces*/19for(space=(size-line)/2;space>0;space--){20printf("");21}/*endfor*/2223/*printasterisks*/24for(asterisk=1;asterisk<=line;asterisk++){25printf("*");26}/*endfor*/2728printf("n");29}/*endfor*/3031/*bottomhalf*/32for(line=size;line>=0;line-=2){3334/*printprecedingspaces*/35for(space=(size-line)/2;space>0;space--){36printf("");37}/*endfor*/3839/*printasterisks*/40for(asterisk=1;asterisk<=line;asterisk++){41printf("*");42}/*endfor*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions854344printf("n");45}/*endfor*/4647return0;/*indicatesuccessfultermination*/4849}/*endmain*/Enteranoddnumberforthediamondsize(1-19):13*************************************************************************************4.33WriteaprogramthatprintsatableofalltheRomannumeralequivalentsofthedecimalnumbersintherange1to100.ANS:1/*Exercise4.33Solution*/2#include34intmain(void)5{6intloop;/*loopcounter*/7intdiv;/*tensdigit*/8intmod;/*onesdigit*/910/*displaytableheaders*/11printf("RomannNumeralttDecimaln");1213/*loop100times*/14for(loop=1;loop<=100;loop++){15div=loop/10;/*separatetensdigit*/16mod=loop%10;/*separateonesdigit*/1718/*switchstructurefortensdigit*/19switch(div){2021/*printappropriateRomannumeralfortensdigit*/22case0:23break;2425case1:26printf("X");27break;/*exitswitch*/2829case2:30printf("XX");31break;/*exitswitch*/3233case3:34printf("XXX");35break;/*exitswitch*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com86CProgramControl:SolutionsChapter43637case4:38printf("XL");39break;/*exitswitch*/4041case5:42printf("L");43break;/*exitswitch*/4445case6:46printf("LX");47break;/*exitswitch*/4849case7:50printf("LXX");51break;/*exitswitch*/5253case8:54printf("LXXX");55break;/*exitswitch*/5657case9:58printf("XC");59break;/*exitswitch*/6061case10:62printf("C");63break;/*exitswitch*/6465default:66break;/*exitswitch*/67}/*endswitch*/6869/*switchstructureforonesdigit*/70switch(mod){7172/*printappropriateRomannumeralforonesdigit*/73case0:74printf("tt%4dn",div*10);75break;/*exitswitch*/7677case1:78printf("Itt%4dn",div*10+mod);79break;/*exitswitch*/8081case2:82printf("IItt%4dn",div*10+mod);83break;/*exitswitch*/8485case3:86printf("IIItt%4dn",div*10+mod);87break;/*exitswitch*/8889case4:90printf("IVtt%4dn",div*10+mod);91break;/*exitswitch*/9293case5:94printf("Vtt%4dn",div*10+mod);95break;/*exitswitch*/96©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions8797case6:98printf("VItt%4dn",div*10+mod);99break;/*exitswitch*/100101case7:102printf("VIItt%4dn",div*10+mod);103break;/*exitswitch*/104105case8:106printf("VIIItt%4dn",div*10+mod);107break;/*exitswitch*/108109case9:110printf("IXtt%4dn",div*10+mod);111break;/*exitswitch*/112113case10:114printf("Xtt%4dn",div*10+mod);115break;/*exitswitch*/116117default:118break;/*exitswitch*/119}/*endswitch*/120121}/*endfor*/122123return0;/*indicatesuccessfultermination*/124125}/*endmain*/RomanNumeralDecimalI1II2III3IV4V5VI6VII7VIII8IX9X10...LXXXIX89XC90XCI91XCII92XCIII93XCIV94XCV95XCVI96XCVII97XCVIII98XCIX99C100©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com88CProgramControl:SolutionsChapter44.34Writeaprogramthatprintsatableofthebinary,octalandhexadecimalequivalentsofthedecimalnumbersintherange1through256.Ifyouarenotfamiliarwiththesenumbersystems,readAppendixEbeforeyouattemptthisexercise.ANS:1/*Exercise4.34Solution*/2#include34intmain(void)5{6intloop;/*loopcounter*/7intnumber;/*currentnumber*/8inttemp1;/*temporaryinteger*/910/*printtableheaders*/11printf("DecimalttBinaryttOctalttHexadecimaln");1213/*loopthroughvalues1to256*/14for(loop=1;loop<=256;loop++){15printf("%dtt",loop);16number=loop;1718/*binarynumbers*/19printf("%c",number==256?"1":"0");2021printf("%c",number<256&&number>=128?"1":"0");22number%=128;2324printf("%c",number<128&&number>=64?"1":"0");25number%=64;2627printf("%c",number<64&&number>=32?"1":"0");28number%=32;2930printf("%c",number<32&&number>=16?"1":"0");31number%=16;3233printf("%c",number<16&&number>=8?"1":"0");34number%=8;3536printf("%c",number<8&&number>=4?"1":"0");37number%=4;3839printf("%c",number<4&&number>=2?"1":"0");40number%=2;4142printf("%ct",number==1?"1":"0");4344/*octalnumbers*/45number=loop;4647printf("%d",number<512&&number>=64?number/64:0);48number%=64;4950printf("%d",number<64&&number>=8?number/8:0);51number%=8;5253printf("%dtt",number==0?0:number);5455/*hexadecimalnumbers*/56number=loop;57temp1=16;58©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions8959if(number<4096&&number>=256){60printf("%d",number/256);61}/*endif*/6263if(number<256&&number>=16){64temp1=number/16;65number%=16;66}/*endif*/67else{68printf("0");69}/*endelse*/7071/*converttoletteriftemp1isabove9*/72if(temp1<=9){73printf("%d",temp1);74}/*endif*/75elseif(temp1>=10&&temp1<=15){76printf("%c","A"+(temp1-10));77}/*endelseif*/7879/*converttoletterifnumberisabove9*/80if(number<=9){81printf("%d",number);82}/*endif*/83elseif(number>=10&&number<=15){84printf("%c","A"+(number-10));85}/*endelseif*/8687printf("n");88}/*endfor*/8990return0;/*indicatesuccessfultermination*/9192}/*endmain*/DecimalBinaryOctalHexadecimal100000000100101200000001000202300000001100303400000010000404500000010100505600000011000606700000011100707800000100001008900000100101109100000010100120A...250011111010372FA251011111011373FB252011111100374FC253011111101375FD254011111110376FE255011111111377FF25610000000040010F©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com90CProgramControl:SolutionsChapter44.35Describetheprocessyouwouldusetoreplaceado…whileloopwithanequivalentwhileloop.Whatproblemoccurswhenyoutrytoreplaceawhileloopwithanequivalentdo…whileloop?Supposeyouhavebeentoldthatyoumustremoveawhileloopandreplaceitwithado…while.Whatadditionalcontrolstatementwouldyouneedtouseandhowwouldyouuseittoensurethattheresultingprogrambehavesexactlyastheoriginal?ANS:Thebodyofado…whileloopbecomesthebodyofawhileloop,andthecontentsofthebodyarerepeatedbeforethewhileloop.Inado…whileloop,thebodyisexecutedatleastonce,whereasexecutionofthebodyinawhileloopdependsonthecontinuationcondition.Replacingawhileloopwithado…whilelooprequiresanifselectionstatement.Thedo…whileloopwouldbethebodyoftheifstatementandtheconditionwouldbethesameastheloopcontinuationconditioninthedo…while.4.36Writeaprogramthatinputstheyearintherange1994through1999andusesfor-looprepetitiontoproduceacondensed,neatlyprintedcalendar.Watchoutforleapyears.ANS:1/*Exercise4.36Solution*/2/*Thisisasimplecalendersolution,thatdoes*/3/*notaccountfortheshiftingofdatesfrom*/4/*yeartoyear.*/56#include78intmain(void)9{10intyear;/*currentyear*/11intleapYear;/*leapyear,1=yes,0=no*/12intdays;/*totaldaysincurrentmonth*/13intmonth;/*currentmonth*/14intspace;/*spacecounter*/15intdayPosition;/*startingdaypositionofyear*/16intdayNum;/*counterfordaysofthemonth*/1718/*loopuntilinputisvalid*/19do{20printf("Enteracalendaryearbetween1994and1999:");21scanf("%d",&year);22}while(year<1994||year>1999);/*enddo...while*/2324/*determinestartingdayposition*/25switch(year){2627case1994:28dayPosition=7;29break;/*exitswitch*/3031case1995:32dayPosition=1;33break;/*exitswitch*/3435case1996:36dayPosition=2;37break;/*exitswitch*/3839case1997:40dayPosition=4;41break;/*exitswitch*/4243case1998:44dayPosition=5;45break;/*exitswitch*/46©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions9147case1999:48dayPosition=6;49break;/*exitswitch*/50}/*endswitch*/5152/*checkforleapyears*/53if(year%400==0){54leapYear=1;55}/*endif*/56elseif(year%4==0&&year%100!=0){57leapYear=1;58}/*endelseif*/59else{60leapYear=0;61}/*endelse*/6263/*loopthroughmonthsandprintcalendar*/64for(month=1;month<=12;month++){6566/*beginwiththemonth*/67switch(month){6869case1:70printf("nnJanuary%dn",year);71days=31;72break;/*exitswitch*/7374case2:75printf("nnFebruary%dn",year);76days=leapYear==1?29:28;77break;/*exitswitch*/7879case3:80printf("nnMarch%dn",year);81days=31;82break;/*exitswitch*/8384case4:85printf("nnApril%dn",year);86days=30;87break;/*exitswitch*/8889case5:90printf("nnMay%dn",year);91days=31;92break;/*exitswitch*/9394case6:95printf("nnJune%dn",year);96days=30;97break;/*exitswitch*/9899case7:100printf("nnJuly%dn",year);101days=31;102break;/*exitswitch*/103104case8:105printf("nnAugust%dn",year);106days=31;107break;/*exitswitch*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com92CProgramControl:SolutionsChapter4108109case9:110printf("nnSeptember%dn",year);111days=30;112break;/*exitswitch*/113114case10:115printf("nnOctober%dn",year);116days=31;117break;/*exitswitch*/118119case11:120printf("nnNovember%dn",year);121days=30;122break;/*exitswitch*/123124case12:125printf("nnDecember%dn",year);126days=31;127break;/*exitswitch*/128}/*endswitch*/129130printf("SMTWRFSn");/*printheads*/131132/*movetoproperspacetobeginprintingmonth*/133for(space=1;space34intmain(void)5{6intx;/*loopcounter*/7intbreakOut=1;/*breakoutcondition*/89/*testforbreakoutcondition*/10for(x=1;x<=10&&breakOut==1;x++){1112/*breakoutofloopafterx=4*/13if(x==4){14breakOut=-1;15}/*endif*/1617printf("%d",x);18}/*endfor*/1920printf("nBrokeoutofloopatx=%dn",x);2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com94CProgramControl:SolutionsChapter41234Brokeoutofloopatx=54.38Whatdoesthefollowingprogramsegmentdo?1for(i=1;i<=5;i++){2for(j=1;j<=3;j++){3for(k=1;k<=4;k++)4printf("*");5printf("n");6}7printf("n");8}ANS:************************************************************4.39Describeingeneralhowyouwouldremoveanycontinuestatementfromaloopinaprogramandreplacethatstatementwithsomestructuredequivalent.UsethetechniqueyoudevelopedheretoremovethecontinuestatementfromtheprogramofFig.4.12.ANS:1/*Exercise4.39Solution*/2#include34intmain(void)5{6intx;/*loopcounter*/78/*loop10times*/9for(x=1;x<=10;x++){1011/*ifx==5,skiptonextinteration*/12if(x==5){13++x;14}/*endif*/1516printf("%d",x);17}/*endfor*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter4CProgramControl:Solutions951819printf("nUsed++xtoskipprintingthevalue5n");2021return0;/*indicatesuccessfultermination*/2223}/*endmain*/1234678910Used++xtoskipprintingthevalue5©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com96CProgramControl:SolutionsChapter4©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com5CFunctions:SolutionsSOLUTIONS5.8Showthevalueofxaftereachofthefollowingstatementsisperformed:a)x=fabs(7.5);ANS:7.5b)x=floor(7.5);ANS:7.0c)x=fabs(0.0);ANS:0.0d)x=ceil(0.0);ANS:0.0e)x=fabs(-6.4);ANS:6.4f)x=ceil(-6.4);ANS:-6.0g)x=ceil(-fabs(-8+floor(-5.5)));ANS:-14.05.9Aparkinggaragechargesa$2.00minimumfeetoparkforuptothreehours.Thegaragechargesanadditional$0.50perhourforeachhourorpartthereofinexcessofthreehours.Themaximumchargeforanygiven24-hourperiodis$10.00.Assumethatnocarparksforlongerthan24hoursatatime.Writeaprogramthatwillcalculateandprinttheparkingchargesforeachof3customerswhoparkedtheircarsinthisgarageyesterday.Youshouldenterthehoursparkedforeachcustomer.Yourprogramshouldprinttheresultsinaneattabularformat,andshouldcalculateandprintthetotalofyesterday"sreceipts.TheprogramshouldusethefunctioncalculateChargestodeterminethechargeforeachcustomer.Youroutputsshouldappearinthefollowingfor-mat:Enterthehoursparkedfor3cars:1.54.024.0CarHoursCharge11.52.0024.02.50324.010.00TOTAL29.514.50©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com98CFunctions:SolutionsChapter5ANS:1/*Exercise5.9Solution*/2#include3#include45doublecalculateCharges(doublehours);/*functionprototype*/67intmain()8{9doubleh;/*numberofhoursforcurrentcar*/10doublecurrentCharge;/*parkingchargeforcurrentcar*/11doubletotalCharges=0.0;/*totalcharges*/12doubletotalHours=0.0;/*totalnumberofhours*/13inti;/*loopcounter*/14intfirst=1;/*flagforprintingtableheaders*/1516printf("Enterthehoursparkedfor3cars:");1718/*loop3timesfor3cars*/19for(i=1;i<=3;i++){20scanf("%lf",&h);21totalHours+=h;/*addcurrenthourstototalhours*/2223/*iffirsttimethroughloop,displayheaders*/24if(first){25printf("%5s%15s%15sn","Car","Hours","Charge");2627/*setflagtofalsetopreventfromprintingagain*/28first=0;29}/*endif*/3031/*calculatecurrentcar"schargeandupdatetotal*/32totalCharges+=(currentCharge=calculateCharges(h));3334/*displayrowdataforcurrentcar*/35printf("%5d%15.1f%15.2fn",i,h,currentCharge);36}/*endfor*/3738/*displayrowdatafortotals*/39printf("%5s%15.1f%15.2fn","TOTAL",totalHours,totalCharges);4041return0;/*indicatesuccessfultermination*/4243}/*endmain*/4445/*calculateChargesreturnschargeaccordingtonumberofhours*/46doublecalculateCharges(doublehours)47{48doublecharge;/*calculatedcharge*/4950/*$2forupto3hours*/51if(hours<3.0){52charge=2.0;53}/*endif*/5455/*$.50foreachhourorpartthereofinexcessof3hours*/56elseif(hours<19.0){57charge=2.0+.5*ceil(hours-3.0);58}/*endelseif*/59else{/*maximumcharge$10*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions9960charge=10.0;61}/*endelse*/6263returncharge;/*returncalculatedcharge*/6465}/*endfunctioncalculateCharges*/5.10Anapplicationoffunctionfloorisroundingavaluetothenearestinteger.Thestatementy=floor(x+.5);willroundthenumberxtothenearestinteger,andassigntheresulttoy.Writeaprogramthatreadsseveralnumbersandusestheprecedingstatementtoroundeachofthesenumberstothenearestinteger.Foreachnumberprocessed,printboththeoriginalnum-berandtheroundednumber.ANS:1/*Exercise5.10Solution*/2#include3#include45voidcalculateFloor(void);/*functionprototype*/67intmain()8{9calculateFloor();/*callfunctioncalculateFloor*/1011return0;/*indicatesuccessfultermination*/1213}/*endmain*/1415/*calculateFloorrounds5inputs*/16voidcalculateFloor(void)17{18doublex;/*currentinput*/19doubley;/*currentinputrounded*/20intloop;/*loopcounter*/2122/*loopfor5inputs*/23for(loop=1;loop<=5;loop++){24printf("Enterafloatingpointvalue:");25scanf("%lf",&x);2627/*yholdsroundedinput*/28y=floor(x+.5);29printf("%froundedis%.1fnn",x,y);30}/*endfor*/3132}/*endfunctioncalculateFloor*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com100CFunctions:SolutionsChapter5Enterafloatingpointvalue:1.51.500000roundedis2.0Enterafloatingpointvalue:5.555.550000roundedis6.0Enterafloatingpointvalue:73.234123143273.234123roundedis73.0Enterafloatingpointvalue:9.09.000000roundedis9.0Enterafloatingpointvalue:44.000000roundedis4.05.11Functionfloormaybeusedtoroundanumbertoaspecificdecimalplace.Thestatementy=floor(x*10+.5)/10;roundsxtothetenthsposition(thefirstpositiontotherightofthedecimalpoint).Thestatementy=floor(x*100+.5)/100;roundsxtothehundredthsposition(i.e.,thesecondpositiontotherightofthedecimalpoint).Writeaprogramthatdefinesfourfunctionstoroundanumberxinvariouswaysa)roundToInteger(number)b)roundToTenths(number)c)roundToHundreths(number)d)roundToThousandths(number)Foreachvalueread,yourprogramshouldprinttheoriginalvalue,thenumberroundedtothenearestinteger,thenumberroundedtothenearesttenth,thenumberroundedtothenearesthundredth,andthenumberroundedtothenearestthousandth.ANS:1/*Exercise5.11Solution*/2#include3#include45doubleroundToInteger(doublen);/*functionprototype*/6doubleroundToTenths(doublen);/*functionprototype*/7doubleroundToHundredths(doublen);/*functionprototype*/8doubleroundToThousandths(doublen);/*functionprototype*/910intmain()11{12inti;/*loopcounter*/13intcount;/*numberofvaluestoprocess*/14doublenumber;/*currentinput*/1516printf("Howmanynumbersdoyouwanttoprocess?");17scanf("%d",&count);1819/*loopforinputs*/20for(i=0;i3#include45doublehypotenuse(doubles1,doubles2);/*functionprototype*/67intmain()8{9inti;/*loopcounter*/10doubleside1;/*valueforfirstside*/11doubleside2;/*valueforsecondside*/1213/*loop3times*/14for(i=1;i<=3;i++){15printf("Enterthesidesofthetriangle:");16scanf("%lf%lf",&side1,&side2);1718/*calculateanddisplayhypotenusevalue*/19printf("Hypotenuse:%.1fnn",hypotenuse(side1,side2));20}/*endfor*/2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/2526/*hypotenusecalculatesvalueofhypotenuseof27arighttrianglegiventwosidevalues*/28doublehypotenuse(doubles1,doubles2)29{30returnsqrt(pow(s1,2)+pow(s2,2));3132}/*endfunctionhypotenuse*/Enterthesidesofthetriangle:3.04.0Hypotenuse:5.0Enterthesidesofthetriangle:5.012.0Hypotenuse:13.0Enterthesidesofthetriangle:8.015.0Hypotenuse:17.0©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com104CFunctions:SolutionsChapter55.16WriteafunctionintegerPower(base,exponent)thatreturnsthevalueofbaseexponentForexample,integerPower(3,4)=3*3*3*3.Assumethatexponentisapositive,nonzerointeger,andbaseisaninte-ger.FunctionintegerPowershouldusefortocontrolthecalculation.Donotuseanymathlibraryfunctions.ANS:1/*Exercise5.16Solution*/2#include34intintegerPower(intb,inte);56intmain()7{8intexp;/*integerexponent*/9intbase;/*integerbase*/1011printf("Enterintegerbaseandexponent:");12scanf("%d%d",&base,&exp);1314printf("%dtothepower%dis:%dn",15base,exp,integerPower(base,exp));1617return0;/*indicatesuccessfultermination*/1819}/*endmain*/2021/*integerPowercalculatesandreturnsbraisedtotheepower*/22intintegerPower(intb,inte)23{24intproduct=1;/*resultingproduct*/25inti;/*loopcounter*/2627/*multiplyproducttimesb(erepetitions)*/28for(i=1;i<=e;i++){29product*=b;30}/*endfor*/3132returnproduct;/*returnresultingproduct*/3334}/*endfunctionintegerPower*/Enterintegerbaseandexponent:535tothepower3is:125©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1055.17Writeafunctionmultiplethatdeterminesforapairofintegerswhetherthesecondintegerisamultipleofthefirst.Thefunctionshouldtaketwointegerargumentsandreturn1(true)ifthesecondisamultipleofthefirst,and0(false)otherwise.Usethisfunctioninaprogramthatinputsaseriesofpairsofintegers.ANS:1/*Exercise5.17Solution*/2#include34intmultiple(inta,intb);/*functionprototype*/56intmain()7{8intx;/*firstinteger*/9inty;/*secondinteger*/10inti;/*loopcounter*/1112/*loop3times*/13for(i=1;i<=3;i++){14printf("Entertwointegers:");15scanf("%d%d",&x,&y);1617/*determineifsecondismultipleoffirst*/18if(multiple(x,y)){19printf("%disamultipleof%dnn",y,x);20}/*endif*/21else{22printf("%disnotamultipleof%dnn",y,x);23}/*endelse*/2425}/*endfor*/2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/3031/*multipledeterminesifbismultipleofa*/32intmultiple(inta,intb)33{34return!(b%a);3536}/*endfunctionmultiple*/Entertwointegers:21010isamultipleof2Entertwointegers:51717isnotamultipleof5Entertwointegers:3696696isamultipleof3©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com106CFunctions:SolutionsChapter55.18Writeaprogramthatinputsaseriesofintegersandpassesthemoneatatimetofunctionevenwhichusestheremainderoperatortodetermineifanintegeriseven.Thefunctionshouldtakeanintegerargumentandreturn1iftheintegerisevenand0otherwise.ANS:1/*Exercise5.18Solution*/2#include34inteven(inta);/*functionprototype*/56intmain()7{8intx;/*currentinput*/9inti;/*loopcounter*/1011/*loopfor3inputs*/12for(i=1;i<=3;i++){13printf("Enteraninteger:");14scanf("%d",&x);1516/*determineifinputiseven*/17if(even(x)){18printf("%disanevenintegernn",x);19}/*endif*/20else{21printf("%disnotanevenintegernn",x);22}/*endelse*/2324}/*endfor*/2526return0;/*indicatesuccessfultermination*/2728}/*endmain*/2930/*evenreturnstrueifaiseven*/31inteven(inta)32{33return!(a%2);3435}/*endfunctioneven*/Enteraninteger:77isnotanevenintegerEnteraninteger:66isanevenintegerEnteraninteger:1000010000isaneveninteger©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1075.19Writeafunctionthatdisplaysattheleftmarginofthescreenasolidsquareofasteriskswhosesideisspecifiedinintegerparameterside.Forexample,ifsideis4,thefunctiondisplays:Enterside:4****************ANS:1/*Exercise5.19Solution*/2#include34voidsquare(ints);/*functionprototype*/56intmain()7{8intside;/*inputsidelength*/910printf("Enterside:");11scanf("%d",&side);1213square(side);/*displaysolidsquareofasterisks*/1415return0;/*indicatesuccessfultermination*/1617}/*endmain*/1819/*squaredisplayssolidsquareofasteriskswithspecifiedside*/20voidsquare(ints)21{22inti;/*outerloopcounter*/23intj;/*innerloopcounter*/2425/*loopsidetimesfornumberofrows*/26for(i=1;i<=s;i++){2728/*loopsidetimesfornumberofcolumns*/29for(j=1;j<=s;j++){30printf("*");31}/*endfor*/3233printf("n");34}/*endfor*/3536}/*endfunctionsquare*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com108CFunctions:SolutionsChapter55.20ModifythefunctioncreatedinExercise5.19toformthesquareoutofwhatevercharacteriscontainedincharacterparam-eterfillCharacter.Thusifsideis5andfillCharacteris“#”thenthisfunctionshouldprint:Enteracharacterandthesidelength:#5#########################ANS:1/*Exercise5.20Solution*/2#include34voidsquare(intside,charfillCharacter);/*functionprototype*/56intmain()7{8ints;/*sidelength*/9charc;/*fillcharacter*/1011printf("Enteracharacterandthesidelength:");12scanf("%c%d",&c,&s);1314square(s,c);/*displaysolidsquareofinputcharacter*/1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/1920/*squaredisplayssolidsquareoffillCharacterwithspecifiedside*/21voidsquare(intside,charfillCharacter)22{23intloop;/*outerloopcounter*/24intloop2;/*innerloopcounter*/2526/*loopsidetimesfornumberofrows*/27for(loop=1;loop<=side;loop++){2829/*loopsidetimesfornumberofcolumns*/30for(loop2=1;loop2<=side;loop2++){31printf("%c",fillCharacter);32}/*endfor*/3334printf("n");35}/*endfor*/3637}/*endfunctionsquare*/5.21UsetechniquessimilartothosedevelopedinExercises5.19and5.20toproduceaprogramthatgraphsawiderangeofshapes.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1095.22Writeprogramsegmentsthataccomplisheachofthefollowing:a)Calculatetheintegerpartofthequotientwhenintegeraisdividedbyintegerb.b)Calculatetheintegerremainderwhenintegeraisdividedbyintegerb.c)Usetheprogrampiecesdevelopedina)andb)towriteafunctionthatinputsanintegerbetween1and32767andprintsitasaseriesofdigits,eachpairofwhichisseparatedbytwospaces.Forexample,theinteger4562shouldbeprintedas:4562ANS:1/*Exercise5.22Solution*/2#include34intquotient(inta,intb);/*functionprototype*/5intremainder(inta,intb);/*functionprototype*/67intmain()8{9intnumber;/*inputnumber*/10intdivisor=10000;/*currentdivisor*/1112printf("Enteranintegerbetween1and32767:");13scanf("%d",&number);1415printf("Thedigitsinthenumberare:n");1617/*determineandprinteachdigit*/18while(number>=10){1920/*ifnumberis>=currentdivisor,determinedigit*/21if(number>=divisor){2223/*usequotienttodeterminecurrentdigit*/24printf("%d",quotient(number,divisor));2526/*updatenumbertoberemainder*/27number=remainder(number,divisor);2829/*updatedivisorfornextdigit*/30divisor=quotient(divisor,10);31}/*endif*/32else{/*ifnumber3#include45/*functionprototype*/6unsignedseconds(unsignedh,unsignedm,unsigneds);78intmain()9{10inthours;/*currenttime"shours*/11intminutes;/*currenttime"sminutes*/12intsecs;/*currenttime"sseconds*/13intfirst;/*firsttime,inseconds*/14intsecond;/*secondtime,inseconds*/15intdifference;/*differencebetweentwotimes,inseconds*/1617printf("Enterthefirsttimeasthreeintegers:");18scanf("%d%d%d",&hours,&minutes,&secs);1920/*calculatefirsttimeinseconds*/21first=seconds(hours,minutes,secs);2223printf("Enterthesecondtimeasthreeintegers:");24scanf("%d%d%d",&hours,&minutes,&secs);2526/*calculatesecondtimeinseconds*/27second=seconds(hours,minutes,secs);2829/*calculatedifference*/30difference=fabs(first-second);3132/*displaydifference*/33printf("Thedifferencebetweenthetimesis%dsecondsn",34difference);3536return0;/*indicatesuccessfultermination*/3738}/*endmain*/3940/*secondsreturnsnumberofsecondssinceclock"struck12"41giveninputtimeashoursh,minutesm,secondss*/42unsignedseconds(unsignedh,unsignedm,unsigneds)43{44return3600*h+60*m+s;4546}/*endfunctionseconds*/Enterthefirsttimeasthreeintegers:42039Enterthesecondtimeasthreeintegers:72039Thedifferencebetweenthetimesis10800seconds©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com112CFunctions:SolutionsChapter55.24Implementthefollowingintegerfunctions:a)FunctioncelsiusreturnstheCelsiusequivalentofaFahrenheittemperature.b)FunctionfahrenheitreturnstheFahrenheitequivalentofaCelsiustemperature.c)UsethesefunctionstowriteaprogramthatprintschartsshowingtheFahrenheitequivalentsofallCelsiustemperaturesfrom0to100degrees,andtheCelsiusequivalentsofallFahrenheittemperaturesfrom32to212degrees.Printtheout-putsinaneattabularformatthatminimizesthenumberoflinesofoutputwhileremainingreadable.ANS:1/*Exercise5.24Solution*/2#include34intcelcius(intfTemp);/*functionprototype*/5intfahrenheit(intcTemp);/*functionprototype*/67intmain()8{9inti;/*loopcounter*/1011/*displaytableofFahrenheitequivalentsofCelsiustemperature*/12printf("FahrenheitequivalentsofCelciustemperatures:n");13printf("CelciusttFahrenheitn");1415/*displayFahrenheitequivalentsofCelsius0to100*/16for(i=0;i<=100;i++){17printf("%dtt%dn",i,fahrenheit(i));18}/*endfor*/1920/*displaytableofCelsiusequivalentsofFahrenheittemperature*/21printf("nCelciusequivalentsofFahrenheittemperatures:n");22printf("FahrenheittCelciusn");2324/*displayCelsiusequivalentsofFahrenheit32to212*/25for(i=32;i<=212;i++){26printf("%dtt%dn",i,celcius(i));27}/*endfor*/2829return0;/*indicatesuccessfultermination*/3031}/*endmain*/3233/*celsiusreturnsCelsiusequivalentoffTemp,34giveninFahrenheit*/35intcelcius(intfTemp)36{37return(int)(5.0/9.0*(fTemp-32));3839}/*endfunctioncelsius*/4041/*fahrenheitreturnsFahrenheitequivalentofcTemp,42giveninCelsius*/43intfahrenheit(intcTemp)44{45return(int)(9.0/5.0*cTemp+32);4647}/*endfunctionfahrenheit*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions113FahrenheitequivalentsofCelciustemperatures:CelciusFahrenheit032133235337439541642744846948...CelciusequivalentsofFahrenheittemperatures:FahrenheitCelcius320330341351362372383393404415...©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com114CFunctions:SolutionsChapter55.25Writeafunctionthatreturnsthesmallestofthreefloatingpointnumbers.ANS:1/*Exercise5.25Solution*/2#include34/*functionprototype*/5doublesmallest3(doublea,doubleb,doublec);67intmain()8{9doublex;/*firstinput*/10doubley;/*secondinput*/11doublez;/*thirdinput*/1213printf("Enterthreedoubleingpointvalues:");14scanf("%lf%lf%lf",&x,&y,&z);1516/*determinesmallestvalue*/17printf("Thesmallestvalueis%fn",smallest3(x,y,z));1819return0;/*indicatesuccessfultermination*/2021}/*endmain*/2223/*smallest3returnsthesmallestofa,bandc*/24doublesmallest3(doublea,doubleb,doublec)25{26doublesmallest=a;/*assumeaisthesmallest*/2728if(b34intperfect(intvalue);/*functionprototype*/56intmain()7{8intj;/*loopcounter*/910printf("Fortheintegersfrom1to1000:n");1112/*loopfrom2to1000*/13for(j=2;j<=1000;j++){1415/*ifcurrentintegerisperfect*/16if(perfect(j)){17printf("%disperfectn",j);18}/*endif*/1920}/*endfor*/2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/2526/*perfectreturnstrueifvalueisperfectinteger,27i.e.,ifvalueisequaltosumofitsfactors*/28intperfect(intvalue)29{30intfactorSum=1;/*currentsumoffactors*/31inti;/*loopcounter*/3233/*loopthroughpossiblefactorvalues*/34for(i=2;i<=value/2;i++){3536/*ifiisfactor*/37if(value%i==0){38factorSum+=i;/*addtosum*/39}/*endif*/4041}/*endfor*/4243/*returntrueifvalueisequaltosumoffactors*/44if(factorSum==value){45return1;46}/*endif*/47else{48return0;49}/*endelse*/5051}/*endfunctionperfect*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com116CFunctions:SolutionsChapter5Fortheintegersfrom1to1000:6isperfect28isperfect496isperfect©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1175.27Anintegerissaidtobeprimeifitisdivisibleonlyby1anditself.Forexample,2,3,5and7areprime,but4,6,8and9arenot.a)Writeafunctionthatdeterminesifanumberisprime.b)Usethisfunctioninaprogramthatdeterminesandprintsalltheprimenumbersbetween1and10,000.Howmanyofthese10,000numbersdoyoureallyhavetotestbeforebeingsurethatyouhavefoundalltheprimes?c)Initiallyyoumightthinkthatn/2istheupperlimitforwhichyoumusttesttoseeifanumberisprime,butyouneedonlygoashighasthesquarerootofn.Why?Rewritetheprogram,andrunitbothways.Estimatetheperformanceimprovement.ANS:1/*Exercise5.27SolutionPartBSolution*/2#include34intprime(intn);56intmain()7{8intloop;/*loopcounter*/9intcount=0;/*totalnumberofprimesfound*/1011printf("Theprimenumbersfrom1to10000are:n");1213/*loopthrough1to10000*/14for(loop=1;loop<=10000;loop++){1516/*ifcurrentnumberisprime*/17if(prime(loop)){18++count;19printf("%6d",loop);2021/*newlineafter10valuesdisplayed*/22if(count%10==0){23printf("n");24}/*endif*/2526}/*endif*/2728}/*endfor*/2930return0;/*indicatesuccessfultermination*/3132}/*endmain*/3334/*primereturns1ifnisprime*/35intprime(intn)36{37intloop2;/*loopcounter*/3839/*loopthroughpossiblefactors*/40for(loop2=2;loop2<=n/2;loop2++){4142/*iffactorfound,notprime*/43if(n%loop2==0){44return0;45}/*endif*/4647}/*endfor*/4849return1;/*return1ifprime*/5051}/*endfunctionprime*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com118CFunctions:SolutionsChapter5Theprimenumbersfrom1to10000are:12357111317192329313741434753596167717379838997101103107109113127131137139149151157163167...9733973997439749976797699781978797919803981198179829983398399851985798599871988398879901990799239929993199419949996799731/*Exercise5.27PartCSolution*/2#include3#include45intprime(intn);/*functionprototype*/67intmain()8{9intj;/*loopcounter*/10intcount=0;/*totalnumberofprimesfound*/1112printf("Theprimenumbersfrom1to10000are:n");1314/*loopthroughnumbers1to10000*/15for(j=1;j<=10000;j++){1617/*ifcurrentnumberprime*/18if(prime(j)){19++count;20printf("%5d",j);2122/*newlineafter10valuesdisplayed*/23if(count%10==0){24printf("n");25}/*endif*/2627}/*endif*/2829}/*endfor*/3031return0;/*indicatesuccessfultermination*/3233}/*endmain*/3435/*primereturns1ifnisprime*/36intprime(intn)37{38inti;/*loopcounter*/3940/*loopthroughpossiblefactors*/41for(i=2;i<=(int)sqrt(n);i++){4243/*iffactorfound,notprime*/44if(n%i==0){45return0;46}/*endif*/4748}/*endfor*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1194950return1;5152}/*endfunctionprime*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com120CFunctions:SolutionsChapter55.28Writeafunctionthattakesanintegervalueandreturnsthenumberwithitsdigitsreversed.Forexample,giventhenumber7631,thefunctionshouldreturn1367.ANS:1/*Exercise5.28Solution*/2#include34intreverseDigits(intn);56intmain()7{8intnumber;/*inputnumber*/910printf("Enteranumberbetween1and9999:");11scanf("%d",&number);1213/*findnumberwithdigitsreversed*/14printf("Thenumberwithitsdigitsreversedis:%dn",15reverseDigits(number));1617return0;/*indicatesuccessfultermination*/1819}/*endmain*/2021/*reverseDigitsreturnsnumberobtainedby22reversingdigitsofn*/23intreverseDigits(intn)24{25intreverse=0;/*reversednumber*/26intdivisor=1000;/*currentdivisor*/27intmultiplier=1;/*currentmultiplier*/2829/*loopuntilsingle-digitnumber*/30while(n>9){3132/*ifn>=currentdivisor,determinedigit*/33if(n>=divisor){3435/*updatereversednumberwithcurrentdigit*/36reverse+=n/divisor*multiplier;3738n%=divisor;/*updaten*/39divisor/=10;/*updatedivisor*/40multiplier*=10;/*updatemultiplier*/41}/*endif*/42else{/*else,nodigit*/43divisor/=10;/*updatedivisor*/44}/*endelse*/4546}/*endwhile*/4748reverse+=n*multiplier;4950returnreverse;/*returnreversednumber*/5152}/*endfunctionreverseDigits*/Enteranumberbetween1and9999:6Thenumberwithitsdigitsreversedis:6©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions121Enteranumberbetween1and9999:9273Thenumberwithitsdigitsreversedis:3729©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com122CFunctions:SolutionsChapter55.29Thegreatestcommondivisor(GCD)oftwointegersisthelargestintegerthatevenlydivideseachofthetwonumbers.Writefunctiongcdthatreturnsthegreatestcommondivisoroftwointegers.ANS:1/*Exercise5.29Solution*/2#include34intgcd(intx,inty);/*functionprototype*/56intmain()7{8intj;/*loopcounter*/9inta;/*firstnumber*/10intb;/*secondnumber*/1112/*loopfor5pairsofinputs*/13for(j=1;j<=5;j++){14printf("Entertwointegers:");15scanf("%d%d",&a,&b);1617/*findgreatestcommondivisorofaandb*/18printf("Thegreatestcommondivisor"19"of%dand%dis%dnn",a,b,gcd(a,b));20}/*endfor*/2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/2526/*gcdfindgreatestcommondivisorofxandy*/27intgcd(intx,inty)28{29inti;30intgreatest=1;/*currentgcd,1isminimum*/3132/*loopfrom2tosmallerofxandy*/33for(i=2;i<=((x34intqualityPoints(intaverage);/*functionprototype*/56intmain()7{8intaverage;/*currentaverage*/9intloop;/*loopcounter*/1011/*loopfor5inputs*/12for(loop=1;loop<=5;loop++){13printf("nEnterthestudent"saverage:");14scanf("%d",&average);1516/*determineanddisplaycorrespondingqualitypoints*/17printf("%dona4pointscaleis%dn",18average,qualityPoints(average));19}/*endfor*/2021return0;/*indicatesuccessfultermination*/2223}/*endmain*/2425/*qualityPointstakesaverageinrange0to100and26returnscorrespondingqualitypointson0to4scale*/27intqualityPoints(intaverage)28{2930/*90<=average<=100*/31if(average>=90){32return4;33}/*endif*/34elseif(average>=80){/*80<=average<=89*/35return3;36}/*endelseif*/37elseif(average>=70){/*70<=average<=79*/38return2;39}/*endelseif*/40elseif(average>=60){/*60<=average<=69*/41return1;42}/*endelseif*/43else{/*0<=average<60*/44return0;45}/*endelse*/4647}/*endfunctionqualityPoints*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions125Enterthestudent"saverage:9292ona4pointscaleis4Enterthestudent"saverage:8787ona4pointscaleis3Enterthestudent"saverage:7575ona4pointscaleis2Enterthestudent"saverage:6363ona4pointscaleis1Enterthestudent"saverage:2222ona4pointscaleis0©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com126CFunctions:SolutionsChapter55.31Writeaprogramthatsimulatescointossing.ForeachtossofthecointheprogramshouldprintHeadsorTails.Lettheprogramtossthecoin100times,andcountthenumberoftimeseachsideofthecoinappears.Printtheresults.Theprogramshouldcallaseparatefunctionflipthattakesnoargumentsandreturns0fortailsand1forheads.[Note:Iftheprogramrealisticallysim-ulatesthecointossing,theneachsideofthecoinshouldappearapproximatelyhalfthetimeforatotalofapproximately50headsand50tails.]ANS:1/*Exercise5.31Solution*/2#include3#include4#include56intflip();/*functionprototype*/78intmain()9{10intloop;/*loopcounter*/11intheadCount=0;/*totalHeadscount*/12inttailCount=0;/*totalTailscount*/1314srand(time(NULL));/*seedrandomnumbergenerator*/1516/*simulatecointoss100times*/17for(loop=1;loop<=100;loop++){1819/*simulatecointoss,0referstotails*/20if(flip()==0){21tailCount++;/*updateTailscount*/22}/*endif*/23else{24headCount++;/*updateHeadscount*/25}/*endelse*/2627if(loop%10==0){28printf("n");29}/*endif*/3031}/*endfor*/3233/*displaytotals*/34printf("nThetotalnumberofHeadswas%dn",headCount);35printf("ThetotalnumberofTailswas%dn",tailCount);3637return0;/*indicatesuccessfultermination*/3839}/*endmain*/4041/*flipusesrandomnumbertosimulatecointoss*/42intflip(){43intHorT=rand()%2;/*scaleby2forbinaryresult*/4445/*displayresultofflip*/46if(HorT==0){47printf("Tails");48}/*endif*/49else{50printf("Heads");51}/*endelse*/5253returnHorT;/*returnresultofcointoss*/5455}/*endfunctionflip*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions127TailsHeadsTailsTailsTailsTailsHeadsTailsTailsTailsTailsTailsTailsHeadsTailsHeadsTailsTailsHeadsTailsTailsHeadsHeadsTailsTailsHeadsTailsTailsTailsTailsTailsTailsHeadsHeadsHeadsHeadsHeadsHeadsTailsTailsHeadsHeadsHeadsHeadsHeadsTailsTailsTailsTailsTailsTailsTailsTailsHeadsHeadsTailsTailsTailsTailsHeadsTailsTailsTailsHeadsHeadsTailsTailsHeadsTailsTailsHeadsTailsTailsHeadsTailsTailsTailsTailsHeadsTailsTailsTailsTailsTailsHeadsTailsHeadsHeadsTailsTailsHeadsTailsTailsHeadsTailsTailsHeadsTailsTailsTailsThetotalnumberofHeadswas34ThetotalnumberofTailswas66©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com128CFunctions:SolutionsChapter55.32Computersareplayinganincreasingroleineducation.Writeaprogramthatwillhelpanelementaryschoolstudentlearnmultiplication.Userandtoproducetwopositiveone-digitintegers.Itshouldthentypeaquestionsuchas:Howmuchis6times7?Thestudentthentypestheanswer.Yourprogramchecksthestudent"sanswer.Ifitiscorrect,print"Verygood!"andthenaskanothermultiplicationquestion.Iftheansweriswrong,print"No.Pleasetryagain."andthenletthestudenttrythesamequestionagainrepeatedlyuntilthestudentfinallygetsitright.ANS:1/*Exercise5.32solution*/2#include3#include4#include56voidmultiplication(void);/*functionprototype*/78intmain(void)9{10srand(time(NULL));/*seedrandomnumbergenerator*/11multiplication();/*beginmultiplicationpractice*/1213return0;/*indicatesuccessfultermination*/1415}/*endmain*/1617/*multiplicationproducespairsofrandomnumbersand18promptsuserforproduct*/19voidmultiplication(void)20{21intx;/*firstfactor*/22inty;/*secondfactor*/23intresponse=0;/*userresponseforproduct*/2425/*usesentinel-controlledrepetition*/26printf("Enter-1toend.n");2728/*loopwhilesentinelvaluenotreadfromuser*/29while(response!=-1){30x=rand()%10;/*generate1-digitrandomnumber*/31y=rand()%10;/*generateanother1-digitrandomnumber*/3233printf("Howmuchis%dtimes%d?",x,y);34scanf("%d",&response);3536/*loopwhilenotsentinelvalueorcorrectresponse*/37while(response!=-1&&response!=x*y){38printf("No.Pleasetryagain.n?");39scanf("%d",&response);40}/*endwhile*/4142/*correctresponse*/43if(response!=-1){44printf("Verygood!nn");45}/*endif*/4647}/*endwhile*/4849printf("That"sallfornow.Bye.n");5051}/*endfunctionmultiplication*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions129Enter-1toend.Howmuchis0times7?0Verygood!Howmuchis0times0?0Verygood!Howmuchis2times6?18No.Pleasetryagain.?12Verygood!Howmuchis5times0?0Verygood!Howmuchis9times2?18Verygood!Howmuchis6times1?-1That"sallfornow.Bye.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com130CFunctions:SolutionsChapter55.33Theuseofcomputersineducationisreferredtoascomputer-assistedinstruction(CAI).OneproblemthatdevelopsinCAIenvironmentsisstudentfatigue.Thiscanbeeliminatedbyvaryingthecomputer"sdialoguetoholdthestudent"sattention.ModifytheprogramofExercise5.32sothevariouscommentsareprintedforeachcorrectanswerandeachincorrectanswerasfollows:ResponsestoacorrectanswerVerygood!Excellent!Nicework!Keepupthegoodwork!ResponsestoanincorrectanswerNo.Pleasetryagain.Wrong.Tryoncemore.Don"tgiveup!No.Keeptrying.Usetherandomnumbergeneratortochooseanumberfrom1to4toselectanappropriateresponsetoeachanswer.Useaswitchstatementwithprintfstatementstoissuetheresponses.ANS:1/*Exercise5.33Solution*/2#include3#include4#include56voidcorrectMessage(void);/*functionprototype*/7voidincorrectMessage(void);/*functionprototype*/8voidmultiplication(void);/*functionprototype*/910intmain()11{12srand(time(NULL));/*seedrandomnumbergenerator*/13multiplication();/*beginmultiplicationpractice*/1415return0;/*indicatesuccessfultermination*/1617}/*endmain*/1819/*correctMessagerandomlychoosesresponsetocorrectanswer*/20voidcorrectMessage(void)21{2223/*generaterandomnumberbetween0and3*/24switch(rand()%4){2526/*displayarandomresponse*/27case0:28printf("Verygood!nn");29break;/*exitswitch*/3031case1:32printf("Excellent!nn");33break;/*exitswitch*/3435case2:36printf("Nicework!nn");37break;/*exitswitch*/3839case3:40printf("Keepupthegoodwork!nn");41break;/*exitswitch*/42}/*endswitch*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1314344}/*endfunctioncorrectMessage*/4546/*incorrectMessagerandomlychoosesresponsetoincorrectanswer*/47voidincorrectMessage(void)48{4950/*generaterandomnumberbetween0and3*/51switch(rand()%4){5253/*displayrandomresponse*/54case0:55printf("No.Pleasetryagain.n?");56break;/*exitswitch*/5758case1:59printf("Wrong.Tryoncemore.n?");60break;/*exitswitch*/6162case2:63printf("Don"tgiveup!n?");64break;/*exitswitch*/6566case3:67printf("No.Keeptrying.n?");68break;/*exitswitch*/69}/*endswitch*/7071}/*endfunctionincorrectMessage*/7273/*multiplicationproducespairsofrandomnumbersand74promptsuserforproduct*/75voidmultiplication(void)76{77intx;/*firstfactor*/78inty;/*secondfactor*/79intresponse=0;/*userresponseforproduct*/8081/*usesentinel-controlledrepetition*/82printf("Enter-1toend.n");8384/*loopwhilesentinelvaluenotreadfromuser*/85while(response!=-1){86x=rand()%10;/*generate1-digitrandomnumber*/87y=rand()%10;/*generateanother1-digitrandomnumber*/8889printf("Howmuchis%dtimes%d?",x,y);90scanf("%d",&response);9192/*loopwhilenotsentinelvalueorcorrectresponse*/93while(response!=-1&&response!=x*y){94incorrectMessage();95scanf("%d",&response);96}/*endwhile*/9798/*correctresponse*/99if(response!=-1){100correctMessage();101}/*endif*/102103}/*endwhile*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com132CFunctions:SolutionsChapter5104105printf("That"sallfornow.Bye.n");106}/*endfunctionmultiplication*/Enter-1toend.Howmuchis7times6?42Verygood!Howmuchis8times5?40Excellent!Howmuchis7times2?15No.Pleasetryagain.?14Keepupthegoodwork!Howmuchis9times6?54Keepupthegoodwork!Howmuchis3times7?-1That"sallfornow.Bye.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1335.34Moresophisticatedcomputer-aidedinstructionssystemsmonitorthestudent’sperformanceoveraperiodoftime.Thede-cisiontobeginanewtopicisoftenbasedonthestudent"ssuccesswithprevioustopics.ModifytheprogramofExercise5.33tocountthenumberofcorrectandincorrectresponsestypedbythestudent.Afterthestudenttypes10answers,yourprogramshouldcalculatethepercentageofcorrectresponses.Ifthepercentageislowerthan75percent,yourprogramshouldprint"Pleaseaskyourinstructorforextrahelp"andthenterminate.ANS:1/*Exercise5.34Solution*/2#include3#include4#include56voidmultiplication(void);/*functionprototype*/7voidcorrectMessage(void);/*functionprototype*/8voidincorrectMessage(void);/*functionprototype*/910intmain()11{12srand(time(NULL));/*seedrandomnumbergenerator*/13multiplication();/*beginmultiplicationpractice*/1415return0;/*indicatesuccessfultermination*/1617}/*endmain*/1819/*multiplicationproducespairsofrandomnumbersand20promptsuserforproduct*/21voidmultiplication(void)22{23inti;/*loopcounter*/24intx;/*firstfactor*/25inty;/*secondfactor*/26intresponse;/*userresponseforproduct*/27intright=0;/*totalnumberofrightresponses*/28intwrong=0;/*totalnumberofwrongresponses*/2930/*loop10times*/31for(i=1;i<=10;i++){32x=rand()%10;/*generate1-digitrandomnumber*/33y=rand()%10;/*generateanother1-digitrandomnumber*/3435printf("Howmuchis%dtimes%d?",x,y);36scanf("%d",&response);3738/*loopwhilenotcorrectresponse*/39while(response!=x*y){40wrong++;/*updatetotalnumberofwrongresponses*/41incorrectMessage();42scanf("%d",&response);43}/*endwhile*/4445right++;/*updatetotalnumberofcorrectresponses*/46correctMessage();47}/*endfor*/4849/*determineifhelpisneeded*/50if((double)right/(right+wrong)<.75){51printf("Pleaseaskyourinstructorforextrahelp.n");52}/*endif*/53©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com134CFunctions:SolutionsChapter554printf("That"sallfornow.Bye.n");55}/*endfunctionmultiplication*/5657/*correctMessagerandomlychoosesresponsetocorrectanswer*/58voidcorrectMessage(void)59{6061/*generaterandomnumberbetween0and3*/62switch(rand()%4){6364/*displayrandomresponse*/65case0:66printf("Verygood!nn");67break;/*exitswitch*/6869case1:70printf("Excellent!nn");71break;/*exitswitch*/7273case2:74printf("Nicework!nn");75break;/*exitswitch*/7677case3:78printf("Keepupthegoodwork!nn");79break;/*exitswitch*/80}/*endswitch*/8182}/*endfunctioncorrectMessage*/8384/*incorrectMessagerandomlychoosesresponsetoincorrectanswer*/85voidincorrectMessage(void)86{8788/*generaterandomnumberbetween0and3*/89switch(rand()%4){9091/*displayrandomresponse*/92case0:93printf("No.Pleasetryagain.n?");94break;/*exitswitch*/9596case1:97printf("Wrong.Tryoncemore.n?");98break;/*exitswitch*/99100case2:101printf("Don"tgiveup!n?");102break;/*exitswitch*/103104case3:105printf("No.Keeptrying.n?");106break;/*exitswitch*/107}/*endswitch*/108109}/*endfunctionincorrectMessage*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions135Howmuchis3times9?27Excellent!Howmuchis1times3?3Verygood!Howmuchis8times1?8Verygood!Howmuchis3times6?24No.Pleasetryagain.?18Excellent!...Howmuchis1times9?9Verygood!Howmuchis4times0?4Wrong.Tryoncemore.?0Excellent!Howmuchis5times8?40Nicework!That"sallfornow.Bye.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com136CFunctions:SolutionsChapter55.35WriteaCprogramthatplaysthegameof“guessthenumber”asfollows:Yourprogramchoosesthenumbertobeguessedbyselectinganintegeratrandomintherange1to1000.Theprogramthentypes:Ihaveanumberbetween1and1000.Canyouguessmynumber?Pleasetypeyourfirstguess.Theplayerthentypesafirstguess.Theprogramrespondswithoneofthefollowing:1.Excellent!Youguessedthenumber!Wouldyouliketoplayagain(yorn)?2.Toolow.Tryagain.3.Toohigh.Tryagain.Iftheplayer’sguessisincorrect,yourprogramshouldloopuntiltheplayerfinallygetsthenumberright.YourprogramshouldkeeptellingtheplayerToohighorToolowtohelptheplayer“zeroin”onthecorrectanswer.[Note:Thesearchingtechniqueemployedinthisproblemiscalledbinarysearch.Wewillsaymoreaboutthisinthenextproblem.]ANS:1/*Exercise5.35solution*/2#include3#include4#include56voidguessGame(void);/*functionprototype*/78intmain()9{10srand(time(NULL));/*seedrandomnumbergenerator*/11guessGame();1213return0;/*indicatesuccessfultermination*/1415}/*endmain*/1617/*guessGamegeneratesnumbersbetween1and100018andchecksuser"sguess*/19voidguessGame(void)20{21intx;/*randomlygeneratednumber*/22intguess;/*user"sguess*/23intresponse;/*responsetocontinuegame,1=yes,2=no*/2425/*loopuntilusertypes2toquitgame*/26do{2728/*generaterandomnumberbetween1and1000291isshift,1000isscalingfactor*/30x=1+rand()%1000;3132/*promptforguess*/33printf("nIhaveanumberbetween1and1000.n");34printf("Canyouguessmynumber?n");35printf("Pleasetypeyourfirstguess.n?");36scanf("%d",&guess);37©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions13738/*loopuntilcorrectnumber*/39while(guess!=x){4041/*ifguessistoolow*/42if(guess3#include4#include56voidguessGame(void);/*functionprototype*/78intmain()9{10srand(time(NULL));/*seedrandomnumbergenerator*/11guessGame();1213return0;/*indicatesuccessfultermination*/1415}/*endmain*/1617/*guessGamegeneratesnumbersbetween1and100018andchecksuser"sguess*/19voidguessGame(void)20{21intx;/*randomlygeneratednumber*/22intguess;/*user"sguess*/23inttotal=1;/*numberofguesses*/24intresponse;/*responsetocontinuegame,1=yes,0=no*/2526/*loopuntiluserenters0toquitgame*/27do{2829/*generaterandomnumberbetween1and1000301isshift,1000isscalingfactor*/31x=1+rand()%1000;3233/*promptforguess*/34printf("nIhaveanumberbetween1and1000.n");35printf("Canyouguessmynumber?n");36printf("Pleasetypeyourfirstguess.n?");37scanf("%d",&guess);3839/*loopwhilenotcorrectanswer*/40while(guess!=x){4142/*guessisincorrect;displayhint*/43if(guess34longpower(longbase,longexponent);/*functionprototype*/56intmain()7{8longb;/*base*/9longe;/*exponent*/1011printf("Enterabaseandanexponent:");12scanf("%ld%ld",&b,&e);1314/*calculateanddisplaybraisedtotheepower*/15printf("%ldraisedtothe%ldis%ldn",b,e,power(b,e));1617return0;/*indicatesuccessfultermination*/1819}/*endmain*/2021/*powerrecursivelycalculatesbaseraisedtotheexponent22assumeexponent>=1*/23longpower(longbase,longexponent)24{2526/*basecase:exponentequals1,returnbase*/27if(exponent==1){28returnbase;29}/*endif*/30else{/*recursivestep*/31returnbase*power(base,exponent-1);32}/*endelse*/3334}/*endfunctionpower*/Enterabaseandanexponent:5105raisedtothe10is97656255.38TheFibonacciseries0,1,1,2,3,5,8,13,21,…beginswiththeterms0and1andhasthepropertythateachsucceedingtermisthesumofthetwoprecedingterms.a)Writeanon-recursivefunctionfibonacci(n)thatcalculatesthenthFibonaccinumber.b)DeterminethelargestFibonaccinumberthatcanbeprintedonyoursystem.Modifytheprogramofparta)tousedoubleinsteadofinttocalculateandreturnFibonaccinumbers.Lettheprogramloopuntilitfailsbecauseofanexcessivelyhighvalue.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions141ANS:1/*Exercise5.38PartASolution*/2#include3#defineMAX23/*themaximumnumberforwhichthe*/4/*fibonaccivaluecanbecalculated*/5/*on2-byteintegersystems*/6intfibonacci(intn);78intmain()9{10intloop;/*loopcounter*/1112/*calculateanddisplayFibonaccivaluefor0toMAX*/13for(loop=0;loop<=MAX;loop++){14printf("fibonacci(%d)=%dn",loop,fibonacci(loop));15}/*endfor*/1617return0;/*indicatesuccessfultermination*/1819}/*endmain*/2021/*fibonaccinonrecursivelycalculatesnthFibonaccinumber*/22intfibonacci(intn)23{24intj;/*loopcounter*/25intfib[MAX];/*definearrayofsizeMAX*/2627fib[0]=0;28fib[1]=1;2930/*looptofindnthFibonaccivalue*/31for(j=2;j<=n;j++){32fib[j]=fib[j-1]+fib[j-2];33}/*endfor*/3435returnfib[n];/*returnnthFibonaccivalue*/3637}/*endfunctionfibonacci*/fibonacci(0)=0fibonacci(1)=1fibonacci(2)=1fibonacci(3)=2fibonacci(4)=3fibonacci(5)=5fibonacci(6)=8fibonacci(7)=13fibonacci(8)=21fibonacci(9)=34fibonacci(10)=55fibonacci(11)=89fibonacci(12)=144fibonacci(13)=233fibonacci(14)=377fibonacci(15)=610fibonacci(16)=987fibonacci(17)=1597fibonacci(18)=2584fibonacci(19)=4181fibonacci(20)=6765fibonacci(21)=10946fibonacci(22)=17711fibonacci(23)=28658©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com142CFunctions:SolutionsChapter51/*Exercise5.38PartBSolution*/2#include3#defineSIZE10045doublefibonacci(intn);/*functionprototype*/67intmain()8{9intloop;/*loopcounter*/1011/*loopSIZEtimesandcalculateFibonaccivalues*/12for(loop=0;loop34/*functionprototype*/5voidtower(intc,intstart,intend,inttemp);67intmain()8{9intn;/*numberofdisks*/1011printf("Enterthestartingnumberofdisks:");12scanf("%d",&n);1314/*printinstructionsformovingdisksfrom15peg1topeg3usingpeg2fortemporarystorage*/16tower(n,1,3,2);1718return0;/*indicatesuccessfultermination*/1920}/*endmain*/2122/*towerrecursivelyprintsinstructionsformovingdisks23fromstartpegtoendpegusingtemppegfortemporarystorage*/24voidtower(intc,intstart,intend,inttemp)25{2627/*basecase*/28if(c==1){29printf("%d-->%dn",start,end);30return;31}/*endif*/3233/*movec-1disksfromstarttotemp*/34tower(c-1,start,temp,end);3536/*movelastdiskfromstarttoend*/37printf("%d-->%dn",start,end);3839/*movec-1disksfromtemptoend*/40tower(c-1,temp,end,start);41}/*endfunctiontower*/Enterthestartingnumberofdisks:41-->21-->32-->31-->23-->13-->21-->21-->32-->32-->13-->12-->31-->21-->32-->3©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1455.40Anyprogramthatcanbeimplementedrecursivelycanbeimplementediteratively,althoughsometimeswithconsiderablymoredifficultyandconsiderablylessclarity.TrywritinganiterativeversionoftheTowersofHanoi.Ifyousucceed,compareyouriterativeversionwiththerecursiveversionyoudevelopedinExercise5.39.Investigateissuesofperformance,clarity,andyourabil-itytodemonstratethecorrectnessoftheprograms.5.41(VisualizingRecursion)Itisinterestingtowatchrecursion“inaction.”ModifythefactorialfunctionofFig.5.14toprintitslocalvariableandrecursivecallparameter.Foreachrecursivecall,displaytheoutputsonaseparatelineandaddalevelofin-dentation.Doyourutmosttomaketheoutputsclear,interesting,andmeaningful.Yourgoalhereistodesignandimplementanoutputformatthathelpsapersonunderstandrecursionbetter.Youmaywanttoaddsuchdisplaycapabilitiestothemanyotherre-cursionexamplesandexercisesthroughoutthetext.ANS:Note:TheprintfinfunctionprintRecursionusestheconversionspecification%*d.The*enablesthepro-grammertospecifythefieldwidthasavariableargumentintheprintf.Inthiscasevariablenisusedasthefieldwidth,anditsvalueisoutput.1/*Exercise5.41Solution*/2#include34longfactorial(longnumber);/*functionprototype*/5voidprintRecursion(intn);/*functionprototype*/67intmain()8{9inti;/*loopcounter*/1011/*calculatefactorial(i)anddisplayresult*/12for(i=0;i<=10;i++){13printf("%2d!=%ldn",i,factorial(i));14}/*endfor*/1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/1920/*recursivedefinitionoffunctionfactorial*/21longfactorial(longnumber)22{2324/*basecase*/25if(number<=1){26return1;27}/*endif*/28else{/*recursivestep*/29printRecursion(number);/*addoutputsandindentation*/30return(number*factorial(number-1));31}/*endelse*/3233}/*endfunctionfactorial*/3435/*printRecursionaddsoutputsandindentationtohelp36visualizerecursion*/37voidprintRecursion(intn)38{39printf("number=%*dn",n,n);40}/*endfunctionprintRecursion*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com146CFunctions:SolutionsChapter50!=11!=1number=22!=2number=3number=23!=6number=4number=3number=24!=24number=5number=4number=3number=25!=120...number=9number=8number=7number=6number=5number=4number=3number=29!=362880number=10number=9number=8number=7number=6number=5number=4number=3number=210!=3628800©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1475.42Thegreatestcommondivisorofintegersxandyisthelargestintegerthatevenlydividesbothxandy.Writearecursivefunctiongcdthatreturnsthegreatestcommondivisorofxandy.Thegcdofxandyisdefinedrecursivelyasfollows:Ifyisequalto0,thengcd(x,y)isx;otherwisegcd(x,y)isgcd(y,x%y)where%istheremainderoperator.ANS:1/*Exercise5.42Solution*/2#include34/*functionprototype*/5unsignedintgcd(unsignedintxMatch,unsignedintyMatch);67intmain()8{9unsignedintx;/*firstinteger*/10unsignedinty;/*secondinteger*/11unsignedintgcDiv;/*greatestcommondivisorofxandy*/1213printf("Entertwointegers:");14scanf("%u%u",&x,&y);1516gcDiv=gcd(x,y);1718printf("Greatestcommondivisorof%uand%uis%un",19x,y,gcDiv);2021return0;/*indicatesuccessfultermination*/2223}/*endmain*/2425/*gcdrecursivelyfindsgreatestcommondivisor26ofxMatchandyMatch*/27unsignedintgcd(unsignedintxMatch,unsignedintyMatch)28{2930/*basecase*/31if(yMatch==0){32returnxMatch;33}/*endif*/34else{/*recursivestep*/35returngcd(yMatch,xMatch%yMatch);36}/*endelse*/3738}/*endfunctiongcd*/Entertwointegers:1011250500Greatestcommondivisorof10112and50500is4©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com148CFunctions:SolutionsChapter55.43Canmainbecalledrecursively?Writeaprogramcontainingafunctionmain.Includestaticlocalvariablecountini-tializedto1.Postincrementandprintthevalueofcounteachtimemainiscalled.Runyourprogram.Whathappens?ANS:1/*Exercise5.43Solution*/2#include34intmain()5{6staticintcount=1;/*staticlocalvariablecount*/78printf("%dn",count);9count++;1011main();/*recursivelycallintmain()*/1213return0;/*indicatesuccessfultermination*/1415}/*endmain*/12345678910...©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1495.44Exercises5.32through5.34developedacomputer-assistedinstructionprogramtoteachanelementaryschoolstudentmul-tiplication.Thisexercisesuggestsenhancementstothatprogram.a)Modifytheprogramtoallowtheusertoenteragrade-levelcapability.Agradelevelof1meanstouseonlysingle-digitnumbersintheproblems,agradeleveloftwomeanstousenumbersaslargeastwo-digits,etc.ANS:1/*Exercise5.44PartASolution*/2#include3#include4#include56intrandValue(intlevel);/*functionprototype*/7voidmultiplication(void);/*functionprototype*/8voidcorrectMessage(void);/*functionprototype*/9voidincorrectMessage(void);/*functionprototype*/1011intmain()12{13srand(time(NULL));/*seedrandomnumbergenerator*/14multiplication();/*beingmultiplicationpractice*/1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/1920/*randValuegeneratesrandomnumbersbasedongradelevel*/21intrandValue(intlevel)22{2324/*leveldeterminessizeofrandomnumber*/25switch(level){2627case1:28returnrand()%10;2930case2:31returnrand()%100;3233case3:34returnrand()%1000;3536default:37returnrand()%10;38}/*endswitch*/3940}/*endfunctionrandValue*/4142/*multiplicationproducespairsofrandomnumbersand43promptsuserforproduct;leveldeterminessizeofnumbers*/44voidmultiplication(void)45{46inti;/*loopcounter*/47intx;/*firstfactor*/48inty;/*secondfactor*/49intgradeLevel;/*grade-levelcapability*/50intright=0;/*totalnumberofrightresponses*/51intwrong=0;/*totalnumberofwrongresponses*/52unsignedintresponse;/*userresponseforproduct*/5354printf("Enterthegrade-level(1to3):");55scanf("%d",&gradeLevel);5657/*loop10times*/58for(i=1;i<=10;i++){5960/*generaterandomnumbersdependingonlevel*/61x=randValue(gradeLevel);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com150CFunctions:SolutionsChapter562y=randValue(gradeLevel);6364printf("Howmuchis%dtimes%d?",x,y);65scanf("%u",&response);6667/*loopwhileresponseisincorrect*/68while(response!=x*y){69++wrong;/*updatetotalnumberofwronganswers*/70incorrectMessage();71scanf("%u",&response);72}/*endwhile*/7374++right;/*updatetotalnumberofrightanswers*/75correctMessage();76}/*endfor*/7778/*if<75%right*/79if((double)right/(right+wrong)<.75){80printf("Pleaseaskyourinstructorforextrahelp.n");81}/*endif*/8283printf("That"sallfornow.Bye.n");84}/*endfunctionmultiplication*/8586/*correctMessagerandomlychoosesresponsetocorrectanswer*/87voidcorrectMessage(void)88{8990/*generaterandomnumberbetween0and3*/91switch(rand()%4){9293case0:94printf("Verygood!nn");95break;/*exitswitch*/9697case1:98printf("Excellent!nn");99break;/*exitswitch*/100101case2:102printf("Nicework!nn");103break;/*exitswitch*/104105case3:106printf("Keepupthegoodwork!nn");107break;/*exitswitch*/108}/*endswitch*/109110}/*endfunctioncorrectMessage*/111112/*incorrectMessagerandomlychoosesresponsetoincorrectanswer*/113voidincorrectMessage(void)114{115116/*generaterandomnumberbetween0and3*/117switch(rand()%4){118119case0:120printf("No.Pleasetryagain.n?");121break;/*exitswitch*/122123case1:124printf("Wrong.Tryoncemore.n?");125break;/*exitswitch*/126127case2:128printf("Don"tgiveup!n?");129break;/*exitswitch*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions151130131case3:132printf("No.Keeptrying.n?");133break;/*exitswitch*/134}/*endswitch*/135136}/*endfunctionincorrectMessage*/Enterthegrade-level(1to3):1Howmuchis6times0?0Keepupthegoodwork!Howmuchis6times3?18Keepupthegoodwork!...Enterthegrade-level(1to3):2Howmuchis5times63?315Excellent!Howmuchis29times13?392No.Pleasetryagain.?377Excellent!...Enterthegrade-level(1to3):3Howmuchis799times343?274057Keepupthegoodwork!Howmuchis201times349?0Don"tgiveup!...©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com152CFunctions:SolutionsChapter5b)Modifytheprogramtoallowtheusertopickthetypeofarithmeticproblemsheorshewishestostudy.Anoptionof1meansadditionproblemsonly,2meanssubtractionproblemsonly,3meansmultiplicationproblemsonly,4meansdi-visionproblemsonly,and5meanstorandomlyintermixproblemsofallthesetypes.ANS:1/*Exercise5.44PartBSolution*/2#include3#include4#include56intmenu(void);/*functionprototype*/7voidarithmetic(void);/*functionprototype*/8voidcorrectMessage(void);/*functionprototype*/9voidincorrectMessage(void);/*functionprototype*/1011intmain()12{13srand(time(NULL));/*seedrandomnumbergenerator*/14arithmetic();/*beginarithmeticprocess*/1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/1920/*menudisplaysusermenuofchoices*/21intmenu(void)22{23intchoice;/*user"schoice*/2425/*displaymenuandreaduser"schoice*/26do{27printf("Choosetypeofproblemtostudy.n");28printf("Enter:1foraddition,2forsubtractionn");29printf("Enter:3formultiplication,4fordivisionn");30printf("Enter:5foracombinationof1through4n");31printf("?");32scanf("%d",&choice);33}while(choice<1||choice>5);/*enddo...while*/3435returnchoice;/*returnuser"schoice*/3637}/*endfunctionmenu*/3839/*incorrectMessagerandomlychoosesresponsetoincorrectanswer*/40voidincorrectMessage(void)41{4243/*generaterandomnumberbetween0and3*/44switch(rand()%4){4546case0:47printf("No.Pleasetryagain.n?");48break;/*exitswitch*/4950case1:51printf("Wrong.Tryoncemore.n?");52break;/*exitswitch*/5354case2:55printf("Don"tgiveup!n?");56break;/*exitswitch*/5758case3:59printf("No.Keeptrying.n?");60break;/*exitswitch*/61}/*endswitch*/6263}/*endfunctionincorrectMessage*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1536465/*correctMessagerandomlychoosesresponsetocorrectanswer*/66voidcorrectMessage(void)67{6869/*generaterandomnumberbetween0and3*/70switch(rand()%4){7172case0:73printf("Verygood!nn");74break;/*exitswitch*/7576case1:77printf("Excellent!nn");78break;/*exitswitch*/7980case2:81printf("Nicework!nn");82break;/*exitswitch*/8384case3:85printf("Keepupthegoodwork!nn");86break;/*exitswitch*/87}/*endswitch*/8889}/*endfunctioncorrectMessage*/909192voidarithmetic(void)93{94inti;/*loopcounter*/95intx;/*firstnumber*/96inty;/*secondnumber*/97intresponse;/*userresponseforproduct*/98intanswer;/*correctanswer*/99intselection;/*menuselection*/100intright=0;/*totalcorrectresponses*/101intwrong=0;/*totalincorrectresponses*/102inttype;/*typeofproblemschosen*/103intproblemMix;/*randomchoiceoftypeofproblem*/104charoperator;/*arithmeticoperator*/105106selection=menu();107type=selection;108109/*loop10times*/110for(i=1;i<=10;i++){111x=rand()%10;/*generatefirstrandomnumber*/112y=rand()%10;/*generatesecondrandomnumber*/113114/*ifoption5,randomlyselecttype*/115if(selection==5){116problemMix=1+rand()%4;117type=problemMix;118}/*endif*/119120/*generateansweranddefineoperatordependingonoption*/121switch(type){122123/*option1:addition*/124case1:125operator="+";126answer=x+y;127break;/*exitswitch*/128129/*option2:subtraction*/130case2:131operator=‘‘-";©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com154CFunctions:SolutionsChapter5132answer=x-y;133break;/*exitswitch*/134135/*option3:multiplication*/136case3:137operator="*";138answer=x*y;139break;/*exitswitch*/140141/*option4:integerdivision*/142case4:143operator="/";144145/*eliminatedividebyzeroerror*/146if(y==0){147y=1;148answer=x/y;149}/*endif*/150else{151x*=y;/*create"nice"division*/152answer=x/y;153}/*endelse*/154155break;/*exitswitch*/156}/*endswitch*/157158printf("Howmuchis%d%c%d?",x,operator,y);159160scanf("%d",&response);161162/*whilenotcorrectanswer*/163while(response!=answer){164++wrong;165incorrectMessage();166scanf("%d",&response);167}/*endwhile*/168169++right;170correctMessage();171}/*endfor*/172173/*if<75%right,suggesthelp*/174if((double)right/(right+wrong)<.75){175printf("Pleaseaskyourinstructorforextrahelp.n");176}/*endif*/177178printf("That"sallfornow.Bye.n");179}/*endfunctionarithmetic*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions155Choosetypeofproblemtostudy.Enter:1foraddition,2forsubtractionEnter:3formultiplication,4fordivisionEnter:5foracombinationof1through4?5Howmuchis9*9?81Nicework!Howmuchis3-1?2Keepupthegoodwork!Howmuchis1*3?3Nicework!...Howmuchis1-9?-8Nicework!That"sallfornow.Bye.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com156CFunctions:SolutionsChapter55.45Writefunctiondistancethatcalculatesthedistancebetweentwopoints(x1,y1)and(x2,y2).Allnumbersandreturnval-uesshouldbeoftypedouble.ANS:1/*Exercise5.45Solution*/2#include3#include45/*functionprototype*/6doubledistance(doublexOne,doubleyOne,doublexTwo,doubleyTwo);78intmain()9{10doublex1;/*xcoordinateoffirstpoint*/11doubley1;/*ycoordinateoffirstpoint*/12doublex2;/*xcoordinateofsecondpoint*/13doubley2;/*ycoordinateofsecondpoint*/14doubledist;/*distancebetweentwopoints*/1516/*promptforfirstpointcoordinates*/17printf("Enterthefirstpoint:");18scanf("%lf%lf",&x1,&y1);1920/*promptforsecondpointcoordinates*/21printf("Enterthesecondpoint:");22scanf("%lf%lf",&x2,&y2);2324dist=distance(x1,y1,x2,y2);/*calculatedistance*/2526printf("Distancebetween(%.2f,%.2f)"27"and(%.2f,%.2f)is%.2fn",28x1,y1,x2,y2,dist);2930return0;/*indicatesuccessfultermination*/3132}/*endmain*/3334/*distancecalculatesdistancebetween2points35givenby(xOne,yOne)and(xTwo,yTwo)*/36doubledistance(doublexOne,doubleyOne,doublexTwo,doubleyTwo)37{38doubledistance;/*distancebetweentwopoints*/3940distance=sqrt(pow(xOne-xTwo,2)+pow(yOne-yTwo,2));4142returndistance;4344}/*endfunctiondistance*/Enterthefirstpoint:34Enterthesecondpoint:00Distancebetween(3.00,4.00)and(0.00,0.00)is5.00©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1575.46Whatdoesthefollowingprogramdo?1#include23/*functionmainbeginsprogramexecution*/4intmain()5{6intc;/*variabletoholdcharacterinputbyuser*/78if((c=getchar())!=EOF){9main();10printf("%c",c);11}/*endif*/1213return0;/*indicatessuccessfultermination*/1415}/*endmain*/ANS:Inputsacharacterandrecursivelycallsmain()untiltheEOFcharacterisentered.Everycharacterenteredisthenoutputinreverseorder.abccba©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com158CFunctions:SolutionsChapter55.47Whatdoesthefollowingprogramdo?1#include23intmystery(inta,intb);/*functionprototype*/45/*functionmainbeginsprogramexecution*/6intmain()7{8intx;/*firstinteger*/9inty;/*secondinteger*/1011printf("Entertwointegers:");12scanf("%d%d",&x,&y);1314printf("Theresultis%dn",mystery(x,y));1516return0;/*indicatessuccessfultermination*/1718}/*endmain*/1920/*Parameterbmustbeapositiveinteger21topreventinfiniterecursion*/22intmystery(inta,intb)23{24/*basecase*/25if(b==1){26returna;27}/*endif*/28else{/*recursivestep*/29returna+mystery(a,b-1);30}/*endelse*/3132}/*endfunctionmystery*/ANS:Theproblemmimicsmultiplicationbyaddingupa,btimes.Entertwointegers:876Theresultis522©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1595.48AfteryoudeterminewhattheprogramofExercise5.47does,modifytheprogramtofunctionproperlyafterremovingtherestrictionofthesecondargumentbeingnonnegative.ANS:1/*Exercise5.48Solution*/2#include34intmystery(inta,intb);/*functionprototype*/56intmain()7{8intx;/*firstinteger*/9inty;/*secondinteger*/1011printf("Entertwointegers:");12scanf("%d%d",&x,&y);1314printf("Theresultis%dn",mystery(x,y));1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/1920/*mysterymultipliesa*busingrecursion*/21intmystery(inta,intb)22{2324/*ifaandborjustbarenegative*/25if((a<0&&b<0)||b<0){26a*=-1;/*multiplyaandbby-1tomakepositive*/27b*=-1;28}/*endif*/2930/*basecase*/31if(b==1){32returna;33}/*endif*/34else{/*recursivestep*/35returna+mystery(a,b-1);36}/*endelse*/3738}/*endfunctionmystery*/Entertwointegers:-976Theresultis-582Entertwointegers:97-6Theresultis-582Entertwointegers:-97-6Theresultis582©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com160CFunctions:SolutionsChapter55.49WriteaprogramthattestsasmanyofthemathlibraryfunctionsinFig.5.2asyoucan.Exerciseeachofthesefunctionsbyhavingyourprogramprintouttablesofreturnvaluesforadiversityofargumentvalues.ANS:1/*Exercise5.49Solution*/2#include3#include45intmain()6{7intloop;/*integerloopcounter*/8intcount;/*loopcounter*/9doubleloop2;/*doubleloopcounter*/1011/*loopandtesteachmathfunction*/12for(count=1;count<14;count++){1314/*testmathfunctionbasedoncount*/15switch(count){1617/*printtableheaders*/18case1:19printf("funct");2021for(loop=1;loop<6;loop++){22printf("%10d",loop);23}/*endfor*/2425break;/*exitswitch*/2627/*displaysqrtforrangeofvalues*/28case2:29printf("nsqrt()");3031for(loop=1;loop<6;loop++){32printf("%10.2lf",sqrt(loop));33}/*endfor*/3435break;/*exitswitch*/3637/*displayexpforrangeofvalues*/38case3:39printf("exp()");4041for(loop=1;loop<6;loop++){42printf("%10.2lf",exp(loop));43}/*endfor*/4445break;/*exitswitch*/4647/*displaynaturallogforrangeofvalues*/48case4:49printf("log()");5051for(loop=1;loop<6;loop++){52printf("%10.2lf",log(loop));53}/*endfor*/5455break;/*exitswitch*/5657/*displaylogbase10forrangeofvalues*/58case5:59printf("log10()");6061for(loop=1;loop<6;loop++){62printf("%10.2lf",log10(loop));63}/*endfor*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1616465break;/*exitswitch*/6667/*displaypowfunction,testwith2asbase*/68case6:69printf("pow(2,x)");7071for(loop=1;loop<6;loop++){72printf("%10.2lf",pow(2,loop));73}/*endfor*/7475break;/*exitswitch*/7677/*displaytableheaders*/78case7:79printf("nnfunct");8081for(loop2=-1.5;loop2<3.0;loop2+=1.1){82printf("%10.2lf",loop2);83}/*endfor*/8485break;/*exitswitch*/8687/*displayfabsforrangeofvalues*/88case8:89printf("nfabs()");9091for(loop2=-1.5;loop2<3.0;loop2+=1.1){92printf("%10.2lf",fabs(loop2));93}/*endfor*/9495break;/*exitswitch*/9697/*displayceilforrangeofvalues*/98case9:99printf("ceil()");100101for(loop2=-1.5;loop2<3.0;loop2+=1.1){102printf("%10.2lf",ceil(loop2));103}/*endfor*/104105break;/*exitswitch*/106107/*displayfloorforrangeofvalues*/108case10:109printf("floor()");110111for(loop2=-1.5;loop2<3.0;loop2+=1.1){112printf("%10.2lf",floor(loop2));113}/*endfor*/114115break;/*exitswitch*/116117/*displaysinforrangeofvalues*/118case11:119printf("sin()");120121for(loop2=-1.5;loop2<3.0;loop2+=1.1){122printf("%10.2lf",sin(loop2));123}/*endfor*/124125break;/*exitswitch*/126127/*displaycosforrangeofvalues*/128case12:129printf("cos()");130©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com162CFunctions:SolutionsChapter5131for(loop2=-1.5;loop2<3.0;loop2+=1.1){132printf("%10.2lf",cos(loop2));133}/*endfor*/134135break;/*exitswitch*/136137/*displaytanforrangeofvalues*/138case13:139printf("tan()");140141for(loop2=-1.5;loop2<3.0;loop2+=1.1){142printf("%10.2lf",tan(loop2));143}/*endfor*/144145break;/*exitswitch*/146}/*endswitch*/147148printf("n");149}/*endfor*/150151return0;/*indicatesuccessfultermination*/152153}/*endmain*/funct12345sqrt()1.001.411.732.002.24exp()2.727.3920.0954.60148.41log()0.000.691.101.391.61log10()0.000.300.480.600.70pow(2,x)2.004.008.0016.0032.00funct-1.50-0.400.701.802.90fabs()1.500.400.701.802.90ceil()-1.000.001.002.003.00floor()-2.00-1.000.001.002.00sin()-1.00-0.390.640.970.24cos()0.070.920.76-0.23-0.97tan()-14.10-0.420.84-4.29-0.255.50Findtheerrorineachofthefollowingprogramsegmentsandexplainhowtocorrectit:a)doublecube(float);/*functionprototype*/...cube(floatnumber)/*functiondefinition*/{returnnumber*number*number;}ANS:Functiondefinitionismissingreturntype.doublecube(float);/*functionprototype*/...doublecube(floatnumber)/*functiondefinition*/{returnnumber*number*number;}b)registerautointx=7;ANS:Toomanystorageclassdefinitions.Autoclassdefinitionisnotnecessary.registerintx=7;/*autoremoved*/c)intrandomNumber=srand();©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions163ANS:srand()seedstherandomnumbergenerator,andhasavoidreturntype.Functionrand()producesrandomnum-bers.intrandomNumber=rand();d)doubley=123.45678;intx;x=y;printf("%fn",(double)x);ANS:Decimalvalueislostwhenadoubleisassignedtoaninteger.Type-castingtheinttodoublecannotbringbacktheoriginaldecimalvalue.Only123.000000canbeprinted.doubley=123.45678;doublex;x=y;printf(“%fn”,x);e)doublesquare(doublenumber){doublenumber;returnnumber*number;}ANS:numberisdefinedtwice.doublesquare(doublenumber){returnnumber*number;}f)intsum(intn){if(n==0)return0;elsereturnn+sum(n);}ANS:Infiniterecursion.intsum(intn){if(n==0)return0;elsereturnn+sum(n-1);}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com164CFunctions:SolutionsChapter55.51ModifythecrapsprogramofFig.5.10toallowwagering.Packageasafunctiontheportionoftheprogramthatrunsonegameofcraps.InitializevariablebankBalanceto1000dollars.Prompttheplayertoenterawager.UseawhilelooptocheckthatwagerislessthanorequaltobankBalanceandifnotprompttheusertoreenterwageruntilavalidwagerisentered.Afteracorrectwagerisentered,runonegameofcraps.Iftheplayerwins,increasebankBalancebywagerandprintthenewbank-Balance.Iftheplayerloses,decreasebankBalancebywager,printthenewbankBalance,checkifbankBalancehasbecomezero,andifsoprintthemessage"Sorry.Youbusted!"Asthegameprogresses,printvariousmessagestocreatesome“chatter”suchas"Oh,you"regoingforbroke,huh?",or"Awcmon,takeachance!",or"You"reupbig.Now"sthetimetocashinyourchips!".ANS:1/*Exercise5.51Solution*/2#include3#include4#include56/*enumerationconstantsrepresentgamestatus*/7enumStatus{CONTINUE,WON,LOST};89introllDice(void);/*functionprototype*/10enumStatuscraps(void);/*functionprototype*/11voidchatter(void);/*functionprototype*/1213intmain()14{15enumStatusresult;/*resultofcurrentgame*/16intwager=0;/*wagerforcurrentgame*/17intbankBalance=1000;/*currentbankbalance*/1819srand(time(NULL));/*seedrandomnumbergenerator*/2021/*displaycurrentbalanceandpromptforwager*/22printf("Youhave$%dinthebank.n",bankBalance);23printf("Placeyourwager:");24scanf("%d",&wager);2526/*loopwhilenotvalidwager*/27while(wager<=0||wager>1000){28printf("Pleasebetavalidamount.n");29scanf("%d",&wager);30}/*endwhile*/3132result=craps();/*playgameofcraps*/3334/*ifplayerlostcurrentgame*/35if(result==LOST){3637/*decreasebalancebywageranddisplaynewbalance*/38bankBalance-=wager;39printf("Yournewbankbalanceis$%dn",bankBalance);4041/*ifbalanceis0*/42if(bankBalance==0){43printf("Sorry.YouareBusted!ThankYouForPlaying.n");44}/*endif*/4546}/*endif*/47else{/*playerwongame*/4849/*increasebalancebywageranddisplaynewbalance*/50bankBalance+=wager;51printf("Yournewbankbalanceis$%dn",bankBalance);52}/*endelse*/5354return0;/*indicatesuccessfultermination*/5556}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions1655758/*rolldice,calculatesumanddisplayresults*/59introllDice(void)60{61intdie1;/*firstdievalue*/62intdie2;/*seconddievalue*/63intworkSum;/*sumofdice*/6465die1=1+rand()%6;/*pickrandomdie1value*/66die2=1+rand()%6;/*pickrandomdie2value*/67workSum=die1+die2;/*sumdie1anddie2*/6869/*displayresultsofthisroll*/70printf("Playerrolled%d+%d=%dn",die1,die2,workSum);7172returnworkSum;/*returnsumofdice*/7374}/*endfunctionrollDice*/7576/*crapsplaysonegameofcraps,returnsresultofgame*/77enumStatuscraps(void)78{79enumStatusgameStatus;/*cancontainCONTINUE,WONorLOST*/80intsum;/*currentrollofdice*/81intmyPoint;/*pointvalue*/8283sum=rollDice();/*firstrollofdice*/8485/*determinegamestatusandpointbasedonsumofdice*/86switch(sum){8788/*winonfirstroll*/89case7:90case11:91gameStatus=WON;92chatter();93break;/*exitswitch*/9495/*loseonfirstroll*/96case2:97case3:98case12:99gameStatus=LOST;100chatter();101break;/*exitswitch*/102103/*rememberpoint*/104default:105gameStatus=CONTINUE;106myPoint=sum;107printf("Pointis%dn",myPoint);108chatter();109break;/*exitswitch*/110}/*endswitch*/111112/*whilegamenotcomplete*/113while(gameStatus==CONTINUE){114chatter();115sum=rollDice();/*rolldiceagain*/116117/*determinegamestatus*/118if(sum==myPoint){119gameStatus=WON;/*winbymakingpoint*/120}/*endif*/121else{122123if(sum==7){124gameStatus=LOST;/*losebyrolling7*/125}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com166CFunctions:SolutionsChapter5126127}/*endelse*/128129}/*endwhile*/130131/*displaywonorlostmessageandreturnstatus*/132if(gameStatus==WON){133printf("Playerwinsn");134returnWON;135}/*endif*/136else{137printf("Playerlosesn");138returnLOST;139}/*endelse*/140141}/*endfunctioncraps*/142143/*chatterdisplaysmessagesatrandomtocreate"chatter"*/144voidchatter(void)145{146intselect;/*randomnumber*/147148select=1+rand()%6;149150/*choosemessageatrandom*/151switch(select){152153case1:154printf("Oh,you"regoingforbroke,huh?n");155break;/*exitswitch*/156157case2:158printf("Awcmon,takeachance!n");159break;/*exitswitch*/160161case3:162printf("Hey,Ithinkthisguyisgoingtobreakthebank!!n");163break;/*exitswitch*/164165case4:166printf("You"reupbig.Now"sthetimetocashinyourchips!n");167break;/*exitswitch*/168169case5:170printf("Waytoolucky!Thosedicehavetobeloaded!n");171break;/*exitswitch*/172173case6:174printf("Betitall!Betitall!n");175break;/*exitswitch*/176177default:178break;/*exitswitch*/179}/*endswitch*/180181}/*endfunctionchatter*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter5CFunctions:Solutions167Youhave$1000inthebank.Placeyourwager:1000Playerrolled4+5=9Pointis9You"reupbig.Now"sthetimetocashinyourchips!Oh,you"regoingforbroke,huh?Playerrolled5+6=11Hey,Ithinkthisguyisgoingtobreakthebank!!Playerrolled3+1=4Betitall!Betitall!Playerrolled5+5=10Awcmon,takeachance!Playerrolled6+6=12Betitall!Betitall!Playerrolled2+1=3Hey,Ithinkthisguyisgoingtobreakthebank!!Playerrolled5+6=11Hey,Ithinkthisguyisgoingtobreakthebank!!Playerrolled2+1=3Awcmon,takeachance!Playerrolled2+4=6You"reupbig.Now"sthetimetocashinyourchips!Playerrolled2+3=5Oh,you"regoingforbroke,huh?Playerrolled6+3=9PlayerwinsYournewbankbalanceis$2000©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com168CFunctions:SolutionsChapter5©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com6CArrays:SolutionsEXERCISES6.6Fillintheblanksineachofthefollowing:a)Cstoreslistsofvaluesin.ANS:arrays.b)Theelementsofanarrayarerelatedbythefactthatthey.ANS:havethesamenameandtype.c)Whenreferringtoanarrayelement,thepositionnumbercontainedwithinparenthesesiscalleda(n).ANS:subscript.d)Thenamesofthefiveelementsofarraypare,,,and.ANS:p[0],p[1],p[2],p[3],p[4].e)Thecontentsofaparticularelementofanarrayiscalledtheofthatelement.ANS:value.f)Naminganarray,statingitstypeandspecifyingthenumberofelementsinthearrayiscalledthearray.ANS:defining.g)Theprocessofplacingtheelementsofanarrayintoeitherascendingordescendingorderiscalled.ANS:sorting.h)Inadouble-subscriptedarray,thefirstsubscript(byconvention)identifiestheofanelementandthesecondsubscript(byconvention)identifiestheofanelement.ANS:row,column.i)Anm-by-narraycontainsrows,columnsandelements.ANS:m,n,m*n.j)Thenameoftheelementinrow3andcolumn5ofarraydis.ANS:d[3][5].6.7Statewhichofthefollowingaretrueandwhicharefalse.Iffalse,explainwhy.a)Torefertoaparticularlocationorelementwithinanarray,wespecifythenameofthearrayandthevalueofthepar-ticularelement.ANS:False.Wespecifythenameandthesubscriptoftheelement.b)Anarraydefinitionreservesspaceforthearray.ANS:True.c)Toindicatethat100locationsshouldbereservedforintegerarrayp,theprogrammerwritesthedefinitionp[100];ANS:True.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com170CArrays:SolutionsChapter6d)ACprogramthatinitializestheelementsofa15-elementarraytozeromustcontainoneforstatement.ANS:False.Theelementsofanarraycanbeinitializedinthedefinition.e)ACprogramthattotalstheelementsofadouble-subscriptedarraymustcontainnestedforstatements.ANS:False.Itispossibletototaltheelementsofadouble-subscriptedarraybyenumeratingalltheelementsinanassign-mentstatement.f)Themean,medianandmodeofthefollowingsetofvaluesare5,6and7,respectively:1,2,5,6,7,7,7.ANS:True.6.8Writestatementstoaccomplisheachofthefollowing:a)Displaythevalueoftheseventhelementofcharacterarrayf.ANS:printf(“%cn”,f[6]);b)Inputavalueintoelement4ofsingle-subscriptedfloating-pointarrayb.ANS:scanf(“%f”,&b[4]);c)Initializeeachofthe5elementsofsingle-subscriptedintegerarraygto8.ANS:for(loop=0;loop<=4;loop++)g[loop]=8;d)Totaltheelementsoffloating-pointarraycof100elements.ANS:for(loop=0;loop<=99;loop++)sum+=c[loop];e)Copyarrayaintothefirstportionofarrayb.Assumedoublea[11],b[34];ANS:for(loop=0;loop<=10;loop++)b[loop]=a[loop];f)Determineandprintthesmallestandlargestvaluescontainedin99-elementfloating-pointarrayw.ANS:smallest=largest=w[0];for(loop=1;loop<=98;loop++)if(w[loop]largest)largest=w[loop];6.9Considera2-by-5integerarrayt.a)Writeadefinitionfort.ANS:intt[2][5];b)Howmanyrowsdoesthave?ANS:2c)Howmanycolumnsdoesthave?ANS:5d)Howmanyelementsdoesthave?ANS:10e)Writethenamesofalltheelementsinthesecondrowoft.ANS:t[1][0],t[1][1],t[1][2],t[1][3],t[1][4].f)Writethenamesofalltheelementsinthethirdcolumnoft.ANS:t[0][2],t[1][2].g)Writeasinglestatementthatsetstheelementoftinrow1andcolumn2tozero.ANS:t[1][2]=0;h)Writeaseriesofstatementsthatinitializeeachelementofttozero.Donotusearepetitionstructure.ANS:t[0][0]=0;t[0][1]=0;t[0][2]=0;t[0][3]=0;t[0][4]=0;t[1][0]=0;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions171t[1][1]=0;t[1][2]=0;t[1][3]=0;t[1][4]=0;i)Writeanestedforstatementthatinitializeseachelementofttozero.ANS:for(i=0;i<=1;i++)for(j=0;j<=4;j++)t[i][j]=0;j)Writeastatementthatinputsthevaluesfortheelementsoftfromtheterminal.ANS:for(i=0;i<=1;i++)for(j=0;j<=4;j++){printf(“Enteraninteger:”);scanf(“%d”,&t[i][j])}k)Writeaseriesofstatementsthatdetermineandprintthesmallestvalueinarrayt.ANS:smallest=t[0][0];for(i=0;i<=1;i++)for(j=0;j<=4;j++)if(t[i][j]34intmain()5{6intsalaries[11]={0};/*arraytoholdsalarycounts*/7intsales;/*currentemployee"ssales*/8doublesalary;/*currentemployee"ssalary*/9doublei=0.09;/*commissionpercentage*/1011/*promptuserforgrosssales*/12printf("Enteremployeegrosssales(-1toend):");13scanf("%d",&sales);1415/*whilesentinelvaluenotreadfromuser*/16while(sales!=-1){1718/*calculatesalarybasedonsales*/19salary=200.0+sales*i;20printf("EmployeeCommissionis$%.2fn",salary);2122/*updateappropriatesalaryrange*/23if(salary>=200&&salary<1000){24++salaries[(int)salary/100];25}/*endif*/26elseif(salary>=1000){27++salaries[10];28}/*endelseif*/2930/*promptuserforanotheremployeesalesamount*/31printf("nEnteremployeegrosssales(-1toend):");32scanf("%d",&sales);33}/*endwhile*/3435/*displaytableofrangesandemployeesineachrange*/36printf("nEmployeesintherange:n");37printf("$200-$299:%dn",salaries[2]);38printf("$300-$399:%dn",salaries[3]);39printf("$400-$499:%dn",salaries[4]);40printf("$500-$599:%dn",salaries[5]);41printf("$600-$699:%dn",salaries[6]);42printf("$700-$799:%dn",salaries[7]);43printf("$800-$899:%dn",salaries[8]);44printf("$900-$999:%dn",salaries[9]);45printf("Over$1000:%dn",salaries[10]);4647return0;/*indicatesuccessfultermination*/4849}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions173Enteremployeegrosssales(-1toend):3000EmployeeCommissionis$470.00Enteremployeegrosssales(-1toend):1000EmployeeCommissionis$290.00Enteremployeegrosssales(-1toend):10000EmployeeCommissionis$1100.00Enteremployeegrosssales(-1toend):8000EmployeeCommissionis$920.00Enteremployeegrosssales(-1toend):200EmployeeCommissionis$218.00Enteremployeegrosssales(-1toend):7000EmployeeCommissionis$830.00Enteremployeegrosssales(-1toend):-1Employeesintherange:$200-$299:2$300-$399:0$400-$499:1$500-$599:0$600-$699:0$700-$799:0$800-$899:1$900-$999:1Over$1000:1©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com174CArrays:SolutionsChapter66.11ThebubblesortpresentedinFig.6.15isinefficientforlargearrays.Makethefollowingsimplemodificationstoimprovetheperformanceofthebubblesort.a)Afterthefirstpass,thelargestnumberisguaranteedtobeinthehighest-numberedelementofthearray;afterthesecondpass,thetwohighestnumbersare“inplace,”andsoon.Insteadofmakingninecomparisonsoneverypass,modifythebubblesorttomakeeightcomparisonsonthesecondpass,sevenonthethirdpassandsoon.b)Thedatainthearraymayalreadybeintheproperorderornear-properorder,sowhymakeninepassesiffewerwillsuffice?Modifythesorttocheckattheendofeachpassifanyswapshavebeenmade.Ifnonehasbeenmade,thenthedatamustalreadybeintheproperorder,sotheprogramshouldterminate.Ifswapshavebeenmade,thenatleastonemorepassisneeded.ANS:1/*Exercise6.11Solution*/2#include3#defineMAX1045intmain()6{78/*initializearrayawithinitializerlist*/9inta[MAX]={10,9,8,7,6,5,4,3,2,1};10inti;/*loopcounter*/11intpass;/*loopcounter*/12inthold;/*temporaryvariableforswapping*/13intswap;/*flagtobreakloopifelementsaresorted*/1415printf("Dataitemsinoriginalordern");1617/*displayoriginal,unsortedarray*/18for(i=0;ia[i+1]){33swap=1;/*raiseflagifanyelementsareswapped*/34hold=a[i];35a[i]=a[i+1];36a[i+1]=hold;37}/*endif*/3839}/*endfor*/4041printf("AfterPass%d:",pass);4243/*displayarrayaftereachpass*/44for(i=0;i<=MAX-pass;i++){45printf("%d",a[i]);46}/*endfor*/4748printf("n");49©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions17550/*breakloopifarrayissorted*/51if(!swap){52break;53}/*endif*/5455}/*endfor*/5657printf("nDataitemsinascendingordern");5859/*displayarrayinsortedorder*/60for(i=0;i<10;i++){61printf("%4d",a[i]);62}/*endfor*/6364printf("n");6566return0;/*indicatesuccessfultermination*/6768}/*endmain*/Dataitemsinoriginalorder10987654321AfterPass1:98765432110AfterPass2:876543219AfterPass3:76543218AfterPass4:6543217AfterPass5:543216AfterPass6:43215AfterPass7:3214AfterPass8:213AfterPass9:12Dataitemsinascendingorder123456789106.12Writesinglestatementsthatperformeachofthefollowingsingle-subscriptedarrayoperations:a)Initializethe10elementsofintegerarraycountstozeros.ANS:for(i=0;i<=9;i++)counts[i]=0;b)Add1toeachofthe15elementsofintegerarraybonus.ANS:for(i=0;i<=14;i++)++bonus[i];c)Readthe12valuesoffloating-pointarraymonthlyTemperaturesfromthekeyboard.ANS:for(i=0;i<=11;i++){printf(“Enteratemperature:”);scanf(“%f”,&monthlyTemperatures[i]);}d)Printthe5valuesofintegerarraybestScoresincolumnformat.ANS:for(i=0;i<=4;i++){printf(“%dt”,bestScores[i]);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com176CArrays:SolutionsChapter66.13Findtheerror(s)ineachofthefollowingstatements:a)Assume:charstr[5];scanf("%s",str);/*Usertypeshello*/ANS:strneedsaminimumlengthof6;oneelementforeachletterinhelloandanelementfortheterminatingNULLcharacter.b)Assume:inta[3];printf("$d%d%dn",a[1],a[2],a[3]);ANS:printf(“%d%d%dn”,a[0],a[1],a[2]);c)doublef[3]={1.1,10.01,100.001,1000.0001};ANS:Toomanyvariablesdefined.doublef[3]={1.1,10.01,100.01};d)Assume:doubled[2][10];d[1,9]=2.345;ANS:d[1][9]=2.345;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions1776.14ModifytheprogramofFig.6.16sofunctionmodeiscapableofhandlingatieforthemodevalue.Alsomodifyfunctionmediansothetwomiddleelementsareaveragedinanarraywithanevennumberofelements.ANS:1/*Exercise6.14Solution*/2#include3#defineSIZE10045voidmean(intanswer[]);/*functionprototype*/6voidmedian(intanswer[]);/*functionprototype*/7voidmode(intfreq[],intanswer[]);/*functionprototype*/89intmain()10{1112/*arrayofresponses*/13intresponse[SIZE]={6,7,8,9,8,7,8,9,8,9,147,8,9,5,9,8,7,8,7,1,156,7,8,9,3,9,8,7,1,7,167,8,9,8,9,8,9,7,1,9,176,7,8,7,8,7,9,8,9,2,187,8,9,8,9,8,9,7,5,3,195,6,7,2,5,3,9,4,6,4,207,8,9,6,8,7,8,9,7,1,217,4,4,2,5,3,8,7,5,6,224,5,6,1,6,5,7,8,7,9};23intfrequency[10]={0};/*arrayofresponsefrequencies*/2425mean(response);/*processmean*/26median(response);/*processmedian*/27mode(frequency,response);/*processmode*/2829return0;/*indicatessuccessfultermination*/3031}/*endmain*/3233/*calculateaverageofallresponsevalues*/34voidmean(intanswer[])35{36intj;/*loopcounter*/37inttotal=0;/*totalofallresponsevalues*/3839printf("%sn%sn%sn","******","Mean","******");4041/*totalresponsevalues*/42for(j=0;j<=SIZE-1;j++){43total+=answer[j];44}/*endfor*/4546/*outputresults*/47printf("Themeanistheaveragevalueofthedatan");48printf("items.Themeanisequaltothetotalofn");49printf("allthedataitemsdividedbythenumbern");50printf("ofdataitems(%d).,",SIZE);51printf("Themeanvalueforthisrunis:");52printf("%d/%d=%.4fnn",total,SIZE,(double)total/SIZE);53}/*endfunctionmean*/5455/*sortanarrayanddeterminemedianelement"svalue*/56voidmedian(intanswer[])57{58intloop;/*loopcounter*/59intpass;/*loopcounter*/60inthold;/*temporaryvariableforswapping*/61intfirstRow;/*flagtoindicatefirstrowofarray*/6263printf("n%sn%sn%sn","******","Median","******");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com178CArrays:SolutionsChapter664printf("Theunsortedarrayofresponsesisn");6566/*displayunsortedarray*/67for(loop=0,firstRow=1;loop<=SIZE-1;loop++){6869/*startanewline*/70if(loop%20==0&&!firstRow){71printf("n");72}/*endif*/7374printf("%2d",answer[loop]);75firstRow=0;76}/*endfor*/7778printf("nn");7980/*sortarray*/81for(pass=0;pass<=SIZE-2;pass++){8283/*compareelementsandswapifnecessary*/84for(loop=0;loop<=SIZE-2;loop++){8586/*swapelements*/87if(answer[loop]>answer[loop+1]){88hold=answer[loop];89answer[loop]=answer[loop+1];90answer[loop+1]=hold;91}/*endif*/9293}/*endfor*/9495}/*endfor*/9697printf("Thesortedarrayisn");9899/*displaysortedarray*/100for(loop=0,firstRow=1;loop<=SIZE-1;loop++){101102/*startanewline*/103if(loop%20==0&&!firstRow){104printf("n");105}/*endif*/106107printf("%2d",answer[loop]);108firstRow=0;109}/*endfor*/110111printf("nn");112113/*evennumberofelements*/114if(SIZE%2==0){115printf("Themedianistheaverageofelements%d",116(SIZE+1)/2);117printf("and%dof",1+(SIZE+1)/2);118printf("thesorted%delementarray.n",SIZE);119printf("Forthisrunthemedianis");120printf("%.1fnn",(double)(answer[(SIZE+1)/2]+121answer[(SIZE+1)/2+1])/2);122}/*endif*/123else{/*oddnumberofelements*/124printf("Themedianiselement%dof",(SIZE+1)/2);125printf("thesorted%delementarray.n",SIZE);126printf("Forthisrunthemedianis");127printf("%dnn",answer[(SIZE+1)/2-1]);128}/*endelse*/129130}/*endfunctionmedian*/131©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions179132/*determinemostfrequentresponse*/133voidmode(intfreq[],intanswer[])134{135intrating;/*loopcounter*/136intloop;/*loopcounter*/137intlargest=0;/*representslargestfrequency*/138intarray[10]={0};/*arrayusedtoholdlargestfrequencies*/139intcount=0;/*flagtocountnumberofmodes*/140141printf("n%sn%sn%sn","******","Mode","******");142143/*setallfrequenciesto0*/144for(rating=1;rating<=9;rating++){145freq[rating]=0;146}/*endfor*/147148/*traversearrayandincrementcorrespondingfrequency*/149for(loop=0;loop<=SIZE-1;loop++){150++freq[answer[loop]];151}/*endfor*/152153printf("%s%11s%19snn","Response","Frequency","Histogram");154printf("%54sn","1122");155printf("%54snn","50505");156157/*displayvaluesandfrequency*/158for(rating=1;rating<=9;rating++){159printf("%8d%11d",rating,freq[rating]);160161/*testifcurrentfrequencyisgreaterthanlargestfrequency*/162if(freq[rating]>largest){163largest=freq[rating];164165/*setvaluesofarrayto0*/166for(loop=0;loop<10;loop++){167array[loop]=0;168}/*endfor*/169170/*addnewlargestfrequencytoarray*/171array[rating]=largest;172++count;173}/*endif*/174/*ifcurrentfrequencyequalslargest,addcurrenttoarray*/175elseif(freq[rating]==largest){176array[rating]=largest;177++count;178}/*endelseif*/179180/*displayhistogram*/181for(loop=1;loop<=freq[rating];loop++){182printf("*");183}/*endfor*/184185printf("n");186}/*endfor*/187188printf("n");189190/*ifmorethanonemode*/191if(count>1){192printf("Themodesare:");193}/*endif*/194else{/*onlyonemode*/195printf("Themodeis:");196}/*endelse*/197198/*displaymode(s)*/199for(loop=1;loop<=9;loop++){©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com180CArrays:SolutionsChapter6200201if(array[loop]!=0){202printf("%dwithafrequencyof%dntt",loop,array[loop]);203}/*endif*/204205}/*endfor*/206207printf("n");208}/*endfunctionmode*/******Mean******Themeanistheaveragevalueofthedataitems.Themeanisequaltothetotalofallthedataitemsdividedbythenumberofdataitems(100).,Themeanvalueforthisrunis:662/100=6.6200******Median******Theunsortedarrayofresponsesis6789878989789598787167893987177898989719678787989278989897535672539464789687897174425387564561657879Thesortedarrayis1111122233334444455555555666666666777777777777777777777778888888888888888888888899999999999999999999Themedianistheaverageofelements50and51ofthesorted100elementarray.Forthisrunthemedianis7.0******Mode******ResponseFrequencyHistogram11225050515*****23***34****45*****58********69*********723***********************823***********************920********************Themodesare:7withafrequencyof238withafrequencyof23©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions1816.15Useasingle-subscriptedarraytosolvethefollowingproblem.Readin20numbers,eachofwhichisbetween10and100,inclusive.Aseachnumberisread,printitonlyifitisnotaduplicateofanumberalreadyread.Provideforthe“worstcase”inwhichall20numbersaredifferent.Usethesmallestpossiblearraytosolvethisproblem.ANS:1/*Exercise6.15Solution*/2#include3#defineMAX2045intmain()6{7inta[MAX]={0};/*arrayforuserinput*/8inti;/*loopcounter*/9intj;/*loopcounter*/10intk=0;/*numberofvaluescurrentlyentered*/11intduplicate;/*flagforduplicatevalues*/12intvalue;/*currentvalue*/1314printf("Enter20integersbetween10and100:n");1516/*get20integersfromuser*/17for(i=0;i<=MAX-1;i++){18duplicate=0;19scanf("%d",&value);2021/*testifintegerisaduplicate*/22for(j=0;j4#defineSIZE1056intwhatIsThis(constintb[],intp);/*functionprototype*/78/*functionmainbeginsprogramexecution*/9intmain()10{11intx;/*holdsreturnvalueoffunctionwhatIsThis*/1213/*initializearraya*/14inta[SIZE]={1,2,3,4,5,6,7,8,9,10};1516x=whatIsThis(a,SIZE);1718printf("Resultis%dn",x);1920return0;/*indicatessuccessfultermination*/2122}/*endmain*/2324/*whatdoesthisfunctiondo?*/25intwhatIsThis(constintb[],intp)26{27/*basecase*/28if(p==1){29returnb[0];30}/*endif*/31else{/*recursionstep*/3233returnb[p-1]+whatIsThis(b,p-1);34}/*endelse*/3536}/*endfunctionwhatIsThis*/ANS:Theprogramrecursivelysumstheelementsina.Resultis55©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com184CArrays:SolutionsChapter66.18Whatdoesthefollowingprogramdo?1/*ex06_18.c*/2/*Whatdoesthisprogramdo?*/3#include4#defineSIZE1056/*functionprototype*/7voidsomeFunction(constintb[],intstartIndex,intsize);89/*functionmainbeginsprogramexecution*/10intmain()11{12inta[SIZE]={8,3,1,2,6,0,9,7,4,5};/*initializea*/1314printf("Answeris:n");15someFunction(a,0,SIZE);16printf("n");1718return0;/*indicatessuccessfultermination*/1920}/*endmain*/2122/*Whatdoesthisfunctiondo?*/23voidsomeFunction(constintb[],intstartIndex,intsize)24{25if(startIndex3#include4#include56intmain()7{8longi;/*loopcounter*/9intj;/*loopcounter*/10intx;/*firstdie*/11inty;/*seconddie*/12intsum[13]={0};/*countoccurrencesofeachcombination*/1314/*arrayexpectedcontainscountsfortheexpected15numberoftimeseachsumoccursin36rollsofthedice*/16intexpected[13]={0,0,1,2,3,4,5,6,5,4,3,2,1};1718srand(time(NULL));/*seedrandomnumbergenerator*/1920/*rolldice36,000times*/21for(i=1;i<=36000;i++){22x=1+rand()%6;23y=1+rand()%6;24++sum[x+y];25}/*endfor*/2627printf("%10s%10s%10s%10sn","Sum","Total","Expected","Actual");2829/*displayresultsofrollingdice*/30for(j=2;j<=12;j++){31printf("%10d%10d%9.3f%%%9.3f%%n",j,sum[j],32100.0*expected[j]/36,100.0*sum[j]/36000);33}/*endfor*/3435return0;/*indicatesuccessfultermination*/3637}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com186CArrays:SolutionsChapter6SumTotalExpectedActual210182.778%2.828%320085.556%5.578%430208.333%8.389%5402411.111%11.178%6489113.889%13.586%7601116.667%16.697%8506513.889%14.069%9398411.111%11.067%1029708.333%8.250%1119895.556%5.525%1210202.778%2.833%©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions1876.20Writeaprogramthatruns1000gamesofcraps(withouthumanintervention)andanswerseachofthefollowingquestions:a)Howmanygamesarewononthefirstroll,secondroll,…,twentiethrollandafterthetwentiethroll?b)Howmanygamesarelostonthefirstroll,secondroll,…,twentiethrollandafterthetwentiethroll?c)Whatarethechancesofwinningatcraps?[Note:Youshoulddiscoverthatcrapsisoneofthefairestcasinogames.Whatdoyousupposethismeans?]d)Whatistheaveragelengthofagameofcraps?e)Dothechancesofwinningimprovewiththelengthofthegame?ANS:1/*Exercise6.20Solution*/2#include3#include4#include56enumOutcome{CONTINUE,WIN,LOSE};78introllDice(void);/*functionprototype*/910intmain()11{12enumOutcomegameStatus;/*gamestatusindicator*/13intsum;/*sumofrolleddice*/14intmyPoint;/*currentpoint*/15inti;/*gamecounter*/16introll;/*rollcounter*/17intlength=0;/*averagelengthofgame*/18intwins[22]={0};/*winsperroll*/19intlosses[22]={0};/*lossesperroll*/20intwinSum=0;/*totalwins*/21intloseSum=0;/*totallosses*/2223srand(time(NULL));2425/*play1000times*/26for(i=1;i<=1000;i++){27sum=rollDice();28roll=1;2930/*testifgamewonorlostonfirstroll*/31switch(sum){3233case7:34case11:35gameStatus=WIN;36break;/*exitswitch*/3738case2:39case3:40case12:41gameStatus=LOSE;42break;/*exitswitch*/4344default:45gameStatus=CONTINUE;46myPoint=sum;47break;/*exitswitch*/48}/*endswitch*/4950/*continuewhilegamenotwonorlost*/51while(gameStatus==0){52sum=rollDice();53roll++;5455/*winonnextroll*/56if(sum==myPoint){57gameStatus=WIN;58}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com188CArrays:SolutionsChapter659else{/*loseonnextroll*/6061if(sum==7){62gameStatus=LOSE;63}/*endif*/6465}/*endelse*/6667}/*endwhile*/6869/*ifmorethan21rollstaken,setnumberofrollsto21*/70if(roll>21){71roll=21;72}/*endif*/7374/*determinehowmanyrollsweretakenandincrement75correspondingcounterinwinsorlossesarray*/76if(gameStatus==WIN){77wins[roll]++;78winSum++;79}/*endif*/80else{81losses[roll]++;82loseSum++;83}/*endelse*/8485}/*endfor*/8687printf("Gameswonorlostafterthe20throlln"88"aredisplayedasthe21stroll.nn");8990/*displaynumberofgameswonandlostforeachnumberofrolls*/91for(i=1;i<=21;i++){92printf("%3dgameswonand%3dgameslostonroll%d.n",93wins[i],losses[i],i);94}/*endfor*/9596/*calculatechancesofwinning*/97printf("nThechancesofwinningare%d/%d=%.2f%%n",winSum,98winSum+loseSum,100.0*winSum/(winSum+loseSum));99100/*calculateaveragelengthofgame*/101for(i=1;i<=21;i++){102length+=wins[i]*i+losses[i]*i;103}/*endfor*/104105printf("Theaveragegamelengthis%.2frolls.n",106length/1000.0);107108return0;/*indicatesuccessfultermination*/109110}/*endmain*/111112/*functiontosimulatedicerolling*/113introllDice(void)114{115intdie1;/*firstdie*/116intdie2;/*seconddie*/117intworkSum;/*dicesum*/118119die1=1+rand()%6;120die2=1+rand()%6;121workSum=die1+die2;122123returnworkSum;/*returntotaloftwodice*/124125}/*endfunctionrollDice*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions189Gameswonorlostafterthe20throllaredisplayedasthe21stroll.212gameswonand102gameslostonroll1.63gameswonand109gameslostonroll2.54gameswonand92gameslostonroll3.45gameswonand70gameslostonroll4.40gameswonand54gameslostonroll5.17gameswonand34gameslostonroll6.9gameswonand21gameslostonroll7.10gameswonand11gameslostonroll8.7gameswonand9gameslostonroll9.3gameswonand2gameslostonroll10.6gameswonand12gameslostonroll11.4gameswonand4gameslostonroll12.1gameswonand1gameslostonroll13.1gameswonand0gameslostonroll14.0gameswonand1gameslostonroll15.1gameswonand1gameslostonroll16.0gameswonand0gameslostonroll17.0gameswonand1gameslostonroll18.1gameswonand1gameslostonroll19.0gameswonand0gameslostonroll20.0gameswonand1gameslostonroll21.Thechancesofwinningare474/1000=47.40%Theaveragegamelengthis3.36rolls.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com190CArrays:SolutionsChapter66.21(AirlineReservationsSystem)Asmallairlinehasjustpurchasedacomputerforitsnewautomatedreservationssystem.Thepresidenthasaskedyoutoprogramthenewsystem.Youaretowriteaprogramtoassignseatsoneachflightoftheairline"sonlyplane(capacity:10seats).Yourprogramshoulddisplaythefollowingmenuofalternatives:Pleasetype1for"firstclass"Pleasetype2for"economy"Ifthepersontypes1,thenyourprogramshouldassignaseatinthefirstclasssection(seats1-5).Ifthepersontypes2,thenyourprogramshouldassignaseatintheeconomysection(seats6-10).Yourprogramshouldthenprintaboardingpassindicatingtheperson"sseatnumberandwhetheritisinthefirstclassoreconomysectionoftheplane.Useasingle-subscriptedarraytorepresenttheseatingchartoftheplane.Initializealltheelementsofthearrayto0toindicatethatallseatsareempty.Aseachseatisassigned,setthecorrespondingelementsofthearrayto1toindicatethattheseatisnolongeravailable.Yourprogramshould,ofcourse,neverassignaseatthathasalreadybeenassigned.Whenthefirstclasssectionisfull,yourprogramshouldaskthepersonifitisacceptabletobeplacedintheeconomysection(andviceversa).Ifyes,thenmaketheappro-priateseatassignment.Ifno,thenprintthemessage"Nextflightleavesin3hours."ANS:1/*Exercise6.21Solution*/2#include3#include45intmain()6{7intplane[11]={0};/*seatsontheplane*/8inti=0;/*counter*/9intfirstClass=1;/*firstclassseatsstartat1*/10inteconomy=6;/*economyseatsstartat6*/11intchoice;/*user"schoice*/12charresponse[2];/*user"sresponse*/1314/*loop10times*/15while(i<10){16printf("n%sn%sn?","Pleasetype1for"firstclass"",17"Pleasetype2for"economy"");18scanf("%d",&choice);1920/*ifuserselectsfirstclass*/21if(choice==1){2223/*ifseatareavailableinfirstclass*/24if(!plane[firstClass]&&firstClass<=5){25printf("Yourseatassignmentis%dn",firstClass);26plane[firstClass++]=1;27i++;28}/*endif*/29/*ifnofirstclassseats,buteconomyseatsavailable*/30elseif(firstClass>5&&economy<=10){3132/*askifpassengerwouldliketositineconomy*/33printf("Thefirstclasssectionisfull.n");34printf("Wouldyouliketositintheeconomy");35printf("section(YorN)?");36scanf("%s",response);3738/*ifresponseisyes,thenassignseat*/39if(toupper(response[0])=="Y"){40printf("Yourseatassignmentis%dn",economy);41plane[economy++]=1;42i++;43}/*endif*/44else{/*printnextdeparture*/45printf("Nextflightleavesin3hours.n");46}/*endelse*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions1914748}/*endelseif*/49else{/*printnextdeparture*/50printf("Nextflightleavesin3hours.n");51}/*endelse*/5253}/*endif*/54else{/*ifuserselectseconomy*/5556/*ifseatsavailable,assignseat*/57if(!plane[economy]&&economy<=10){58printf("Yourseatassignmentis%dn",economy);59plane[economy++]=1;60i++;61}/*endif*/62/*ifonlyfirstclassseatsareavailable*/63elseif(economy>10&&firstClass<=5){6465/*askiffirstclassissuitable*/66printf("Theeconomysectionisfull.n");67printf("Wouldyouliketositinfirstclass");68printf("section(YorN)?");69scanf("%s",response);7071/*ifresponseisyes,assignseat*/72if(toupper(response[0])=="Y"){73printf("Yourseatassignmentis%dn",firstClass);74plane[firstClass++]=1;75i++;76}/*endif*/77else{/*printnextdeparture*/78printf("Nextflightleavesin3hours.n");79}/*endelse*/8081}/*endelseif*/82else{/*printnextdeparture*/83printf("Nextflightleavesin3hours.n");84}/*endelse*/8586}/*endelse*/8788}/*endwhile*/8990printf("nAllseatsforthisflightaresold.n");9192return0;/*indicatesuccessfultermination*/9394}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com192CArrays:SolutionsChapter6Pleasetype1for"firstclass"Pleasetype2for"economy"?2Yourseatassignmentis6Pleasetype1for"firstclass"Pleasetype2for"economy"?1Yourseatassignmentis1Pleasetype1for"firstclass"Pleasetype2for"economy"?2Yourseatassignmentis7...Pleasetype1for"firstclass"Pleasetype2for"economy"?1Thefirstclasssectionisfull.Wouldyouliketositintheeconomysection(YorN)?nNextflightleavesin3hours.Pleasetype1for"firstclass"Pleasetype2for"economy"?1Thefirstclasssectionisfull.Wouldyouliketositintheeconomysection(YorN)?yYourseatassignmentis9Pleasetype1for"firstclass"Pleasetype2for"economy"?2Yourseatassignmentis10Allseatsforthisflightaresold.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions1936.22Useadouble-subscriptedarraytosolvethefollowingproblem.Acompanyhasfoursalespeople(1to4)whosellfivedif-ferentproducts(1to5).Onceaday,eachsalespersonpassesinaslipforeachdifferenttypeofproductsold.Eachslipcontains:a)Thesalespersonnumberb)Theproductnumberc)ThetotaldollarvalueofthatproductsoldthatdayThus,eachsalespersonpassesinbetween0and5salesslipsperday.Assumethattheinformationfromalloftheslipsforlastmonthisavailable.Writeaprogramthatwillreadallthisinformationforlastmonth’ssalesandsummarizethetotalsalesbysales-personbyproduct.Alltotalsshouldbestoredinthedouble-subscriptedarraysales.Afterprocessingalltheinformationforlastmonth,printtheresultsintabularformatwitheachofthecolumnsrepresentingaparticularsalespersonandeachoftherowsrep-resentingaparticularproduct.Crosstotaleachrowtogetthetotalsalesofeachproductforlastmonth;crosstotaleachcolumntogetthetotalsalesbysalespersonforlastmonth.Yourtabularprintoutshouldincludethesecrosstotalstotherightofthetotaledrowsandtothebottomofthetotaledcolumns.ANS:1/*Exercise6.22Solution*/2#include34intmain()5{67/*totalsalesforeachsalespersonandeachproduct*/8doublesales[4][5]={0.0};9doubleproductSales[5]={0.0};/*totalproductsales*/10doublevalue;/*currentsales*/11doubletotalSales;/*totaloverallsales*/12intsalesPerson;/*currentsalesperson*/13intproduct;/*currentproduct*/14inti;/*loopcounter*/15intj;/*loopcounter*/1617printf("Enterthesalesperson,product,andtotalsales.n");18printf("Enter-1forthesalesperontoendinput.n");19scanf("%d",&salesPerson);2021/*continuereceivinginputforeachsalesperson22while-1isnotentered*/23while(salesPerson!=-1){24scanf("%d%lf",&product,&value);25sales[salesPerson][product]=value;26scanf("%d",&salesPerson);27}/*endwhile*/2829/*displaytable*/30printf("n%sn%sn%sn%sn%sn","Thetotalsalesforeachsalesperson",31"aredisplayedattheendofeach","row,andthetotalsalesforeach",32"productaredisplayedatthebottom","ofeachcolumn.n");33printf("%8d%8d%8d%8d%8dn",1,2,3,4,5);3435/*displaysalespeopleandsales*/36for(i=0;i<=3;i++){37totalSales=0.0;38printf("%d",i);3940/*addtotalsalesanddisplayindividualsales*/41for(j=0;j<=4;j++){42totalSales+=sales[i][j];43printf("%8.2f",sales[i][j]);44productSales[j]+=sales[i][j];45}/*endfor*/4647printf("%8.2fn",totalSales);48}/*endfor*/4950printf("");51©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com194CArrays:SolutionsChapter652/*displaytotalproductsales*/53for(j=0;j<=4;j++){54printf("%8.2f",productSales[j]);55}/*endfor*/5657return0;/*indicatesuccessfultermination*/5859}/*endmain*/Enterthesalesperson,product,andtotalsales.Enter-1forthesalesperontoendinput.001.00012.00023.00034.00045.00101.00112.00123.00134.00145.00201.00212.00223.00234.00245.00301.00312.00323.00334.00345.00-1Thetotalsalesforeachsalespersonaredisplayedattheendofeachrow,andthetotalsalesforeachproductaredisplayedatthebottomofeachcolumn.1234501.002.003.004.005.0015.0011.002.003.004.005.0015.0021.002.003.004.005.0015.0031.002.003.004.005.0015.004.008.0012.0016.0020.00©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions1956.23(TurtleGraphics)TheLogolanguage,whichisparticularlypopularamongpersonalcomputerusers,madetheconceptofturtlegraphicsfamous.ImagineamechanicalturtlethatwalksaroundtheroomunderthecontrolofaCprogram.Theturtleholdsapeninoneoftwopositions,upordown.Whilethepenisdown,theturtletracesoutshapesasitmoves;whilethepenisup,theturtlemovesaboutfreelywithoutwritinganything.Inthisproblemyouwillsimulatetheoperationoftheturtleandcreateacom-puterizedsketchpadaswell.Usea50-by-50arrayfloorwhichisinitializedtozeros.Readcommandsfromanarraythatcontainsthem.Keeptrackofthecurrentpositionoftheturtleatalltimesandwhetherthepeniscurrentlyupordown.Assumethattheturtlealwaysstartsatposi-tion0,0ofthefloorwithitspenup.ThesetofturtlecommandsyourprogrammustprocessareshowninFig.6.24.CommandMeaning1Penup2Pendown3Turnright4Turnleft5,10Moveforward10spaces(oranumberotherthan10)6Printthe20-by-20array9Endofdata(sentinel)Supposethattheturtleissomewherenearthecenterofthefloor.Thefollowing“program”woulddrawandprinta12-by12-square:25,1235,1235,1235,12169Astheturtlemoveswiththependown,settheappropriateelementsofarrayfloorto1s.Whenthe6command(print)isgiven,whereverthereisa1inthearray,displayanasterisk,orsomeothercharacteryouchoose.Whereverthereisazero,displayablank.Writeaprogramtoimplementtheturtlegraphicscapabilitiesdiscussedhere.Writeseveralturtlegraphicsprogramstodrawinterestingshapes.Addothercommandstoincreasethepowerofyourturtlegraphicslanguage.ANS:1/*Exercise6.23Solution*/2#include34#defineTRUE15#defineFALSE06#defineMAX100/*themaximumnumberofcommands*/78/*functionprototypes*/9voidgetCommands(intcommands[][2]);10intturnRight(intd);11intturnLeft(intd);12voidmovePen(intdown,inta[][50],intdir,intdist);13voidprintArray(inta[][50]);1415intmain()16{17intfloor[50][50]={0};/*floorgrid*/18intpenDown=FALSE;/*pendownflag*/19intcommand;/*currentcommand*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com196CArrays:SolutionsChapter620intdirection=0;/*directionindicator*/21intcommandArray[MAX][2]={0};/*arrayofcommands*/22intdistance;/*distancetomove*/23intcount=0;/*commandcounter*/2425getCommands(commandArray);26command=commandArray[count][0];2728/*continuereceivinginputwhile-9isnotentered*/29while(command!=9){3031/*determinewhatcommandwasenteredandperformaction*/32switch(command){3334case1:35penDown=FALSE;36break;/*exitswitch*/3738case2:39penDown=TRUE;40break;/*exitswitch*/4142case3:43direction=turnRight(direction);44break;/*exitswitch*/4546case4:47direction=turnLeft(direction);48break;/*exitswitch*/4950case5:51distance=commandArray[count][1];52movePen(penDown,floor,direction,distance);53break;/*exitswitch*/5455case6:56printf("nThedrawingis:nn");57printArray(floor);58break;/*exitswitch*/59}/*endswitch*/6061command=commandArray[++count][0];62}/*endwhile*/6364return0;/*indicatesuccessfultermination*/6566}/*endmain*/6768/*getCommandspromptsuserforcommands*/69voidgetCommands(intcommands[][2])70{71inti;/*counter*/72inttempCommand;/*temporarycommandholder*/7374printf("Entercommand(9toendinput):");75scanf("%d",&tempCommand);7677/*recievecommandsuntil-9or100commandsareentered*/78for(i=0;tempCommand!=9&&i3?0:d;9798}/*endfunctionturnRight*/99100/*turnLeftturnsturtletotheleft*/101intturnLeft(intd)102{103return--d<0?3:d;104105}/*endfunctionturnLeft*/106107/*movePenmovesthepen*/108voidmovePen(intdown,inta[][50],intdir,intdist)109{110inti;/*loopcounter*/111intj;/*loopcounter*/112staticintxPos=0;/*xcoordinate*/113staticintyPos=0;/*ycoordinate*/114115/*determinewhichwaytomovepen*/116switch(dir){117118case0:/*movetotheright*/119120/*movedistspacesoruntiledgeoffloor*/121for(j=1;j<=dist&&yPos+j<50;j++){122123/*draw1ifpenisdown*/124if(down){125a[xPos][yPos+j]=1;126}/*endif*/127128}/*endfor*/129130yPos+=j-1;131break;/*exitswitch*/132133case1:/*movedown*/134135/*movedistspacesoruntiledgeoffloor*/136for(i=1;i<=dist&&xPos+i<50;i++){137138/*draw1ifpenisdown*/139if(down){140a[xPos+i][yPos]=1;141}/*endif*/142143}/*endfor*/144145xPos+=i-1;146break;/*exitswitch*/147148case2:/*movetotheleft*/149150/*movedistspacesoruntiledgeoffloor*/151for(j=1;j<=dist&&yPos-j>=0;j++){152153/*draw1ifpenisdown*/154if(down){155a[xPos][yPos-j]=1;156}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com198CArrays:SolutionsChapter6157158}/*endfor*/159160yPos-=j-1;161break;/*exitswitch*/162163case3:/*moveup*/164165/*movedistspacesoruntiledgeoffloor*/166for(i=1;i<=dist&&xPos-i>=0;i++){167168/*draw1ifpenisdown*/169if(down){170a[xPos-i][yPos]=1;171}/*endif*/172173}/*endfor*/174175xPos-=i-1;176break;/*exitswitch*/177}/*endswitch*/178179}/*endfunctionmovePen*/180181/*printArrayprintsarraydrawing*/182voidprintArray(inta[][50])183{184inti;/*counter*/185intj;/*counter*/186187/*loopthrougharray*/188for(i=0;i<50;i++){189190/*loopthrougharray*/191for(j=0;j<50;j++){192putchar(a[i][j]?"*":"");193}/*endfor*/194195putchar("n");196}/*endfor*/197198}/*endfunctionprintArray*/Entercommand(9toendinput):2Entercommand(9toendinput):5,12Entercommand(9toendinput):3Entercommand(9toendinput):5,12Entercommand(9toendinput):3Entercommand(9toendinput):5,12Entercommand(9toendinput):3Entercommand(9toendinput):5,12Entercommand(9toendinput):1Entercommand(9toendinput):6Entercommand(9toendinput):9Thedrawingis:************************************************©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions1996.24(Knight’sTour)OneofthemoreinterestingpuzzlersforchessbuffsistheKnight"sTourproblem,originallyproposedbythemathematicianEuler.Thequestionisthis:Canthechesspiececalledtheknightmovearoundanemptychessboardandtoucheachofthe64squaresonceandonlyonce?Westudythisintriguingproblemindepthhere.TheknightmakesL-shapedmoves(overtwoinonedirectionandthenoveroneinaperpendiculardirection).Thus,fromasquareinthemiddleofanemptychessboard,theknightcanmakeeightdifferentmoves(numbered0through7)asshowninFig.6.25.a)Drawan8-by-8chessboardonasheetofpaperandattemptaKnight"sTourbyhand.Puta1inthefirstsquareyoumoveto,a2inthesecondsquare,a3inthethird,etc.Beforestartingthetour,estimatehowfaryouthinkyouwillget,rememberingthatafulltourconsistsof64moves.Howfardidyouget?Wereyouclosetotheestimate?b)Nowletusdevelopaprogramthatwillmovetheknightaroundachessboard.Theboarditselfisrepresentedbyan8-by-8double-subscriptedarrayboard.Eachofthesquaresisinitializedtozero.Wedescribeeachoftheeightpossiblemovesintermsofboththeirhorizontalandverticalcomponents.Forexample,amoveoftype0asshowninFig.6.25consistsofmovingtwosquareshorizontallytotherightandonesquareverticallyupward.Move2consistsofmovingonesquarehorizontallytotheleftandtwosquaresverticallyupward.Horizontalmovestotheleftandverticalmovesupwardareindicatedwithnegativenumbers.Theeightmovesmaybedescribedbytwosingle-subscriptedarrays,hor-izontalandvertical,asfollows:0123456701212303K44755667horizontal[0]=2horizontal[1]=1horizontal[2]=-1horizontal[3]=-2horizontal[4]=-2horizontal[5]=-1horizontal[6]=1horizontal[7]=2vertical[0]=-1vertical[1]=-2vertical[2]=-2vertical[3]=-1vertical[4]=1vertical[5]=2vertical[6]=2vertical[7]=1LetthevariablescurrentRowandcurrentColumnindicatetherowandcolumnoftheknight"scurrentpositionontheboard.TomakeamoveoftypemoveNumber,wheremoveNumberisbetween0and7,yourprogramusesthestatements©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com200CArrays:SolutionsChapter6currentRow+=vertical[moveNumber];currentColumn+=horizontal[moveNumber];Keepacounterthatvariesfrom1to64.Recordthelatestcountineachsquaretheknightmovesto.Remembertotesteachpotentialmovetoseeiftheknighthasalreadyvisitedthatsquare.And,ofcourse,testeverypotentialmovetomakesurethattheknightdoesnotlandoffthechessboard.Nowwriteaprogramtomovetheknightaroundthechess-board.Runtheprogram.Howmanymovesdidtheknightmake?c)AfterattemptingtowriteandrunaKnight"sTourprogram,youhaveprobablydevelopedsomevaluableinsights.Wewillusethesetodevelopaheuristic(orstrategy)formovingtheknight.Heuristicsdonotguaranteesuccess,butacarefullydevelopedheuristicgreatlyimprovesthechanceofsuccess.Youmayhaveobservedthattheoutersquaresareinsomesensemoretroublesomethanthesquaresnearerthecenteroftheboard.Infact,themosttroublesome,orinac-cessible,squaresarethefourcorners.Intuitionmaysuggestthatyoushouldattempttomovetheknighttothemosttroublesomesquaresfirstandleaveopenthosethatareeasiesttogettosothatwhentheboardgetscongestedneartheendofthetourtherewillbeagreaterchanceofsuccess.Wemaydevelopan“accessibilityheuristic”byclassifyingeachofthesquaresaccordingtohowaccessibletheyareandalwaysmovingtheknighttothesquare(withintheknight"sL-shapedmoves,ofcourse)thatismostinacces-sible.Welabeladouble-subscriptedarrayaccessibilitywithnumbersindicatingfromhowmanysquareseachpar-ticularsquareisaccessible.Onablankchessboard,thecentersquaresarethereforeratedas8s,thecornersquaresareratedas2s,andtheothersquareshaveaccessibilitynumbersof3,4,or6asfollows:2344443234666643468888644688886446888864468888643466664323444432NowwriteaversionoftheKnight"sTourprogramusingtheaccessibilityheuristic.Atanytime,theknightshouldmovetothesquarewiththelowestaccessibilitynumber.Incaseofatie,theknightmaymovetoanyofthetiedsquares.Therefore,thetourmaybegininanyofthefourcorners.[Note:Astheknightmovesaroundthechessboard,yourpro-gramshouldreducetheaccessibilitynumbersasmoreandmoresquaresbecomeoccupied.Inthisway,atanygiventimeduringthetour,eachavailablesquare"saccessibilitynumberwillremainequaltopreciselythenumberofsquaresfromwhichthatsquaremaybereached.]Runthisversionofyourprogram.Didyougetafulltour?Nowmodifytheprogramtorun64tours,onefromeachsquareofthechessboard.Howmanyfulltoursdidyouget?d)WriteaversionoftheKnight’sTourprogramwhich,whenencounteringatiebetweentwoormoresquares,decideswhatsquaretochoosebylookingaheadtothosesquaresreachablefromthe“tied”squares.Yourprogramshouldmovetothesquareforwhichthenextmovewouldarriveatasquarewiththelowestaccessibilitynumber.ANS:1/*Exercise6.24PartCSolution*/2/*Knight"sTour-accessversion*/3/*runsonetour*/45#include6#include7#include89#defineTRUE110#defineFALSE01112/*functionprototypes*/13voidclearBoard(intworkBoard[][8]);14voidprintBoard(intworkBoard[][8]);15intvalidMove(introw,intcolumn,intworkBoard[][8]);1617intmain()18{19intboard[8][8];/*chessboard*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions2012021/*arrayofaccesibility*/22intaccess[8][8]={2,3,4,4,4,4,3,2,233,4,6,6,6,6,4,3,244,6,8,8,8,8,6,4,254,6,8,8,8,8,6,4,264,6,8,8,8,8,6,4,274,6,8,8,8,8,6,4,283,4,6,6,6,6,4,3,292,3,4,4,4,4,3,2};3031/*eighthorizontalandverticalmovesfortheknight*/32inthorizontal[8]={2,1,-1,-2,-2,-1,1,2};33intvertical[8]={-1,-2,-2,-1,1,2,2,1};34intcurrentRow;/*currentrow*/35intcurrentColumn;/*currentcolumn*/36intmoveNumber=0;/*movecounter*/37inttestRow;/*possiblenextrow*/38inttestColumn;/*possiblenextcolumn*/39intminRow;/*rowwithminimumaccessnumber*/40intminColumn;/*columnwithminimumaccessnumber*/41intminAccess=9;/*impossibleaccessnumber*/42intaccessNumber;/*currentaccessnumber*/43intmoveType;/*currentmovetype*/44intdone;/*flagtoindicateend*/4546srand(time(NULL));4748clearBoard(board);/*initializearrayboard*/49currentRow=rand()%8;50currentColumn=rand()%8;51board[currentRow][currentColumn]=++moveNumber;52done=FALSE;5354/*continuewhileknightstillhasvalidmoves*/55while(!done){56accessNumber=minAccess;5758/*loopthroughallmovetypes*/59for(moveType=0;moveType<8;moveType++){60testRow=currentRow+vertical[moveType];61testColumn=currentColumn+horizontal[moveType];6263/*makesuremoveisvalid*/64if(validMove(testRow,testColumn,board)){6566/*ifmoveisvalidandhaslowestaccessNumber,67setsquaretoaccessNumber*/68if(access[testRow][testColumn]=0&&row<=7&&column>=0&&153column<=7&&workBoard[row][column]==0);154155}/*endfunctionvalidMove*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions203Thetourendedwith64moves.Thiswasafulltour!Theboardforthistestis:0123456703330194232817212053229183242723134492237261163621365950473825435605148395815465107625754454043661529126342551478116453561344416.25(Knight’sTour:BruteForceApproaches)InExercise6.24wedevelopedasolutiontotheKnight"sTourproblem.Theap-proachused,calledthe“accessibilityheuristic,”generatesmanysolutionsandexecutesefficiently.Ascomputerscontinueincreasinginpower,wewillbeabletosolvemanyproblemswithsheercomputerpowerandrelativelyunsophisticatedalgorithms.Letuscallthisapproach“bruteforce”problemsolving.a)Userandomnumbergenerationtoenabletheknighttowalkaroundthechessboard(initslegitimateL-shapedmoves,ofcourse)atrandom.Yourprogramshouldrunonetourandprintthefinalchessboard.Howfardidtheknightget?ANS:1/*Exercise6.25PartASolution*/2#include3#include4#include56#defineNO07#defineYES189/*functionprototypes*/10intvalidMove(introw,intcolumn,intworkBoard[][8]);11voidprintBoard(intboard[][8]);1213intmain()14{15intcurrentRow;/*currentrow*/16intcurrentColumn;/*currentcolumn*/17intmoveType;/*currentmovetype*/18intmoveNumber=0;/*movecounter*/19inttestRow;/*possiblenextrow*/20inttestColumn;/*possiblenextcolumn*/21intcount;/*counter*/22intdone;/*flagtoindicateend*/23intgoodMove;/*resultofcalltovalidMove*/2425/*horizontalandverticalmovesfortheknight,andboard*/26inthorizontal[8]={2,1,-1,-2,-2,-1,1,2};27intvertical[8]={-1,-2,-2,-1,1,2,2,1};28intboard[8][8]={0};2930srand(time(NULL));3132currentRow=rand()%8;33currentColumn=rand()%8;34board[currentRow][currentColumn]=++moveNumber;35done=NO;3637/*continuewhileknightcanstillmove*/38while(!done){39moveType=rand()%8;40testRow=currentRow+vertical[moveType];41testColumn=currentColumn+horizontal[moveType];©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com204CArrays:SolutionsChapter642goodMove=validMove(testRow,testColumn,board);4344/*testifdesiredmoveisvalid*/45if(goodMove){46currentRow=testRow;47currentColumn=testColumn;48board[currentRow][currentColumn]=++moveNumber;49}/*endif*/50else{5152/*ifmoveisnotlegaltryanotherrandommove*/53for(count=0;count<7&&!goodMove;count++){54moveType=++moveType%8;55testRow=currentRow+vertical[moveType];56testColumn=currentColumn+horizontal[moveType];57goodMove=validMove(testRow,testColumn,board);5859/*testifnewmoveisgood*/60if(goodMove){61currentRow=testRow;62currentColumn=testColumn;63board[currentRow][currentColumn]=++moveNumber;64}/*endif*/6566}/*endfor*/6768/*ifnovalidmoves,knightcannolongermove*/69if(!goodMove){70done=YES;71}/*endif*/7273}/*endelse*/7475/*if64moveshavebeenmade,afulltouriscomplete*/76if(moveNumber==64){77done=YES;78}/*endif*/7980}/*endwhile*/8182printf("Thetourhasendedwith%dmoves.n",moveNumber);8384/*testiffulltourwasmade*/85if(moveNumber==64){86printf("Thiswasafulltour!n");87}/*endif*/88else{89printf("Thiswasnotafulltour.n");90}/*endelse*/9192printf("Theboardforthisrandomtestwas:nn");93printBoard(board);/*printtheboard*/9495return0;/*indicatesuccessfultermination*/9697}/*endmain*/9899/*functiontotestwhetherasquareisontheboard100andhasnotbeenvisitedyet*/101intvalidMove(introw,intcolumn,intworkBoard[][8])102{103/*NOTE:Thisteststopsassoonasitbecomesfalse*/104return(row>=0&&row<8&&column>=0&&105column<8&&workBoard[row][column]==0);106107}/*endfunctionvalidMove*/108©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions205109/*functiontoprintthechessboard*/110voidprintBoard(intboard[][8])111{112introw;/*rowcounter*/113intcol;/*columncounter*/114115printf("01234567n");116117118/*printtherowsandcolumnsofthechessboard*/119for(row=0;row<8;row++){120printf("%d",row);121122for(col=0;col<8;col++){123printf("%3d",board[row][col]);124}/*endfor*/125126printf("n");127}/*endfor*/128129printf("n");130}/*endfunctionprintBoard*/Thetourhasendedwith32moves.Thiswasnotafulltour.Theboardforthisrandomtestwas:0123456701300011280321001229243180201400271025631801623307094150190026505201700220206002100004700000301b)Mostlikely,theprecedingprogramproducedarelativelyshorttour.Nowmodifyyourprogramtoattempt1000tours.Useasingle-subscriptedarraytokeeptrackofthenumberoftoursofeachlength.Whenyourprogramfinishesattempt-ingthe1000tours,itshouldprintthisinformationinneattabularformat.Whatwasthebestresult?ANS:1/*Exercise6.25PartBSolution*/2#include3#include4#include56#defineNO07#defineYES189intvalidMove(int,int,int[][8]);1011intmain()12{13intcurrentRow;/*currentrow*/14intcurrentColumn;/*currentcolumn*/15intmoveType;/*currentmovetype*/16intmoveNumber;/*movecounter*/17inttestRow;/*possiblenextrow*/18inttestColumn;/*possiblenextcolumn*/19intcount;/*counter*/20inti;/*counter*/21introw;/*row*/22intcol;/*column*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com206CArrays:SolutionsChapter623intdone;/*flagtoindicateend*/24intgoodMove;/*resultofcalltovalidMove*/25intboard[8][8];/*chessboard*/26intmoveTotal[65]={0};/*arrayoftourtotals*/2728/*horizontalandverticalmovesfortheknight*/29inthorizontal[8]={2,1,-1,-2,-2,-1,1,2};30intvertical[8]={-1,-2,-2,-1,1,2,2,1};3132srand(time(NULL));3334/*attempt1000tours*/35for(i=0;i<1000;i++){3637/*setallsquaresequalto0*/38for(row=0;row<8;row++){3940for(col=0;col<8;col++){41board[row][col]=0;42}/*endfor*/4344}/*endfor*/4546moveNumber=0;4748currentRow=rand()%8;49currentColumn=rand()%8;50board[currentRow][currentColumn]=++moveNumber;51done=NO;5253/*continuewhileknightstillhasvalidmoves*/54while(!done){55moveType=rand()%8;56testRow=currentRow+vertical[moveType];57testColumn=currentColumn+horizontal[moveType];58goodMove=validMove(testRow,testColumn,board);5960/*ifdesiredmoveisvalid,moveknighttosquare*/61if(goodMove){62currentRow=testRow;63currentColumn=testColumn;64board[currentRow][currentColumn]=++moveNumber;65}/*endif*/66else{6768/*ifmoveisinvalid,testotherpossiblemoves*/69for(count=0;count<7&&!goodMove;count++){70moveType=++moveType%8;71testRow=currentRow+vertical[moveType];72testColumn=currentColumn+horizontal[moveType];73goodMove=validMove(testRow,testColumn,board);7475/*ifmoveisvalid,moveknighttosquare*/76if(goodMove){77currentRow=testRow;78currentColumn=testColumn;79board[currentRow][currentColumn]=++moveNumber;80}/*endif*/8182}/*endfor*/8384/*ifnovalidmoves,whileloopexits*/85if(!goodMove){86done=YES;87}/*endif*/8889}/*endelse*/90©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions20791/*iffulltourismade,whileloopexits*/92if(moveNumber==64){93done=YES;94}/*endif*/9596}/*endwhile*/9798++moveTotal[moveNumber];99}/*endfor*/100101/*dislayhowmanytoursofeachmovenumberweremade*/102for(i=1;i<65;i++){103104if(moveTotal[i]){105printf("Therewere%dtoursof%dmoves.n",106moveTotal[i],i);107}/*endif*/108109}/*endfor*/110111return0;/*indicatesuccessfultermination*/112113}/*endmain*/114115/*functiontodetermineifamoveislegal*/116intvalidMove(inttestRow,inttestColumn,intboard[][8])117{118119/*testifsquareisonboardandifknighthaspreviously120visitedit*/121if(testRow>=0&&testRow<8&&testColumn>=0&&122testColumn<8){123returnboard[testRow][testColumn]!=0?NO:YES;124125}/*endif*/126else{127returnNO;128}/*endelse*/129130}/*endfunctionvalidMove*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com208CArrays:SolutionsChapter6Therewere1toursof4moves.Therewere3toursof5moves.Therewere2toursof6moves.Therewere3toursof7moves.Therewere2toursof8moves.Therewere4toursof10moves.Therewere5toursof11moves.Therewere4toursof12moves.Therewere5toursof13moves.Therewere7toursof14moves.Therewere7toursof15moves.Therewere9toursof16moves.Therewere8toursof17moves.Therewere10toursof18moves.Therewere9toursof19moves.Therewere9toursof20moves.Therewere11toursof21moves.Therewere19toursof22moves.Therewere17toursof23moves.Therewere18toursof24moves.Therewere12toursof25moves.Therewere20toursof26moves.Therewere14toursof27moves.Therewere18toursof28moves.Therewere22toursof29moves.Therewere21toursof30moves.Therewere31toursof31moves.Therewere28toursof32moves.Therewere25toursof33moves.Therewere32toursof34moves.Therewere26toursof35moves.Therewere40toursof36moves.Therewere38toursof37moves.Therewere38toursof38moves.Therewere37toursof39moves.Therewere33toursof40moves.Therewere35toursof41moves.Therewere34toursof42moves.Therewere33toursof43moves.Therewere36toursof44moves.Therewere30toursof45moves.Therewere35toursof46moves.Therewere26toursof47moves.Therewere37toursof48moves.Therewere22toursof49moves.Therewere17toursof50moves.Therewere20toursof51moves.Therewere21toursof52moves.Therewere17toursof53moves.Therewere19toursof54moves.Therewere14toursof55moves.Therewere3toursof56moves.Therewere7toursof57moves.Therewere3toursof59moves.Therewere3toursof60moves.c)Mostlikely,theprecedingprogramgaveyousome“respectable”toursbutnofulltours.Now“pullallthestopsout”andsimplyletyourprogramrununtilitproducesafulltour.[Caution:Thisversionoftheprogramcouldrunforhoursonapowerfulcomputer.]Onceagain,keepatableofthenumberoftoursofeachlengthandprintthistablewhenthefirstfulltourisfound.Howmanytoursdidyourprogramattemptbeforeproducingafulltour?Howmuchtimedidittake?d)ComparethebruteforceversionoftheKnight"sTourwiththeaccessibilityheuristicversion.Whichrequiredamorecarefulstudyoftheproblem?Whichalgorithmwasmoredifficulttodevelop?Whichrequiredmorecomputerpower?Couldwebecertain(inadvance)ofobtainingafulltourwiththeaccessibilityheuristicapproach?Couldwebecertain(inadvance)ofobtainingafulltourwiththebruteforceapproach?Arguetheprosandconsofbruteforceproblemsolvingingeneral.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions2096.26(EightQueens)AnotherpuzzlerforchessbuffsistheEightQueensproblem.Simplystated:Isitpossibletoplaceeightqueensonanemptychessboardsothatnoqueenis“attacking”anyother—thatis,sothatnotwoqueensareinthesamerow,thesamecolumn,oralongthesamediagonal?UsethekindofthinkingdevelopedinExercise6.24toformulateaheuristicforsolvingtheEightQueensproblem.Runyourprogram.[Hint:Itispossibletoassignanumericvaluetoeachsquareofthechessboardindi-catinghowmanysquaresofanemptychessboardare“eliminated”onceaqueenisplacedinthatsquare.Forexample,eachofthefourcornerswouldbeassignedthevalue22,asinFig.Fig.6.26.]**********************Fig.6.26The22squareseliminatedbyplacingaqueenintheupper-leftcorner.Oncethese“eliminationnumbers”areplacedinall64squares,anappropriateheuristicmightbe:Placethenextqueeninthesquarewiththesmallesteliminationnumber.Whyisthisstrategyintuitivelyappealing?6.27(EightQueens:BruteForceApproaches)InthisproblemyouwilldevelopseveralbruteforceapproachestosolvingtheEightQueensproblemintroducedinExercise6.26.a)SolvetheEightQueensproblem,usingtherandombruteforcetechniquedevelopedinExercise6.25.b)Useanexhaustivetechnique(i.e.,tryallpossiblecombinationsofeightqueensonthechessboard).c)WhydoyousupposetheexhaustivebruteforceapproachmaynotbeappropriateforsolvingtheKnight"sTourprob-lem?d)Compareandcontrasttherandombruteforceandexhaustivebruteforceapproachesingeneral.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com210CArrays:SolutionsChapter66.28(Duplicateelimination)InChapter12,weexplorethehigh-speedbinarysearchtreedatastructure.Onefeatureofabinarysearchtreeisthatduplicatevaluesarediscardedwheninsertionsaremadeintothetree.Thisisreferredtoasduplicateelimination.Writeaprogramthatproduces20randomnumbersbetween1and20.Theprogramshouldstoreallnonduplicatevaluesinanarray.Usethesmallestpossiblearraytoaccomplishthistask.1/*Exercise6.28Solution*/2#include3#include4#include56#defineSIZE2078intmain()9{10intloop;/*loopcounter*/11intrandNumber;/*currentrandomnumber*/12intloop2;/*loopcounter*/13intsubscript=0;/*arraysubscriptcounter*/14intduplicate;/*duplicateflag*/15intarray[SIZE]={0};/*arrayofrandomnumbers*/1617srand(time(NULL));1819/*loop20times*/20for(loop=0;loop<=SIZE-1;loop++){21duplicate=0;22randNumber=1+rand()%20;/*generaterandomnumber*/2324/*loopthroughcurrentnumbersinarray*/25for(loop2=0;loop2<=subscript;loop2++){2627/*comparerandNumberwithpreviousnumbers*/28if(randNumber==array[loop2]){29duplicate=1;30break;31}/*endif*/3233}/*endfor*/3435/*ifnotaduplicate*/36if(!duplicate){37array[subscript++]=randNumber;38}/*endif*/3940}/*endwhile*/4142printf("Non-repetitivearrayvaluesare:n");4344/*displayarray*/45for(loop=0;array[loop]!=0;loop++){46printf("ttttArray[%d]=%dn",loop,array[loop]);47}/*endfor*/4849return0;/*indicatesuccessfultermination*/5051}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions211Non-repetitivearrayvaluesare:Array[0]=11Array[1]=17Array[2]=3Array[3]=18Array[4]=9Array[5]=2Array[6]=20Array[7]=4Array[8]=1Array[9]=10Array[10]=7Array[11]=13Array[12]=19Array[13]=6Array[14]=8Array[15]=16©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com212CArrays:SolutionsChapter66.29(Knight’sTour:ClosedTourTest)IntheKnight’sTour,afulltouriswhentheknightmakes64movestouchingeachsquareofthechessboardonceandonlyonce.Aclosedtouroccurswhenthe64thmoveisonemoveawayfromthelocationinwhichtheknightstartedthetour.ModifytheKnight’sTourprogramyouwroteinExercise6.24totestforaclosedtourifafulltourhasoc-curred.ANS:1/*Exercise6.29Solution*/2#include3#include4#include56#defineTRUE17#defineFALSE089/*functionprototypes*/10voidclearBoard(intworkBoard[][8]);11voidprintBoard(intworkBoard[][8]);12intvalidMove(introw,intcolumn,intworkBoard[][8]);1314intmain(void)15{1617intfirstMoveRow;/*startingrow*/18intfirstMoveCol;/*startingcolumn*/19intclosedTour=0;/*closedtourflag*/20intcurrentRow;/*currentrow*/21intcurrentColumn;/*currentcolumn*/22intmoveNumber=0;/*movecounter*/23inttestRow;/*possiblenextrow*/24inttestColumn;/*possiblenextcolumn*/25intminRow;/*minimumrowaccessnumber*/26intminColumn;/*minimumcolumnaccessnumber*/27intminAccess=9;/*accessnumberreset*/28intaccessNumber;/*currentaccessnumber*/29intmoveType;/*currentmovetype*/30intdone;/*flagtoindicateend*/31intboard[8][8];/*chessboard*/3233/*horizontalandverticalmovesfortheknight*/34inthorizontal[8]={2,1,-1,-2,-2,-1,1,2};35intvertical[8]={-1,-2,-2,-1,1,2,2,1};3637/*accessgrid*/38intaccess[8][8]={2,3,4,4,4,4,3,2,393,4,6,6,6,6,4,3,404,6,8,8,8,8,6,4,414,6,8,8,8,8,6,4,424,6,8,8,8,8,6,4,434,6,8,8,8,8,6,4,443,4,6,6,6,6,4,3,452,3,4,4,4,4,3,2};464748srand(time(NULL));4950clearBoard(board);/*initializearrayboard*/51currentRow=rand()%8;52currentColumn=rand()%8;53firstMoveRow=currentRow;/*storefirstmovesrow*/54firstMoveCol=currentColumn;/*storefirstmovescol*/5556board[currentRow][currentColumn]=++moveNumber;57done=FALSE;5859/*loopwhileknightcanstillmove*/60while(!done){61accessNumber=minAccess;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions2136263/*testwhatmovesknightcanmake*/64for(moveType=0;moveType<8;moveType++){65testRow=currentRow+vertical[moveType];66testColumn=currentColumn+horizontal[moveType];6768/*iftheknightcanmakeavalidmove*/69if(validMove(testRow,testColumn,board)){7071/*ifmovehaslowestaccessNumber,movetothatspace*/72if(access[testRow][testColumn]=0&&row<8&&column>=0&&180column<8&&workBoard[row][column]==0);181182}/*endfunctionvalidMove*/Thetourendedwith64moves.Thiswasafulltour!Theboardforthistestis:012345670321334573015421913558311447182916212336049564120433593655462548172845411506140274421537625326452436610516439852217633895223274©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions2156.30(TheSieveofEratosthenes)Aprimeintegerisanyintegerthatcanbedividedevenlyonlybyitselfand1.TheSieveofEratosthenesisamethodoffindingprimenumbers.Itworksasfollows:1)Createanarraywithallelementsinitializedto1(true).Arrayelementswithprimesubscriptswillremain1.Allotherarrayelementswilleventuallybesettozero.2)Startingwitharraysubscript2(subscript1mustbeprime),everytimeanarrayelementisfoundwhosevalueis1,loopthroughtheremainderofthearrayandsettozeroeveryelementwhosesubscriptisamultipleofthesubscriptfortheelementwithvalue1.Forarraysubscript2,allelementsbeyond2inthearraythataremultiplesof2willbesettozero(subscripts4,6,8,10,etc.).Forarraysubscript3,allelementsbeyond3inthearraythataremultiplesof3willbesettozero(subscripts6,9,12,15,etc.).Whenthisprocessiscomplete,thearrayelementsthatarestillsettooneindicatethatthesubscriptisaprimenumber.Thesesub-scriptscanthenbeprinted.Writeaprogramthatusesanarrayof1000elementstodetermineandprinttheprimenumbersbetween1and999.Ignoreelement0ofthearray.ANS:1/*Exercise6.30Solution*/2#include3#defineSIZE100045intmain()6{7intarray[SIZE];/*arraytoindicateprimenumbers*/8intloop;/*loopcounter*/9intloop2;/*loopcounter*/10intcount=0;/*totalprimenumbers*/1112/*setallarrayelementsto1*/13for(loop=0;loop34/*symbolicconstantSIZEmustbedefinedasthearraysize5forbucketSorttowork*/6#defineSIZE1278/*functionprototypes*/9voidbucketSort(inta[]);10voiddistributeElements(inta[],intbuckets[][SIZE],intdigit);11voidcollectElements(inta[],intbuckets[][SIZE]);12intnumberOfDigits(intb[],intarraySize);13voidzeroBucket(intbuckets[][SIZE]);1415intmain()16{1718/*arraytobesorted*/19intarray[SIZE]={19,13,5,27,1,26,31,16,2,9,11,21};©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions21720inti;/*loopcounter*/2122printf("Arrayelementsinoriginalorder:n");2324/*displaytheunsortedarray*/25for(i=0;ilargest){80largest=b[i];81}/*endif*/8283}/*endfor*/8485/*findnumberofdigitsoflargestelement*/86while(largest!=0){87++digits;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com218CArrays:SolutionsChapter688largest/=10;89}/*endwhile*/9091returndigits;/*returnnumberofdigits*/9293}/*endfunctionnumberOfDigits*/9495/*Distributeelementsintobucketsbasedonspecifieddigit*/96voiddistributeElements(inta[],intbuckets[][SIZE],intdigit)97{98intdivisor=10;/*usedtogetspecificdigit*/99inti;/*loopcounter*/100intbucketNumber;/*currentbucketnumber*/101intelementNumber;/*currentelementnumber*/102103/*determinethedivisor*/104for(i=1;i2*/110for(i=0;i3#include4#include56#defineMAXRANGE10007#defineSIZE1089voidselectionSort(intarray[],intsize);/*functionprototype*/1011intmain()12{13intsortThisArray[SIZE]={0};/*arraytobesorted*/14intloop;/*loopcounter*/1516srand(time(NULL));/*seedrandomnumbergenerator*/1718/*fillarraywithrandomnumbersbetween1-1000*/19for(loop=0;loop=1){5354/*findsmallestelementandputitinfirstposition*/55for(loop=0;loop<=size-1;loop++){5657/*swapelements*/58if(array[loop]3#defineSIZE8045/*functionprototype*/6inttestPalindrome(chararray[],intleft,intright);78intmain()9{10charc;/*temporarilyholdskeyboardinput*/11charstring[SIZE];/*originalstring*/12charcopy[SIZE];/*copyofstringwithoutspaces*/13intcount=0;/*lengthofstring*/14intcopyCount;/*lengthofcopy*/15inti;/*counter*/1617printf("Enterasentence:n");1819/*getsentencetotestfromuser*/20while((c=getchar())!="n"&&countright){53return1;54}/*endif*/55elseif(array[left]!=array[right]){56return0;57}/*endelseif*/58else{59returntestPalindrome(array,left+1,right-1);60}/*endelse*/6162}/*endfunctiontestPalindrome*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com222CArrays:SolutionsChapter6Enterasentence:ablewasiereisawelba"ablewasiereisawelba"isapalindromeEnterasentence:hithere"hithere"isnotapalindrome©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions2236.34(LinearSearch)ModifytheprogramofFig.6.18tousearecursivelinearSearchfunctiontoperformthelinearsearchofthearray.Thefunctionshouldreceiveanintegerarrayandthesizeofthearrayasarguments.Ifthesearchkeyisfound,returnthearraysubscript;otherwise,return–1.ANS:1/*Exercise6.34Solution*/2#include3#defineSIZE10045/*functionprototypes*/6intlinearSearch(intarray[],intkey,intlow,inthigh);78intmain()9{10intarray[SIZE];/*arraytobesearched*/11intloop;/*loopcounter*/12intsearchKey;/*elementtosearchfor*/13intelement;/*resultoflinearsearch*/1415/*initializearrayelements*/16for(loop=0;loop3#defineSIZE1545/*functionprototypes*/6intbinarySearch(intb[],intsearchKey,intlow,inthigh);7voidprintHeader(void);8voidprintRow(intb[],intlow,intmid,inthigh);910intmain()11{12inta[SIZE];/*arraytobesearched*/13inti;/*loopcounter*/14intkey;/*searchkey*/15intresult;/*resultofsearch*/1617/*initializearrayelements*/18for(i=0;ihigh){105printf("");106}/*endif*/107elseif(i==mid){/*markmiddlevalue*/108printf("%3d*",b[i]);109}/*endelseif*/110else{111printf("%3d",b[i]);112}/*endelse*/113114}/*endfor*/115116printf("n");117}/*endfunctionprintRow*/Enteranumberbetween0and28:17Subscripts:01234567891011121314------------------------------------------------------------02468101214*1618202224262816182022*2426281618*2016*17notfound©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter6CArrays:Solutions227Enteranumberbetween0and28:10Subscripts:01234567891011121314------------------------------------------------------------02468101214*161820222426280246*81012810*1210foundinarrayelement5©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com228CArrays:SolutionsChapter66.36(EightQueens)ModifytheEightQueensprogramyoucreatedinExercise6.26tosolvetheproblemrecursively.6.37(Printanarray)WritearecursivefunctionprintArraythattakesanarrayandthesizeofthearrayasarguments,andreturnsnothing.Thefunctionshouldstopprocessingandreturnwhenitreceivesanarrayofsizezero.ANS:1/*Exercise6.37Solution*/2#include3#include4#include56#defineSIZE1078/*functionprototype*/9voidprintArray(intarray[],intlow,inthigh);1011intmain()12{13intarray[SIZE];/*arraytobeprinted*/14intloop;/*loopcounter*/1516srand(time(NULL));1718/*initializearrayelementstorandomnumbers*/19for(loop=0;loop3#defineSIZE3045voidstringReverse(charstrArray[]);/*functionprototype*/67intmain()8{9intloop;/*loopcounter*/1011/*initializestringstrArray*/12charstrArray[SIZE]="Printthisstringbackwards.";1314/*displayoriginalstring*/15for(loop=0;loop3#include4#include5#defineSIZE106#defineMAXRANGE100078/*functionprototype*/9intrecursiveMinimum(intarray[],intlow,inthigh);1011intmain()12{13intarray[SIZE];/*arraytobesearched*/14intloop;/*loopcounter*/15intsmallest;/*smallestelement*/1617srand(time(NULL));1819/*initializeelementsofarraytorandomnumbers*/20for(loop=0;loop3#include4#include56/*functionprototypes*/7voidshuffle(intworkDeck[][13]);8voiddeal(intworkDeck[][13],char*workFace[],char*workSuit[]);910intmain()11{12intcard=1;/*cardcounter*/13introw;/*loopcounter*/14intcolumn;/*loopcounter*/15intdeck[4][13];/*arrayofcards*/1617/*definearraysofcardsuitsandfaces*/18char*suit[4]={"Hearts","Diamonds","Clubs","Spades"};19char*face[13]={"Ace","Deuce","Three","Four","Five","Six",20"Seven","Eight","Nine","Ten","Jack","Queen","King"};2122srand(time(NULL));2324/*initializedeck*/25for(row=0;row<=3;row++){2627for(column=0;column<=12;column++){28deck[row][column]=card++;29}/*endfor*/3031}/*endfor*/3233shuffle(deck);34deal(deck,face,suit);3536return0;/*indicatesuccessfultermination*/3738}/*endmain*/3940/*introduceanotherwaytoshuffle*/41voidshuffle(intworkDeck[][13])42{43inttemp;/*temporaryholder*/44introw;/*loopcounter*/45intcolumn;/*loopcounter*/46intrandRow;/*randomsuit*/47intrandColumn;/*randomface*/4849/*runthroughtheloopandtoucheveryelementonce*/50for(row=0;row<=3;row++){5152for(column=0;column<=12;column++){53©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions23754/*generatearandomcard*/55randRow=rand()%4;56randColumn=rand()%13;5758/*swaprandomcardwithcurrentcard*/59temp=workDeck[row][column];60workDeck[row][column]=workDeck[randRow][randColumn];61workDeck[randRow][randColumn]=temp;62}/*endfor*/6364}/*endfor*/6566}/*endfunctionshuffle*/6768/*dealthecards*/69voiddeal(intworkDeck2[][13],char*workFace[],char*workSuit[])70{71intcard;/*cardcounter*/72introw;/*loopcounter*/73intcolumn;/*loopcounter*/7475/*loopthroughandprintthecards*/76for(card=1;card<=52;card++){7778/*loopthroughrows*/79for(row=0;row<=3;row++){8081/*loopthroughcolumns*/82for(column=0;column<=12;column++){8384/*ifcurrentcardequalscardthendeal*/85if(workDeck2[row][column]==card){86printf("%5sof%-8s",workFace[column],workSuit[row]);87card%2==0?putchar("n"):putchar("t");88break;/*breakloop*/89}/*endif*/9091}/*endfor*/9293}/*endfor*/9495}/*endfor*/9697}/*endfunctiondeal*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com238Pointers:SolutionsChapter7EightofSpadesAceofSpadesFiveofHeartsAceofHeartsEightofDiamondsQueenofSpadesDeuceofHeartsSevenofHeartsSevenofClubsSixofHeartsFourofClubsAceofClubsSixofSpadesTenofDiamondsTenofHeartsKingofHeartsFourofDiamondsFourofHeartsJackofDiamondsThreeofDiamondsDeuceofSpadesQueenofClubsThreeofHeartsSixofClubsNineofHeartsNineofDiamondsKingofSpadesSevenofDiamondsFiveofSpadesSevenofSpadesFourofSpadesTenofSpadesKingofDiamondsNineofSpadesDeuceofClubsJackofHeartsAceofDiamondsTenofClubsEightofHeartsSixofDiamondsNineofClubsFiveofDiamondsThreeofClubsDeuceofDiamondsQueenofHeartsKingofClubsQueenofDiamondsJackofClubsFiveofClubsThreeofSpadesJackofSpadesEightofClubs©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions2397.17(Simulation:TheTortoiseandtheHare)Inthisproblem,youwillrecreateoneofthetrulygreatmomentsinhistory,namelytheclassicraceofthetortoiseandthehare.Youwilluserandomnumbergenerationtodevelopasimulationofthismemorableevent.Ourcontendersbegintheraceat“square1”of70squares.Eachsquarerepresentsapossiblepositionalongtheracecourse.Thefinishlineisatsquare70.Thefirstcontendertoreachorpasssquare70isrewardedwithapailoffreshcarrotsandlettuce.Thecourseweavesitswayupthesideofaslipperymountain,sooccasionallythecontendersloseground.Thereisaclockthatticksoncepersecond.Witheachtickoftheclock,yourprogramshouldadjustthepositionoftheanimalsaccordingtotherulesofFig.7.31.AnimalMovetypePercentageofthetimeActualmoveTortoiseFastplod50%3squarestotherightSlip20%6squarestotheleftSlowplod30%1squaretotherightHareSleep20%NomoveatallBighop20%9squarestotherightBigslip10%12squarestotheleftSmallhop30%1squaretotherightSmallslip20%2squarestotheleftUsevariablestokeeptrackofthepositionsoftheanimals(i.e.,positionnumbersare1–70).Starteachanimalatposition1(i.e.,the“startinggate”).Ifananimalslipsleftbeforesquare1,movetheanimalbacktosquare1.Generatethepercentagesintheprecedingtablebyproducingarandominteger,i,intherange1£i£10.Forthetortoise,performa“fastplod”when1£i£5,a“slip”when6£i£7,ora“slowplod”when8£i£10.Useasimilartechniquetomovethehare.BegintheracebyprintingBANG!!!!!ANDTHEY"REOFF!!!!!Then,foreachtickoftheclock(i.e.,eachrepetitionofaloop),printa70positionlineshowingtheletterTinthepositionofthetortoiseandtheletterHinthepositionofthehare.Occasionally,thecontenderswilllandonthesamesquare.Inthiscase,thetortoisebitesthehareandyourprogramshouldprintOUCH!!!beginningatthatposition.AllprintpositionsotherthantheT,theH,ortheOUCH!!!(incaseofatie)shouldbeblank.Aftereachlineisprinted,testifeitheranimalhasreachedorpassedsquare70.Ifso,thenprintthewinnerandterminatethesim-ulation.Ifthetortoisewins,printTORTOISEWINS!!!YAY!!!Iftheharewins,printHarewins.Yuch.Ifbothanimalswinonthesametickoftheclock,youmaywanttofavortheturtle(the“underdog”),oryoumaywanttoprintIt"satie.Ifneitheranimalwins,performtheloopagaintosimulatethenexttickoftheclock.Whenyouarereadytorunyourprogram,assembleagroupoffanstowatchtherace.You"llbeamazedathowinvolvedyouraudiencegets!ANS:1/*Exercise7.17Solution*/2#include3#include4#include56/*functionprototypes*/7voidmoveTortoise(int*turtlePtr);8voidmoveHare(int*rabbitPtr);9voidprintCurrentPositions(int*snapperPtr,int*bunnyPtr);1011intmain()12{13inttortoise=1;/*tortoisecurrentposition*/14inthare=1;/*harecurrentposition*/15inttimer=0;/*timeelapsedduringrace*/16©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com240Pointers:SolutionsChapter717srand(time(NULL));1819printf("ONYOURMARK,GETSETn");20printf("BANG!!!!n");21printf("ANDTHEY"REOFF!!!!n");2223/*loopthroughtheevents*/24while(tortoise!=70&&hare!=70){25moveTortoise(&tortoise);26moveHare(&hare);27printCurrentPositions(&tortoise,&hare);28++timer;29}/*endwhile*/3031/*determinethewinnerandprintmessage*/32if(tortoise>=hare){33printf("nTORTOISEWINS!!!YAY!!!n");34}/*endif*/35else{36printf("Harewins.Yuch.n");37}/*endelse*/3839printf("TIMEELAPSED=%dseconds",timer);4041return0;/*indicatesuccessfultermination*/4243}/*endmain*/4445/*progressforthetortoise*/46voidmoveTortoise(int*turtlePtr)47{48intx;/*randomnumber*/4950x=rand()%10+1;/*generaterandomnumberfrom1-10*/5152/*determineprogress*/53if(x>=1&&x<=5){/*fastplod*/54*turtlePtr+=3;55}/*endif*/56elseif(x==6||x==7){/*slip*/57*turtlePtr-=6;58}/*endelseif*/59else{/*slowplod*/60++(*turtlePtr);61}/*endelse*/6263/*checkboundaries*/64if(*turtlePtr<1){65*turtlePtr=1;66}/*endif*/67if(*turtlePtr>70){68*turtlePtr=70;69}/*endif*/7071}/*endfunctionmoveTortoise*/7273/*progressforthehare*/74voidmoveHare(int*rabbitPtr)75{76inty;/*randomnumber*/77©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions24178y=rand()%10+1;/*generaterandomnumberfrom1-10*/7980/*determineprogress*/81if(y==3||y==4){/*bighop*/82*rabbitPtr+=9;83}/*endif*/84elseif(y==5){/*bigslip*/85*rabbitPtr-=12;86}/*endelseif*/87elseif(y>=6&&y<=8){/*smallhop*/88++(*rabbitPtr);89}/*endelseif*/90elseif(y==10){/*smallslip*/91*rabbitPtr-=2;92}/*endelseif*/9394/*checkboundaries*/95if(*rabbitPtr<1){96*rabbitPtr=1;97}/*endif*/9899if(*rabbitPtr>70){100*rabbitPtr=70;101}/*endif*/102103}/*endfunctionmoveHare*/104105/*displaynewposition*/106voidprintCurrentPositions(int*snapperPtr,int*bunnyPtr)107{108intcount;/*counter*/109110/*loopthroughrace*/111for(count=1;count<=70;count++)112113/*printcurrentleader*/114if(count==*snapperPtr&&count==*bunnyPtr){115printf("OUCH!!!");116}/*endif*/117elseif(count==*bunnyPtr){118printf("H");119}/*endelseif*/120elseif(count==*snapperPtr){121printf("T");122}/*endelseif*/123else{124printf("");125}/*endelse*/126127printf("n");128}/*endfunctionprintCurrentPositions*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com242Pointers:SolutionsChapter7ONYOURMARK,GETSETBANG!!!!ANDTHEY"REOFF!!!!OUCH!!!HTHTTHTHTHTHTHTHTHTHTHTHTHTHTHTHHTHTHTHTHTHTHTHTHTHTHTHTTHOUCH!!!HTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHT...HTTHTHTHTHTHTHTHTHTHHarewins.Yuch.TIMEELAPSED=88seconds©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions243SPECIALSECTION:BUILDINGYOUROWNCOMPUTERInthenextseveralproblems,wetakeatemporarydiversionawayfromtheworldofhigh-levellanguageprogramming.We“peelopen”acomputerandlookatitsinternalstructure.Weintroducemachinelanguageprogrammingandwriteseveralmachinelan-guageprograms.Tomakethisanespeciallyvaluableexperience,wethenbuildacomputer(throughthetechniqueofsoftware-basedsimulation)onwhichyoucanexecuteyourmachinelanguageprograms!7.18(MachineLanguageProgramming)LetuscreateacomputerwewillcalltheSimpletron.Asitsnameimplies,itisasimplemachine,butaswewillsoonsee,apowerfuloneaswell.TheSimpletronrunsprogramswrittenintheonlylanguageitdirectlyunderstands—thatis,SimpletronMachineLanguage,orSMLforshort.TheSimpletroncontainsanaccumulator—a“specialregister”inwhichinformationisputbeforetheSimpletronusesthatinformationincalculationsorexaminesitinvariousways.AllinformationintheSimpletronishandledintermsofwords.Awordisasignedfour-digitdecimalnumbersuchas+3364,-1293,+0007,-0001,etc.TheSimpletronisequippedwitha100-wordmemory,andthesewordsarereferencedbytheirlocationnumbers00,01,…,99.BeforerunninganSMLprogram,wemustloadorplacetheprogramintomemory.Thefirstinstruction(orstatement)ofeverySMLprogramisalwaysplacedinlocation00.EachinstructionwritteninSMLoccupiesonewordoftheSimpletron"smemory(andhenceinstructionsaresignedfour-digitdecimalnumbers).WeassumethatthesignofanSMLinstructionisalwaysplus,butthesignofadatawordmaybeeitherplusorminus.EachlocationintheSimpletron’smemorymaycontaineitheraninstruction,adatavalueusedbyaprogramoranunused(andhenceundefined)areaofmemory.ThefirsttwodigitsofeachSMLinstructionaretheoperationcode,whichspecifiestheoperationtobeperformed.SMLoperationcodesaresummarizedinFig.Fig.7.32.OperationcodeMeaningInput/outputoperations:#defineREAD10Readawordfromtheterminalintoaspecificlocationinmemory.#defineWRITE11Writeawordfromaspecificlocationinmemorytotheterminal.Load/storeoperations:#defineLOAD20Loadawordfromaspecificlocationinmemoryintotheaccumulator.#defineSTORE21Storeawordfromtheaccumulatorintoaspecificlocationinmemory.Arithmeticoperations:#defineADD30Addawordfromaspecificlocationinmemorytothewordintheaccumulator(leaveresultinaccumulator).#defineSUBTRACT31Subtractawordfromaspecificlocationinmemoryfromthewordintheaccumulator(leaveresultinaccumulator).#defineDIVIDE32Divideawordfromaspecificlocationinmemoryintothewordintheaccumulator(leaveresultinaccumulator).#defineMULTIPLY33Multiplyawordfromaspecificlocationinmemorybythewordintheaccumulator(leaveresultinaccumulator).Transferofcontroloperations:#defineBRANCH40Branchtoaspecificlocationinmemory.#defineBRANCHNEG41Branchtoaspecificlocationinmemoryiftheaccumulatorisnegative.#defineBRANCHZERO42Branchtoaspecificlocationinmemoryiftheaccumulatoriszero.#defineHALT43Halt—i.e.,theprogramhascompleteditstask.Fig.7.32SimpletronMachineLanguage(SML)operationcodes.ThelasttwodigitsofanSMLinstructionaretheoperand,whichistheaddressofthememorylocationcontainingthewordtowhichtheoperationapplies.NowletusconsiderseveralsimpleSMLprograms.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com244Pointers:SolutionsChapter7Example1LocationNumberInstruction00+1007(ReadA)01+1008(ReadB)02+2007(LoadA)03+3008(AddB)04+2109(StoreC)05+1109(WriteC)06+4300(Halt)07+0000(VariableA)08+0000(VariableB)09+0000(ResultC)TheprecedingSMLprogramreadstwonumbersfromthekeyboard,andcomputesandprintstheirsum.Theinstruction+1007readsthefirstnumberfromthekeyboardandplacesitintolocation07(whichhasbeeninitializedtozero).Then+1008readsthenextnumberintolocation08.Theloadinstruction,+2007,putsthefirstnumberintotheaccumulator,andtheaddinstruction,+3008,addsthesecondnumbertothenumberintheaccumulator.AllSMLarithmeticinstructionsleavetheirresultsintheaccumulator.Thestoreinstruction,+2109,placestheresultbackintomemorylocation09fromwhichthewriteinstruction,+1109,takesthenumberandprintsit(asasignedfour-digitdecimalnumber).Thehaltinstruction,+4300,terminatesexecution.Example2LocationNumberInstruction00+1009(ReadA)01+1010(ReadB)02+2009(LoadA)03+3110(SubtractB)04+4107(Branchnegativeto07)05+1109(WriteA)06+4300(Halt)07+1110(WriteB)08+4300(Halt)09+0000(VariableA)10+0000(VariableB)©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions245TheprecedingSMLprogramreadstwonumbersfromthekeyboard,anddeterminesandprintsthelargervalue.Notetheuseoftheinstruction+4107asaconditionaltransferofcontrol,muchthesameasC’sifstatement.NowwriteSMLprogramstoaccomplisheachofthefollowingtasks.a)Useasentinel-controlledlooptoread10positiveintegersandcomputeandprinttheirsum.ANS:00+1009(ReadValue)01+2009(LoadValue)02+4106(Branchnegativeto06)03+3008(AddSum)04+2108(StoreSum)05+4000(Branch00)06+1108(WriteSum)07+4300(Halt)08+0000(VariableSum)09+0000(VariableValue)b)Useacounter-controlledlooptoreadsevennumbers,somepositiveandsomenegative,andcomputeandprinttheiraverage.ANS:00+2018(LoadCounter)01+3121(SubtractTermination)02+4211(Branchzeroto11)03+2018(LoadCounter)04+3019(AddIncrement)05+2118(StoreCounter)06+1017(ReadValue)07+2016(LoadSum)08+3017(AddValue)09+2116(StoreSum)10+4000(Branch00)11+2016(LoadSum)12+3218(DivideCounter)13+2120(StoreResult)14+1120(WriteResult)15+4300(Halt)16+0000(VariableSum)17+0000(VariableValue)18+0000(VariableCounter)19+0001(VariableIncrement)20+0000(VariableResult)21+0007(VariableTermination)c)Readaseriesofnumbersanddetermineandprintthelargestnumber.Thefirstnumberreadindicateshowmanynum-bersshouldbeprocessed.ANS:00+1017(ReadEndvalue)01+2018(LoadCounter)02+3117(SubtractEndvalue)03+4215(Branchzeroto15)04+2018(LoadCounter)05+3021(AddIncrement)06+2118(StoreCounter)07+1019(ReadValue)08+2020(LoadLargest)09+3119(SubtractValue)10+4112(Branchnegativeto12)11+4001(Branch01)12+2019(LoadValue)13+2120(StoreLargest)14+4001(Branch01)15+1120(WriteLargest)16+4300(Halt)17+0000(VariableEndvalue)18+0000(VariableCounter)19+0000(VariableValue)20+0000(VariableLargest)21+0001(VariableIncrement)©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com246Pointers:SolutionsChapter77.19(AComputerSimulator)Itmayatfirstseemoutrageous,butinthisproblemyouaregoingtobuildyourowncomputer.No,youwillnotbesolderingcomponentstogether.Rather,youwillusethepowerfultechniqueofsoftware-basedsimulationtocreateasoftwaremodeloftheSimpletron.Youwillnotbedisappointed.YourSimpletronsimulatorwillturnthecomputeryouareusingintoaSimpletron,andyouwillactuallybeabletorun,testanddebugtheSMLprogramsyouwroteinExercise7.18.WhenyourunyourSimpletronsimulator,itshouldbeginbyprinting:***WelcometoSimpletron!******Pleaseenteryourprogramoneinstruction******(ordataword)atatime.Iwilltypethe******locationnumberandaquestionmark(?).******Youthentypethewordforthatlocation.******Typethesentinel-99999tostopentering******yourprogram.***SimulatethememoryoftheSimpletronwithasingle-subscriptedarraymemorythathas100elements.Nowassumethatthesimulatorisrunning,andletusexaminethedialogasweentertheprogramofExample2ofExercise7.18:00?+100901?+101002?+200903?+311004?+410705?+110906?+430007?+111008?+430009?+000010?+000011?-99999***Programloadingcompleted******Programexecutionbegins***TheSMLprogramhasnowbeenplaced(orloaded)intothearraymemory.NowtheSimpletronexecutesyourSMLprogram.Executionbeginswiththeinstructioninlocation00and,likeC,continuessequentially,unlessdirectedtosomeotherpartoftheprogrambyatransferofcontrol.Usethevariableaccumulatortorepresenttheaccumulatorregister.UsethevariableinstructionCountertokeeptrackofthelocationinmemorythatcontainstheinstructionbeingperformed.UsethevariableoperationCodetoindicatetheopera-tioncurrentlybeingperformed—i.e.,thelefttwodigitsoftheinstructionword.Usethevariableoperandtoindicatethememorylocationonwhichthecurrentinstructionoperates.Thus,operandistherightmosttwodigitsoftheinstructioncurrentlybeingper-formed.Donotexecuteinstructionsdirectlyfrommemory.Rather,transferthenextinstructiontobeperformedfrommemorytoavariablecalledinstructionRegister.Then“pickoff”thelefttwodigitsandplacetheminthevariableoperationCode,and“pickoff”therighttwodigitsandplacetheminoperand.WhenSimpletronbeginsexecution,thespecialregistersareinitializedasfollows:accumulator+0000instructionCounter00instructionRegister+0000operationCode00operand00Nowletus“walkthrough”theexecutionofthefirstSMLinstruction,+1009inmemorylocation00.Thisiscalledaninstruc-tionexecutioncycle.TheinstructionCountertellsusthelocationofthenextinstructiontobeperformed.WefetchthecontentsofthatlocationfrommemorybyusingtheCstatementinstructionRegister=memory[instructionCounter];TheoperationcodeandtheoperandareextractedfromtheinstructionregisterbythestatementsoperationCode=instructionRegister/100;operand=instructionRegister%100;NowtheSimpletronmustdeterminethattheoperationcodeisactuallyaread(versusawrite,aload,etc.).Aswitchdiffer-entiatesamongthetwelveoperationsofSML.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions247Intheswitchstatement,thebehaviorofvariousSMLinstructionsissimulatedasfollows(weleavetheotherstothereader):read:scanf("%d",&memory[operand]);load:accumulator=memory[operand];add:accumulator+=memory[operand];Variousbranchinstructions:We"lldiscusstheseshortly.halt:Thisinstructionprintsthemessage***Simpletronexecutionterminated***thenprintsthenameandcontentsofeachregisteraswellasthecompletecontentsofmemory.Suchaprintoutisoftencalledacomputerdump.Tohelpyouprogramyourdumpfunction,asampledumpformatisshowninFig.Fig.7.33.NotethatadumpafterexecutingaSimpletronprogramwouldshowtheactualvaluesofinstructionsanddatavaluesatthemomentexecutionterminated.REGISTERS:accumulator+0000instructionCounter00instructionRegister+0000operationCode00operand00MEMORY:01234567890+0000+0000+0000+0000+0000+0000+0000+0000+0000+000010+0000+0000+0000+0000+0000+0000+0000+0000+0000+000020+0000+0000+0000+0000+0000+0000+0000+0000+0000+000030+0000+0000+0000+0000+0000+0000+0000+0000+0000+000040+0000+0000+0000+0000+0000+0000+0000+0000+0000+000050+0000+0000+0000+0000+0000+0000+0000+0000+0000+000060+0000+0000+0000+0000+0000+0000+0000+0000+0000+000070+0000+0000+0000+0000+0000+0000+0000+0000+0000+000080+0000+0000+0000+0000+0000+0000+0000+0000+0000+000090+0000+0000+0000+0000+0000+0000+0000+0000+0000+0000Fig.7.33SampledumpofSimpletron’smemory.Letusproceedwiththeexecutionofourprogram’sfirstinstruction,namelythe+1009inlocation00.Aswehaveindicated,theswitchstatementsimulatesthisbyperformingtheCstatementscanf("%d",&memory[operand]);Aquestionmark(?)shouldbedisplayedonthescreenbeforethescanfisexecutedtoprompttheuserforinput.TheSim-pletronwaitsfortheusertotypeavalueandthenpresstheReturnkey.Thevalueisthenreadintolocation09.Atthispoint,simulationofthefirstinstructioniscompleted.AllthatremainsistopreparetheSimpletrontoexecutethenextinstruction.Sincetheinstructionjustperformedwasnotatransferofcontrol,weneedmerelyincrementtheinstructioncounterreg-isterasfollows:++instructionCounter;Thiscompletesthesimulatedexecutionofthefirstinstruction.Theentireprocess(i.e.,theinstructionexecutioncycle)beginsanewwiththefetchofthenextinstructiontobeexecuted.Nowletusconsiderhowthebranchinginstructions—thetransfersofcontrol—aresimulated.Allweneedtodoisadjustthevalueintheinstructioncounterappropriately.Therefore,theunconditionalbranchinstruction(40)issimulatedwithintheswitchasinstructionCounter=operand;Theconditional“branchifaccumulatoriszero”instructionissimulatedas©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com248Pointers:SolutionsChapter7if(accumulator==0)instructionCounter=operand;Atthispoint,youshouldimplementyourSimpletronsimulatorandruntheSMLprogramsyouwroteinExercise7.18.YoumayembellishSMLwithadditionalfeaturesandprovidefortheseinyoursimulator.Yoursimulatorshouldcheckforvarioustypesoferrors.Duringtheprogramloadingphase,forexample,eachnumbertheusertypesintotheSimpletron’smemorymustbeintherange-9999to+9999.Yoursimulatorshoulduseawhilelooptotestthateachnumberenteredisinthisrange,and,ifnot,keeppromptingtheusertoreenterthenumberuntiltheuserentersacorrectnum-ber.Duringtheexecutionphase,yoursimulatorshouldcheckforvariousseriouserrors,suchasattemptstodividebyzero,attemptstoexecuteinvalidoperationcodesandaccumulatoroverflows(i.e.,arithmeticoperationsresultinginvalueslargerthan+9999orsmallerthan-9999).Suchseriouserrorsarecalledfatalerrors.Whenafatalerrorisdetected,yoursimulatorshouldprintanerrormessagesuchas:***Attempttodividebyzero******Simpletronexecutionabnormallyterminated***andshouldprintafullcomputerdumpintheformatwehavediscussedpreviously.Thiswillhelptheuserlocatetheerrorintheprogram.ANS:1/*Exercise7.19Solution*/2#include34/*definecommands*/5#defineSIZE1006#defineSENTINEL-999997#defineTRUE18#defineFALSE09#defineREAD1010#defineWRITE1111#defineLOAD2012#defineSTORE2113#defineADD3014#defineSUBTRACT3115#defineDIVIDE3216#defineMULTIPLY3317#defineBRANCH4018#defineBRANCHNEG4119#defineBRANCHZERO4220#defineHALT432122/*functionprototypes*/23voidload(int*loadMemory);24voidexecute(int*memory,int*acPtr,int*icPtr,int*irPtr,25int*opCodePtr,int*opPtr);26voiddump(int*memory,intaccumulator,intinstructionCounter,27intinstructionRegister,intoperationCode,28intoperand);29intvalidWord(intword);3031intmain()32{33intmemory[SIZE];/*definememoryarray*/34intac=0;/*accumulator*/35intic=0;/*instructioncounter*/36intopCode=0;/*operationcode*/37intop=0;/*operand*/38intir=0;/*instructionregister*/39inti;/*counter*/40©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions24941/*clearmemory*/42for(i=0;i=-9999&&word<=9999;293294}/*endfunctionvalidWord*/295***WelcometoSimpletron******Pleaseenteryourprogramoneinstruction******(ordataword)atatime.Iwilltypethe******locationnumberandaquestionmark(?).******Youthentypethewordforthatlocation.******Typethesentinel-99999tostopentering******yourprogram.***00?100701?100802?200703?300804?210905?110906?430007?000008?000009?000010?-99999************STARTSIMPLETRONEXECUTION************Enteraninteger:23Enteraninteger:17Contentsof09:40*************ENDSIMPLETRONEXECUTION*************REGISTERS:accumulator+0040instructioncounter06instructionregister+4300operationcode43operand00MEMORY:01234567890+1007+1008+2007+3008+2109+1109+4300+0023+0017+004010+0000+0000+0000+0000+0000+0000+0000+0000+0000+000020+0000+0000+0000+0000+0000+0000+0000+0000+0000+000030+0000+0000+0000+0000+0000+0000+0000+0000+0000+000040+0000+0000+0000+0000+0000+0000+0000+0000+0000+000050+0000+0000+0000+0000+0000+0000+0000+0000+0000+000060+0000+0000+0000+0000+0000+0000+0000+0000+0000+000070+0000+0000+0000+0000+0000+0000+0000+0000+0000+000080+0000+0000+0000+0000+0000+0000+0000+0000+0000+000090+0000+0000+0000+0000+0000+0000+0000+0000+0000+0000©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com254Pointers:SolutionsChapter77.20ModifythecardshufflinganddealingprogramofFig.7.24sotheshufflinganddealingoperationsareperformedbythesamefunction(shuffleAndDeal).ThefunctionshouldcontainonenestedloopingstructurethatissimilartofunctionshuffleinFig.7.24.ANS:1/*Exercise7.20Solution*/2#include3#include4#include56/*functionprototype*/7voidshuffleAndDeal(intworkdeck[][13],char*workface[],8char*worksuit[]);910intmain()11{1213/*definecardsuitarrayandcardfacearray*/14char*suit[4]={"Hearts","Diamonds","Clubs","Spades"};15char*face[13]={"Ace","Deuce","Three","Four","Five","Six","Seven",16"Eight","Nine","Ten","Jack","Queen","King"};17intdeck[4][13]={0};/*arrayofcards*/1819srand(time(NULL));2021shuffleAndDeal(deck,face,suit);2223return0;/*indicatesuccessfultermination*/2425}/*endmain*/2627/*integrateshufflinganddealingoperation*/28voidshuffleAndDeal(intworkdeck[][13],char*workface[],29char*worksuit[])30{31intcard;/*cardloopcounter*/32introw;/*currentsuit*/33intcolumn;/*currentface*/3435/*loopthroughthedeckofcards,shuffleandprint*/36for(card=1;card<=52;card++){3738/*chooserandomcarduntilnotequaltozero*/39do{40row=rand()%4;41column=rand()%13;42}while(workdeck[row][column]!=0);/*enddo...while*/4344workdeck[row][column]=card;4546/*dealcard*/47printf("%5sof%-8s",workface[column],worksuit[row]);4849card%2==0?printf("n"):printf("t");50}/*endfor*/5152}/*endfunctionshuffleAndDeal*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions255SevenofSpadesKingofDiamondsSixofSpadesKingofHeartsThreeofClubsThreeofDiamondsJackofDiamondsJackofSpadesQueenofClubsEightofHeartsFourofHeartsDeuceofClubsSixofClubsEightofSpadesThreeofHeartsFiveofHeartsSevenofClubsAceofHeartsTenofHeartsFiveofDiamondsQueenofHeartsEightofClubsFiveofClubsDeuceofDiamondsDeuceofSpadesJackofHeartsAceofClubsNineofDiamondsFiveofSpadesNineofClubsDeuceofHeartsKingofSpadesNineofHeartsQueenofSpadesKingofClubsFourofSpadesSevenofDiamondsAceofDiamondsSixofHeartsTenofDiamondsNineofSpadesQueenofDiamondsThreeofSpadesJackofClubsFourofDiamondsAceofSpadesTenofSpadesTenofClubsFourofClubsEightofDiamondsSixofDiamondsSevenofHearts©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com256Pointers:SolutionsChapter77.21Whatdoesthisprogramdo?1/*ex07_21.c*/2/*Whatdoesthisprogramdo?*/3#include45voidmystery1(char*s1,constchar*s2);/*prototype*/67intmain()8{9charstring1[80];/*createchararray*/10charstring2[80];/*createchararray*/1112printf("Entertwostrings:");13scanf("%s%s",string1,string2);1415mystery1(string1,string2);1617printf("%s",string1);1819return0;/*indicatessuccessfultermination*/2021}/*endmain*/2223/*Whatdoesthisfunctiondo?*/24voidmystery1(char*s1,constchar*s2)25{26while(*s1!=""){27s1++;28}/*endwhile*/2930for(;*s1=*s2;s1++,s2++){31;/*emptystatement*/32}/*endfor*/3334}/*endfunctionmystery1*/ANS:Concatenatesstrings.Entertwostrings:string1string2string1string2©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions2577.22Whatdoesthisprogramdo?1/*ex07_22.c*/2/*whatdoesthisprogramdo?*/3#include45intmystery2(constchar*s);/*prototype*/67intmain()8{9charstring[80];/*createchararray*/1011printf("Enterastring:");12scanf("%s",string);1314printf("%dn",mystery2(string));1516return0;/*indicatessuccessfultermination*/1718}/*endmain*/1920/*Whatdoesthisfunctiondo?*/21intmystery2(constchar*s)22{23intx;/*counter*/2425/*loopthroughstring*/26for(x=0;*s!="";s++){27x++;28}/*endfor*/2930returnx;3132}/*endfunctionmystery2*/ANS:Determinesthelengthofastring.Enterastring:string17©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com258Pointers:SolutionsChapter77.23Findtheerrorineachofthefollowingprogramsegments.Iftheerrorcanbecorrected,explainhow.a)int*number;printf("%dn",*number);ANS:numberhasnotbeenassignedtopointtoalocationinmemory.b)float*realPtr;long*integerPtr;integerPtr=realPtr;ANS:Apointercannotbeassignedtoadifferenttype,otherthanvoid*.c)int*x,y;x=y;ANS:Therearetwopossiblesolutions.1)Theindirectionoperator(*)isnotdistributiveandwouldberequiredfory,whichwouldresultinavalidpointerassignment.2)yasitisdefinedisavalidintegervariable,andwouldrequiretheaddressoperator(&)inthepointerassignmentstatement.d)chars[]="thisisacharacterarray";intcount;for(;*s!="";s++)printf("%c",*s);ANS:sshouldbedefinedaschar*,aconstantpointercannotbemoved.e)short*numPtr,result;void*genericPtr=numPtr;result=*genericPtr+7;ANS:Avoid*pointercannotbedereferenced.f)floatx=19.34;floatxPtr=&x;printf("%fn",xPtr);ANS:xPtrisnotdefinedasapointersoitshouldbedereferencedaswell.g)char*s;printf("%sn",s);ANS:shasnotbeenassignedavalue,itdoesnotpointtoanything.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions2597.24(Quicksort)IntheexamplesandexercisesofChapter6,wediscussedthesortingtechniquesbubblesort,bucketsortandselectionsort.WenowpresenttherecursivesortingtechniquecalledQuicksort.Thebasicalgorithmforasingle-subscriptedarrayofvaluesisasfollows:a)PartitioningStep:Takethefirstelementoftheunsortedarrayanddetermineitsfinallocationinthesortedarray(i.e.,allvaluestotheleftoftheelementinthearrayarelessthantheelement,andallvaluestotherightoftheelementinthearrayaregreaterthantheelement).Wenowhaveoneelementinitsproperlocationandtwounsortedsubarrays.b)RecursiveStep:PerformStep1oneachunsortedsubarray.EachtimeStep1isperformedonasubarray,anotherelementisplacedinitsfinallocationofthesortedarray,andtwounsortedsubarraysarecreated.Whenasubarrayconsistsofoneelement,itmustbesorted;therefore,thatelementisinitsfinallocation.Thebasicalgorithmseemssimpleenough,buthowdowedeterminethefinalpositionofthefirstelementofeachsubarray.Asanexample,considerthefollowingsetofvalues(theelementinboldisthepartitioningelement—itwillbeplacedinitsfinallocationinthesortedarray):3726489810126845a)Startingfromtherightmostelementofthearray,compareeachelementwith37untilanelementlessthan37isfound.Thenswap37andthatelement.Thefirstelementlessthan37is12,so37and12areswapped.Thenewarrayis1226489810376845Element12isinitalictoindicatethatitwasjustswappedwith37.b)Startingfromtheleftofthearray,butbeginningwiththeelementafter12,compareeachelementwith37untilanele-mentgreaterthan37isfound.Thenswap37andthatelement.Thefirstelementgreaterthan37is89,so37and89areswapped.Thenewarrayis1226437810896845c)Startingfromtheright,butbeginningwiththeelementbefore89,compareeachelementwith37untilanelementlessthan37isfound.Thenswap37andthatelement.Thefirstelementlessthan37is10,so37and10areswapped.Thenewarrayis1226410837896845d)Startingfromtheleft,butbeginningwiththeelementafter10,compareeachelementwith37untilanelementgreaterthan37isfound.Thenswap37andthatelement.Therearenomoreelementsgreaterthan37,sowhenwecompare37withitself,weknowthat37hasbeenplacedinitsfinallocationofthesortedarray.Oncethepartitionhasbeenappliedtothearray,therearetwounsortedsubarrays.Thesubarraywithvalueslessthan37contains12,2,6,4,10and8.Thesubarraywithvaluesgreaterthan37contains89,68and45.Thesortcontinuesbypartitioningbothsubarraysinthesamemannerastheoriginalarray.Writerecursivefunctionquicksorttosortasingle-subscriptedintegerarray.Thefunctionshouldreceiveasargumentsanintegerarray,astartingsubscriptandanendingsubscript.Functionpartitionshouldbecalledbyquicksorttoperformthepartitioningstep.ANS:1/*Exercise7.24Solution*/2#include3#include4#include56#defineMAX1078/*functionprototypes*/9voidquicksort(int*array,intfirst,intlast);10intpartition(int*array,intleft,intright);11voidswap(int*ptr1,int*ptr2);1213intmain()14{15intloop;/*loopcounter*/16intarrayToBeSorted[MAX]={0};/*arraytosort*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com260Pointers:SolutionsChapter71718srand(time(NULL));1920/*randomlygeneratecontent*/21for(loop=0;loop=last){61return;62}/*endif*/6364currentLocation=partition(array,first,last);/*placeanelement*/65quicksort(array,first,currentLocation-1);/*sortleftside*/66quicksort(array,currentLocation+1,last);/*sortrightside*/6768}/*endfunctionquicksort*/6970/*partitionthearrayintomultiplesections*/71intpartition(intarray[],intleft,intright)72{73intposition=left;/*finallocationoffirstelement*/7475/*infiniteloop*/76while(1){77©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions26178/*loopthroughtheportionofthearray*/79while(array[position]<=array[right]&&80position!=right){81--right;82}/*endwhile*/8384/*ifcorrectpositionisfound*/85if(position==right){86returnposition;87}/*endif*/8889/*swappositions*/90if(array[position]>array[right]){91swap(&array[position],&array[right]);92position=right;93}/*endif*/9495/*loopthroughtheportionofthearray*/96while(array[left]<=array[position]&&97left!=position){98++left;99}/*endwhile*/100101/*ifcorrectpositionisfound*/102if(position==left){103returnposition;104}/*endif*/105106/*swappositions*/107if(array[left]>array[position]){108swap(&array[position],&array[left]);109position=left;110}/*endif*/111112}/*endwhile*/113114}/*endfunctionpartition*/115116/*swaplocations*/117voidswap(int*ptr1,int*ptr2)118{119inttemp;/*temporaryholder*/120121temp=*ptr1;122*ptr1=*ptr2;123*ptr2=temp;124}/*endfunctionswap*/Initialarrayvaluesare:27698055065481176457146912161Thesortedarrayvaluesare:12161276469550571654764811980©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com262Pointers:SolutionsChapter77.25(MazeTraversal)Thefollowinggridisadouble-subscriptedarrayrepresentationofamaze.#############...#......#..#.#.####.####.#....#.##....###.#..####.#.#.#.##..#.#.#.#.###.#.#.#.#.##........#.#######.###.##......#...#############The#symbolsrepresentthewallsofthemaze,andtheperiods(.)representsquaresinthepossiblepathsthroughthemaze.Thereisasimplealgorithmforwalkingthroughamazethatguaranteesfindingtheexit(assumingthereisanexit).Ifthereisnotanexit,youwillarriveatthestartinglocationagain.Placeyourrighthandonthewalltoyourrightandbeginwalkingforward.Neverremoveyourhandfromthewall.Ifthemazeturnstotheright,youfollowthewalltotheright.Aslongasyoudonotremoveyourhandfromthewall,eventuallyyouwillarriveattheexitofthemaze.Theremaybeashorterpaththantheoneyouhavetaken,butyouareguaranteedtogetoutofthemaze.WriterecursivefunctionmazeTraversetowalkthroughthemaze.Thefunctionshouldreceiveasargumentsa12-by-12characterarrayrepresentingthemazeandthestartinglocationofthemaze.AsmazeTraverseattemptstolocatetheexitfromthemaze,itshouldplacethecharacterXineachsquareinthepath.Thefunctionshoulddisplaythemazeaftereachmovesotheusercanwatchasthemazeissolved.ANS:1/*Exercise7.25Solution*/2/*Thissolutionassumesthatthereisonlyone*/3/*entranceandoneexitforagivenmaze,and*/4/*thesearetheonlytwozeroesontheborders.*/5#include6#include78#defineDOWN0/*movedown*/9#defineRIGHT1/*moveright*/10#defineUP2/*moveup*/11#defineLEFT3/*moveleft*/1213#defineX_START2/*startingXandYcoordinateformaze*/14#defineY_START01516/*functionprototypes*/17voidmazeTraversal(charmaze[12][12],intxCoord,intyCoord,18intdirection);19voidprintMaze(constcharmaze[][12]);20intvalidMove(constcharmaze[][12],intr,intc);21intcoordsAreEdge(intx,inty);2223intmain()24{2526/*mazegrid*/27charmaze[12][12]=28{{"1","1","1","1","1","1","1","1","1","1","1","1"},29{"1","0","0","0","1","0","0","0","0","0","0","1"},30{"0","0","1","0","1","0","1","1","1","1","0","1"},31{"1","1","1","0","1","0","0","0","0","1","0","1"},©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions26332{"1","0","0","0","0","1","1","1","0","1","0","0"},33{"1","1","1","1","0","1","0","1","0","1","0","1"},34{"1","0","0","1","0","1","0","1","0","1","0","1"},35{"1","1","0","1","0","1","0","1","0","1","0","1"},36{"1","0","0","0","0","0","0","0","0","1","0","1"},37{"1","1","1","1","1","1","0","1","1","1","0","1"},38{"1","0","0","0","0","0","0","1","0","0","0","1"},39{"1","1","1","1","1","1","1","1","1","1","1","1"}};4041mazeTraversal(maze,X_START,Y_START,RIGHT);4243return0;/*indicatesuccessfultermination*/4445}/*endmain*/4647/*Assumethatthereisexactly1entranceand48exactly1exittothemaze.*/49voidmazeTraversal(charmaze[12][12],intxCoord,intyCoord,50intdirection)51{52staticintflag=0;/*startingpositionflag*/5354maze[xCoord][yCoord]="X";/*markcurrentpoint*/55printMaze(maze);5657/*ifmazecompleted*/58if(coordsAreEdge(xCoord,yCoord)&&xCoord!=X_START&&59yCoord!=Y_START){60printf("nMazesuccessfullyexited!nn");61return;62}/*endif*/63elseif(xCoord==X_START&&yCoord==Y_START&&flag==1){64printf("nArrivedbackatthestartinglocation.nn");65return;66}/*endelseif*/67else{/*makenextmove*/68intmove;/*nextmove*/69intcount;/*counter*/7071flag=1;7273/*loop4timesandfindfirstvalidmove*/74for(move=direction,count=0;count<4;++count,75++move,move%=4){7677/*choosevalidmove*/78switch(move){7980caseDOWN:/*movedown*/8182/*ifmoveisvalid,callmazeTraversal*/83if(validMove(maze,xCoord+1,yCoord)){84mazeTraversal(maze,xCoord+1,yCoord,LEFT);85return;86}/*endif*/8788break;/*exitswitch*/8990caseRIGHT:/*moveright*/91©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com264Pointers:SolutionsChapter792/*ifmoveisvalid,callmazeTraversal*/93if(validMove(maze,xCoord,yCoord+1)){94mazeTraversal(maze,xCoord,yCoord+1,DOWN);95return;96}/*endif*/9798break;/*exitswitch*/99100caseUP:/*moveup*/101102/*ifmoveisvalid,callmazeTraversal*/103if(validMove(maze,xCoord-1,yCoord)){104mazeTraversal(maze,xCoord-1,yCoord,RIGHT);105return;106}/*endif*/107108break;/*exitswitch*/109110caseLEFT:/*moveleft*/111112/*ifmoveisvalid,callmazeTraversal*/113if(validMove(maze,xCoord,yCoord-1)){/*moveleft*/114mazeTraversal(maze,xCoord,yCoord-1,UP);115return;116}/*endif*/117118break;/*exitswitch*/119}/*endswitch*/120121}/*endfor*/122123}/*endelse*/124125}/*endfunctionmazeTraversal*/126127/*validatemove*/128intvalidMove(constcharmaze[][12],intr,intc)129{130return(r>=0&&r<=11&&c>=0&&c<=11&&131maze[r][c]!="1");132133}/*endfunctionvalidMove*/134135/*functiontocheckcoordinates*/136intcoordsAreEdge(intx,inty)137{138139/*ifcoordinateisnotvalid*/140if((x==0||x==11)&&(y>=0&&y<=11)){141return1;142}/*endif*/143elseif((y==0||y==11)&&(x>=0&&x<=11)){144return1;145}/*endelseif*/146else{/*coordinateisvalid*/147return0;148}/*endelse*/149150}/*endfunctioncoordsAreEdge*/151©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions265152/*printthecurrentstateofthemaze*/153voidprintMaze(constcharmaze[][12])154{155intx;/*rowcounter*/156inty;/*columncounter*/157158/*iteratethroughthemaze*/159for(x=0;x<12;x++){160161for(y=0;y<12;y++){162printf("%c",maze[x][y]);163}/*endfor*/164165printf("n");166}/*endfor*/167168printf("nHitreturntoseenextmove");169getchar();170}/*endfunctionprintMaze*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com266Pointers:SolutionsChapter7Hitreturntoseenextmove1111111111111XXX1XXXXXX1XX1X1X111101111X1XXXX1011XXXX111X1001111X101X1011XX1X101X10111X1X101X1011XXXXXXXX101111111X111011XXXXXX10001111111111111Hitreturntoseenextmove1111111111111XXX1XXXXXX1XX1X1X1111X1111X1XXXX1011XXXX111X1001111X101X1011XX1X101X10111X1X101X1011XXXXXXXX101111111X111011XXXXXX10001111111111111...Hitreturntoseenextmove1111111111111XXX1XXXXXX1XX1X1X1111X1111X1XXXX1X11XXXX111X1XX1111X101X1X11XX1X101X1X111X1X101X1X11XXXXXXXX1X1111111X111X11XXXXXX1XXX1111111111111HitreturntoseenextmoveMazesuccessfullyexited!©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions2677.26(GeneratingMazesRandomly)WriteafunctionmazeGeneratorthattakesasanargumentadouble-subscripted12-by-12characterarrayandrandomlyproducesamaze.Thefunctionshouldalsoprovidethestartingandendinglocationsofthemaze.TryyourfunctionmazeTraversefromExercise7.25usingseveralrandomlygeneratedmazes.ANS:1/*Exercise7.26Solution*/2#include3#include4#include56#defineDOWN0/*movedown*/7#defineRIGHT1/*moveright*/8#defineUP2/*moveup*/9#defineLEFT3/*moveleft*/10#definePOSSIBLE_ZEROS100/*maximumpossiblezeroes*/1112/*functionprototypes*/13voidmazeTraversal(charmaze[12][12],constintxCoord,14constintyCoord,introw,intcol,intdirection);15voidmazeGenerator(charmaze[][12],int*xPtr,int*yPtr);16voidprintMaze(constcharmaze[][12]);17intvalidMove(constcharmaze[][12],intr,intc);18intcoordsAreEdge(intx,inty);1920intmain()21{22charmaze[12][12];/*mazegrid*/23intloop;/*rowcounter*/24intloop2;/*columncounter*/25intxStart;/*startingxcoordinate*/26intyStart;/*startingycoordinate*/27intx;/*currentxcoordinate*/28inty;/*currentycoordinate*/2930/*initializemazegridto1"s*/31for(loop=0;loop<12;loop++){3233for(loop2=0;loop2<12;loop2++){34maze[loop][loop2]="1";35}/*endfor*/3637}/*endfor*/3839/*generatethemaze*/40mazeGenerator(maze,&xStart,&yStart);4142x=xStart;/*startingrow*/43y=yStart;/*startingcol*/4445mazeTraversal(maze,xStart,yStart,x,y,RIGHT);4647return0;/*indicatesuccessfultermination*/4849}/*endmain*/5051/*Assumethatthereisexactly1entranceand52exactly1exittothemaze.*/53voidmazeTraversal(charmaze[12][12],constintxCoord,54constintyCoord,introw,intcol,intdirection)55{56staticintflag=0;/*startingpositionflag*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com268Pointers:SolutionsChapter75758maze[row][col]="X";/*insertXatcurrentlocation*/59printMaze(maze);6061/*ifmazecompleted*/62if(coordsAreEdge(row,col)&&row!=xCoord&&col!=yCoord){63printf("nMazesuccessfullyexited!nn");64return;65}/*endif*/66elseif(row==xCoord&&col==yCoord&&flag==1){67printf("nArrivedbackatthestartinglocation.nn");68return;69}/*endelseif*/70else{/*makenextmove*/71intmove;/*nextmove*/72intcount;/*counter*/7374flag=1;7576/*loop4timesandfindfirstvalidmove*/77for(move=direction,count=0;count<4;++count,78++move,move%=4){7980/*choosevalidmove*/81switch(move){8283caseDOWN:/*movedown*/8485/*ifmoveisvalid,callmazeTraversal*/86if(validMove(maze,row+1,col)){87mazeTraversal(maze,xCoord,yCoord,row+1,88col,LEFT);89return;90}/*endif*/9192break;/*exitswitch*/9394caseRIGHT:/*moveright*/9596/*ifmoveisvalid,callmazeTraversal*/97if(validMove(maze,row,col+1)){98mazeTraversal(maze,xCoord,yCoord,row,99col+1,DOWN);100return;101}/*endif*/102103break;/*exitswitch*/104105caseUP:/*moveup*/106107/*ifmoveisvalid,callmazeTraversal*/108if(validMove(maze,row-1,col)){109mazeTraversal(maze,xCoord,yCoord,row-1,110col,RIGHT);111return;112}/*endif*/113114break;/*exitswitch*/115116caseLEFT:/*moveleft*/117©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions269118/*ifmoveisvalid,callmazeTraversal*/119if(validMove(maze,row,col-1)){120mazeTraversal(maze,xCoord,yCoord,row,121col-1,UP);122return;123}/*endif*/124125break;/*exitswitch*/126}/*endswitch*/127128}/*endfor*/129130}/*endelse*/131132}/*endfunctionmazeTraversal*/133134/*validatemove*/135intvalidMove(constcharmaze[][12],intr,intc)136{137return(r>=0&&r<=11&&c>=0&&c<=11&&138maze[r][c]!="1");139140}/*endfunctionvalidMove*/141142/*checkboundariesofcoordinates*/143intcoordsAreEdge(intx,inty)144{145146/*ifcoordinatesnotvalid*/147if((x==0||x==11)&&(y>=0&&y<=11)){148return1;149}/*endif*/150elseif((y==0||y==11)&&(x>=0&&x<=11)){151return1;152}/*endelseif*/153else{/*coordinatesvalid*/154return0;155}/*endelse*/156157}/*endfunctioncoordsAreEdge*/158159/*printthemaze*/160voidprintMaze(constcharmaze[][12])161{162intx;/*rowcounter*/163inty;/*columncounter*/164165/*loopthroughmazegrid*/166for(x=0;x<12;x++){167168for(y=0;y<12;y++){169printf("%c",maze[x][y]);170}/*endfor*/171172printf("n");173}/*endfor*/174175printf("nHitreturntoseenextmove");176getchar();177}/*endfunctionprintMaze*/178©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com270Pointers:SolutionsChapter7179/*randommazegenerator*/180voidmazeGenerator(charmaze[][12],int*xPtr,int*yPtr)181{182inta;/*randomnumber*/183intx;/*randomnumber*/184inty;/*randomnumber*/185intentry;/*randomentry*/186intexit;/*randomexit*/187intloop;/*loopcounter*/188189srand(time(NULL));190191/*generaterandomentryandexitpositions*/192do{193entry=rand()%4;194exit=rand()%4;195}while(entry==exit);/*enddo...while*/196197/*Determineentrypositionwhileavoidingcorners*/198if(entry==0){199*xPtr=1+rand()%10;200*yPtr=0;201maze[*xPtr][0]="0";202}/*endif*/203elseif(entry==1){204*xPtr=0;205*yPtr=1+rand()%10;206maze[0][*yPtr]="0";207}/*endelseif*/208elseif(entry==2){209*xPtr=1+rand()%10;210*yPtr=11;211maze[*xPtr][11]="0";212}/*endelseif*/213else{214*xPtr=11;215*yPtr=1+rand()%10;216maze[11][*yPtr]="0";217}/*endelse*/218219/*Determineexitlocation*/220if(exit==0){221a=1+rand()%10;222maze[a][0]="0";223}/*endif*/224elseif(exit==1){225a=1+rand()%10;226maze[0][a]="0";227}/*endelseif*/228elseif(exit==2){229a=1+rand()%10;230maze[a][11]="0";231}/*endelseif*/232else{233a=1+rand()%10;234maze[11][a]="0";235}/*endelse*/236237/*randomlyaddzeroestomazegrid*/238for(loop=1;loop3#include4#include56#defineROW10/*height*/7#defineCOL10/*width*/8#defineDOWN0/*movedown*/9#defineRIGHT1/*moveright*/10#defineUP2/*moveup*/11#defineLEFT3/*moveleft*/1213/*functionprototypes*/14voidmazeTraversal(charmaze[ROW][COL],constintxCoord,15constintyCoord,introw,intcol,intdirection);16voidmazeGenerator(charmaze[][COL],int*xPtr,int*yPtr);17voidprintMaze(constcharmaze[][COL]);18intvalidMove(constcharmaze[][COL],intr,intc);19intcoordsAreEdge(intx,inty);2021intmain()22{23charmaze[ROW][COL];/*mazegrid*/24intloop;/*rowcounter*/25intloop2;/*columncounter*/26intxStart;/*startingxcoordinate*/27intyStart;/*startingycoordinate*/28intx;/*currentxcoordinate*/29inty;/*currentycoordinate*/3031/*initializemazegridto1"s*/32for(loop=0;loop=0&&r<=ROW-1&&c>=0&&c<=COL-1&&139maze[r][c]!="1");/*avalidmove*/140141}/*endfunctionvalidMove*/142143/*checkboundariesofcoordinates*/144intcoordsAreEdge(intx,inty)145{146147/*ifcoordinatesnotvalid*/148if((x==0||x==ROW-1)&&(y>=0&&y<=COL-1)){149return1;150}/*endif*/151elseif((y==0||y==COL-1)&&(x>=0&&152x<=ROW-1)){153return1;154}/*endelseif*/155else{/*coordinatesvalid*/156return0;157}/*endelse*/158159}/*endfunctioncoordsAreEdge*/160161/*printthemaze*/162voidprintMaze(constcharmaze[][COL])163{164intx;/*rowcounter*/165inty;/*columncounter*/166167/*loopthroughmazegrid*/168for(x=0;x3#defineSTUDENTS34#defineEXAMS456/*functionprototypes*/7voidminimum(intgrades[][EXAMS],intpupils,inttests);8voidmaximum(intgrades[][EXAMS],intpupils,inttests);9voidaverage(intgrades[][EXAMS],intpupils,inttests);10voidprintArray(intgrades[][EXAMS],intpupils,inttests);11voidprintMenu(void);1213intmain()14{1516/*pointertoafunctionthattakesasparametersa17two-dimensionalarrayandtwointegervalues*/18void(*processGrades[4])(int[][EXAMS],int,int)19={printArray,minimum,maximum,average};2021intchoice=0;/*menuchoice*/2223/*arrayofstudentgrades*/24intstudentGrades[STUDENTS][EXAMS]={{77,68,86,73},25{96,87,89,78},26{70,90,86,81}};2728/*loopwhileuserdoesnotchooseoption4*/29while(choice!=4){3031/*displaymenuandreaduser"schoice*/32do{33printMenu();34scanf("%d",&choice);35}while(choice<0||choice>4);/*enddo...while*/3637/*passchoiceintothearray*/38if(choice!=4){39(*processGrades[choice])(studentGrades,STUDENTS,EXAMS);40}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com278Pointers:SolutionsChapter741else{42printf("ProgramEnded.n");43}/*endelse*/4445}/*endwhile*/4647return0;/*indicatesuccessfultermination*/4849}/*endmain*/5051/*searchfortheminimumvalue*/52voidminimum(intgrades[][EXAMS],intpupils,inttests)53{54inti;/*loopcounter*/55intj;/*loopcounter*/56intlowGrade=100;/*setlowGradetohighestpossiblescore*/5758/*loopthroughrows*/59for(i=0;i<=pupils-1;i++){6061/*loopthroughcolumns*/62for(j=0;j<=tests-1;j++){6364/*ifcurrentgradeislowerthanlowGrade*/65if(grades[i][j]highGrade){91highGrade=grades[i][j];92}/*endif*/9394}/*endfor*/9596}/*endfor*/9798printf("ntThehighestgradeis%dn",highGrade);99}/*endfunctionmaximum*/100©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions279101/*calculateaverage*/102voidaverage(intgrades[][EXAMS],intpupils,inttests)103{104inti;/*loopcounter*/105intj;/*loopcounter*/106inttotal;/*sumofallgrades*/107108printf("n");109110/*loopthroughrows*/111for(i=0;i<=pupils-1;i++){112total=0;113114/*loopthroughcolumns*/115for(j=0;j<=tests-1;j++){116total+=grades[i][j];117}/*endfor*/118119printf("tTheaverageforstudent%dis%.1fn",120i+1,(double)total/tests);121}/*endfor*/122123}/*endfunctionaverage*/124125/*printthecontentsofthearray*/126voidprintArray(intgrades[][EXAMS],intpupils,inttests)127{128inti;/*loopcounter*/129intj;/*loopcounter*/130131printf("nt[0][1][2][3]");132133/*loopthroughrows*/134for(i=0;i<=pupils-1;i++){135printf("ntstudentGrades[%d]",i);136137/*loopthroughcolumns*/138for(j=0;j<=tests-1;j++){139printf("%-7d",grades[i][j]);140}/*endfor*/141142}/*endfor*/143144printf("n");145}/*endfunctionprintArray*/146147/*displaythemenu*/148voidprintMenu(void)149{150printf("ntEnterachoice:n"151"t0Printthearrayofgradesn"152"t1Findtheminimumgraden"153"t2Findthemaximumgraden"154"t3Printtheaverageonall"155"testsforeachstudentn"156"t4Endprogramn"157"t?");158}/*endfunctionprintMenu*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com280Pointers:SolutionsChapter7Enterachoice:0Printthearrayofgrades1Findtheminimumgrade2Findthemaximumgrade3Printtheaverageonalltestsforeachstudent4Endprogram?0[0][1][2][3]studentGrades[0]77688673studentGrades[1]96878978studentGrades[2]70908681Enterachoice:0Printthearrayofgrades1Findtheminimumgrade2Findthemaximumgrade3Printtheaverageonalltestsforeachstudent4Endprogram?1Thelowestgradeis68Enterachoice:0Printthearrayofgrades1Findtheminimumgrade2Findthemaximumgrade3Printtheaverageonalltestsforeachstudent4Endprogram?2Thehighestgradeis96Enterachoice:0Printthearrayofgrades1Findtheminimumgrade2Findthemaximumgrade3Printtheaverageonalltestsforeachstudent4Endprogram?3Theaverageforstudent1is76.0Theaverageforstudent2is87.5Theaverageforstudent3is81.8Enterachoice:0Printthearrayofgrades1Findtheminimumgrade2Findthemaximumgrade3Printtheaverageonalltestsforeachstudent4Endprogram?4ProgramEnded.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter7Pointers:Solutions2817.29(ModificationstotheSimpletronSimulator)InExercise7.19,youwroteasoftwaresimulationofacomputerthatexecutesprogramswritteninSimpletronMachineLanguage(SML).Inthisexercise,weproposeseveralmodificationsandenhancementstotheSimpletronSimulator.InExercises12.26and12.27,weproposebuildingacompilerthatconvertsprogramswritteninahigh-levelprogramminglanguage(avariationofBASIC)toSimpletronMachineLanguage.Someofthefollowingmodificationsandenhancementsmayberequiredtoexecutetheprogramsproducedbythecompiler.a)ExtendtheSimpletronSimulator’smemorytocontain1000memorylocationstoenabletheSimpletrontohandlelargerprograms.b)Allowthesimulatortoperformremaindercalculations.ThisrequiresanadditionalSimpletronMachineLanguagein-struction.c)Allowthesimulatortoperformexponentiationcalculations.ThisrequiresanadditionalSimpletronMachineLanguageinstruction.d)ModifythesimulatortousehexadecimalvaluesratherthanintegervaluestorepresentSimpletronMachineLanguageinstructions.e)Modifythesimulatortoallowoutputofanewline.ThisrequiresanadditionalSimpletronMachineLanguageinstruc-tion.f)Modifythesimulatortoprocessfloating-pointvaluesinadditiontointegervalues.g)Modifythesimulatortohandlestringinput.[Hint:EachSimpletronwordcanbedividedintotwogroups,eachholdingatwo-digitinteger.Eachtwo-digitintegerrepresentstheASCIIdecimalequivalentofacharacter.Addamachinelan-guageinstructionthatwillinputastringandstorethestringbeginningataspecificSimpletronmemorylocation.Thefirsthalfofthewordatthatlocationwillbeacountofthenumberofcharactersinthestring(i.e.,thelengthofthestring).EachsucceedinghalfwordcontainsoneASCIIcharacterexpressedastwodecimaldigits.Themachinelan-guageinstructionconvertseachcharacterintoitsASCIIequivalentandassignsittoahalfword.]h)Modifythesimulatortohandleoutputofstringsstoredintheformatofpart(g).[Hint:Addamachinelanguagein-structionthatprintsastringbeginningataspecifiedSimpletronmemorylocation.Thefirsthalfofthewordatthatlo-cationisthelengthofthestringincharacters.EachsucceedinghalfwordcontainsoneASCIIcharacterexpressedastwodecimaldigits.Themachinelanguageinstructionchecksthelengthandprintsthestringbytranslatingeachtwo-digitnumberintoitsequivalentcharacter.]©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com282Pointers:SolutionsChapter77.30Whatdoesthisprogramdo?1/*ex07_30.c*/2/*Whatdoesthisprogramdo?*/3#include45intmystery3(constchar*s1,constchar*s2);/*prototype*/67intmain()8{9charstring1[80];/*createchararray*/10charstring2[80];/*createchararray*/1112printf("Entertwostrings:");13scanf("%s%s",string1,string2);1415printf("Theresultis%dn",mystery3(string1,string2));1617return0;/*indicatessuccessfultermination*/1819}/*endmain*/2021intmystery3(constchar*s1,constchar*s2)22{23for(;*s1!=""&&*s2!="";s1++,s2++){2425if(*s1!=*s2){26return0;27}/*endif*/2829}/*endfor*/3031return1;3233}/*endfunctionmystery3*/ANS:TheProgramcomparestwostrings,elementbyelement,forequality.Entertwostrings:string1string2Theresultis0Entertwostrings:string2string2Theresultis1©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com8CCharactersandStrings:SolutionsSOLUTIONS8.5Writeaprogramthatinputsacharacterfromthekeyboardandteststhecharacterwitheachofthefunctionsinthecharacterhandlinglibrary.Theprogramshouldprintthevaluereturnedbyeachfunction.ANS:1/*Exercise8.5Solution*/2#include3#include45intmain()6{7intc;/*characterinputbyuser*/89printf("Enteracharacter:");10c=getchar();1112/*testeachfunctionofthecharacterhandlinglibrary*/13printf("isdigit("%c")=%dn",c,isdigit(c));14printf("isalpha("%c")=%dn",c,isalpha(c));15printf("isalnum("%c")=%dn",c,isalnum(c));16printf("isxdigit("%c")=%dn",c,isxdigit(c));17printf("islower("%c")=%dn",c,islower(c));18printf("isupper("%c")=%dn",c,isupper(c));19printf("tolower("%c")=%dn",c,tolower(c));20printf("toupper("%c")=%dn",c,toupper(c));21printf("isspace("%c")=%dn",c,isspace(c));22printf("iscntrl("%c")=%dn",c,iscntrl(c));23printf("ispunct("%c")=%dn",c,ispunct(c));24printf("isprint("%c")=%dn",c,isprint(c));25printf("isgraph("%c")=%dn",c,isgraph(c));2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com284CCharactersandStrings:SolutionsChapter8Enteracharacter:hisdigit("h")=0isalpha("h")=2isalnum("h")=2isxdigit("h")=0islower("h")=2isupper("h")=0tolower("h")=104toupper("h")=72isspace("h")=0iscntrl("h")=0ispunct("h")=0isprint("h")=2isgraph("h")=28.6Writeaprogramthatinputsalineoftextwithfunctiongetsintochararrays[100].Outputthelineinuppercaselettersandinlowercaseletters.ANS:1/*Exercise8.6Solution*/2#include3#include45intmain()6{7chars[100];/*definecharacterarrayofsize100*/8inti;/*loopcounter*/910/*usegetstogettextfromuser*/11printf("Enteralineoftext:n");12gets(s);13printf("nThelineinuppercaseis:n");1415/*converteachcharactertouppercaseandoutput*/16for(i=0;s[i]!="";i++){17printf("%c",toupper(s[i]));18}/*endfor*/1920printf("nnThelineinlowercaseis:n");2122/*converteachcharactertolowercaseandoutput*/23for(i=0;s[i]!="";i++){24printf("%c",tolower(s[i]));25}/*endfor*/2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/Enteralineoftext:AlinewithUPPER-andlowercaseLeTtersThelineinuppercaseis:ALINEWITHUPPER-ANDLOWERCASELETTERSThelineinlowercaseis:alinewithupper-andlowercaseletters©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions2858.7Writeaprogramthatinputsfourstringsthatrepresentintegers,convertsthestringstointegers,sumsthevaluesandprintsthetotalofthefourvalues.ANS:1/*Exercise8.7Solution*/2#include3#include45intmain()6{7charstringValue[6];/*integerstringinputbyuser*/8intsum=0;/*resultoffourintegers*/9inti;/*loopcounter*/1011/*loop4times*/12for(i=1;i<=4;i++){13printf("Enteranintegerstring:");14scanf("%s",stringValue);1516/*atoiconvertsstringValuetointeger*/17sum+=atoi(stringValue);18}/*endfor*/1920printf("nThetotalofthevaluesis%dn",sum);2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/Enteranintegerstring:43Enteranintegerstring:77Enteranintegerstring:120Enteranintegerstring:9999Thetotalofthevaluesis102398.8Writeaprogramthatinputsfourstringsthatrepresentfloating-pointvalues,convertsthestringstodoublevalues,sumsthevaluesandprintsthetotalofthefourvalues.ANS:1/*Exercise8.8Solution*/2#include3#include45intmain()6{7charstringValue[15];/*stringinputbyuser*/8doublesum=0.0;/*sumofallfourvalues*/9inti;/*loopcounter*/1011/*loop4times*/12for(i=1;i<=4;i++){13printf("Enteradoubleingpointstring:");14gets(stringValue);1516/*atofconvertsstringValuetoafloating-pointvalue*/17sum+=atof(stringValue);18}/*endfor*/1920printf("nThetotalofthevaluesis%fn",sum);2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com286CCharactersandStrings:SolutionsChapter8Enteradoubleingpointstring:1.2Enteradoubleingpointstring:2.3Enteradoubleingpointstring:3.4Enteradoubleingpointstring:4.5Thetotalofthevaluesis11.4000008.9Writeaprogramthatusesfunctionstrcmptocomparetwostringsinputbytheuser.Theprogramshouldstatewhetherthefirststringislessthan,equaltoorgreaterthanthesecondstring.ANS:1/*Exercise8.9Solution*/2#include3#include45intmain()6{7charstring1[20];/*firststringinputbyuser*/8charstring2[20];/*secondstringinputbyuser*/9intresult;/*resultofcomparingtwostrings*/1011printf("Entertwostrings:");12scanf("%s%s",string1,string2);/*readtwostrings*/1314result=strcmp(string1,string2);1516/*displayappropriatemessageforresult*/17if(result>0){18printf(""%s"isgreaterthan"%s"n",string1,string2);19}/*endif*/20elseif(result==0){21printf(""%s"isequalto"%s"n",string1,string2);22}/*endelseif*/23else{24printf(""%s"islessthan"%s"n",string1,string2);25}/*endelse*/2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/Entertwostrings:GregDave"Greg"isgreaterthan"Dave"Entertwostrings:BillBill"Bill"isequalto"Bill"Entertwostrings:PeteTim"Pete"islessthan"Tim"©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions2878.10Writeaprogramthatusesfunctionstrncmptocomparetwostringsinputbytheuser.Theprogramshouldinputthenumberofcharacterstobecompared.Theprogramshouldstatewhetherthefirststringislessthan,equaltoorgreaterthanthesecondstring.ANS:1/*Exercise8.10Solution*/2#include3#include45intmain()6{7charstring1[20];/*firststringinputbyuser*/8charstring2[20];/*secondstringinputbyuser*/9intresult;/*resultofusingstrncmp*/10intcompareCount;/*howmanycharacterstobecompared*/1112/*gettwostringsfromuser*/13printf("Entertwostrings:");14scanf("%s%s",string1,string2);1516/*getnumberofcharacterstocompare*/17printf("Howmanycharactersshouldbecompared:");18scanf("%d",&compareCount);1920result=strncmp(string1,string2,compareCount);2122/*displayappropriatemessageforresult*/23if(result>0){24printf(""%s"isgreaterthan"%s"upto%dcharactersn",25string1,string2,compareCount);26}/*endif*/27elseif(result==0){28printf(""%s"isequalto"%s"upto%dcharactersn",29string1,string2,compareCount);30}/*endelseif*/31else{32printf(""%s"islessthan"%s"upto%dcharactersn",33string1,string2,compareCount);34}/*endelse*/3536return0;/*indicatesuccessfultermination*/3738}/*endmain*/Entertwostrings:ABCDEFGABCDEFHHowmanycharactersshouldbecompared:6"ABCDEFG"islessthan"ABCDEFH"upto6charactersEntertwostrings:ABCDEFGABCDEFHHowmanycharactersshouldbecompared:7"ABCDEFG"islessthan"ABCDEFH"upto7charactersEntertwostrings:ABCEFGABCDFGHowmanycharactersshouldbecompared:4"ABCEFG"isgreaterthan"ABCDFG"upto4characters©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com288CCharactersandStrings:SolutionsChapter88.11Writeaprogramthatusesrandomnumbergenerationtocreatesentences.Theprogramshouldusefourarraysofpointerstocharcalledarticle,noun,verbandpreposition.Theprogramshouldcreateasentencebyselectingawordatrandomfromeacharrayinthefollowingorder:article,noun,verb,preposition,articleandnoun.Aseachwordispicked,itshouldbeconcatenatedtothepreviouswordsinanarraylargeenoughtoholdtheentiresentence.Thewordsshouldbeseparatedbyspaces.Whenthefinalsentenceisoutput,itshouldstartwithacapitalletterandendwithaperiod.Theprogramshouldgenerate20suchsentences.Thearraysshouldbefilledasfollows:Thearticlearrayshouldcontainthearticles"the","a","one","some"and"any";thenounarrayshouldcontainthenouns"boy","girl","dog","town"and"car";theverbarrayshouldcontaintheverbs"drove","jumped","ran","walked"and"skipped";theprepositionarrayshouldcontaintheprepositions"to","from","over","under"and"on".Aftertheprecedingprogramiswrittenandworking,modifytheprogramtoproduceashortstoryconsistingofseveralofthesesentences.(Howaboutthepossibilityofarandomtermpaperwriter?)ANS:1/*Exercise8.11Solution*/2#include3#include4#include5#include6#include78intmain()9{10/*initialize4arraysofcharpointers*/11char*article[]={"the","a","one","some","any"};12char*noun[]={"boy","girl","dog","town","car"};13char*verb[]={"drove","jumped","ran","walked","skipped"};14char*preposition[]={"to","from","over","under","on"};15charsentence[100]="";/*completedsentence*/16inti;/*loopcounter*/1718/*create20sentences*/19for(i=1;i<=20;i++){2021/*randomlychoosepiecesofsentence*/22strcat(sentence,article[rand()%5]);23strcat(sentence,"");2425strcat(sentence,noun[rand()%5]);26strcat(sentence,"");2728strcat(sentence,verb[rand()%5]);29strcat(sentence,"");3031strcat(sentence,preposition[rand()%5]);32strcat(sentence,"");3334strcat(sentence,article[rand()%5]);35strcat(sentence,"");3637strcat(sentence,noun[rand()%5]);3839/*capitalizefirstletterandprintsentence*/40putchar(toupper(sentence[0]));41printf("%s.n",&sentence[1]);42sentence[0]="";43}/*endfor*/4445return0;/*indicatesuccessfultermination*/4647}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions289Adogskippedtoanycar.Sometownranontheboy.Adogjumpedfromthedog.Onegirljumpedononetown.Onedogjumpedfromsomeboy.Onegirljumpedunderanydog.Onecardroveonsomegirl.Onetownwalkedonagirl.Sometownranononedog.Onecarwalkedfromanytown.Aboydroveoversomegirl.Thedogskippedunderaboy.Thecardrovetoagirl.Sometownskippedunderanycar.Aboyjumpedfromatown.Anycarjumpedunderonetown.Somedogskippedfromsomeboy.Anytownskippedtoonegirl.Somegirljumpedtoanydog.Thecarranunderonedog.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com290CCharactersandStrings:SolutionsChapter88.12(Limericks)Alimerickisahumorousfive-lineverseinwhichthefirstandsecondlinesrhymewiththefifth,andthethirdlinerhymeswiththefourth.UsingtechniquessimilartothosedevelopedinExercise8.11,writeaprogramthatproducesrandomlimericks.Polishingthisprogramtoproducegoodlimericksisachallengingproblem,buttheresultwillbeworththeeffort!8.13WriteaprogramthatencodesEnglishlanguagephrasesintopigLatin.PigLatinisaformofcodedlanguageoftenusedforamusement.ManyvariationsexistinthemethodsusedtoformpigLatinphrases.Forsimplicity,usethefollowingalgorithm:ToformapigLatinphrasefromanEnglishlanguagephrase,tokenizethephraseintowordswithfunctionstrtok.Totrans-lateeachEnglishwordintoapigLatinword,placethefirstletteroftheEnglishwordattheendoftheEnglishword,andaddtheletters“ay.”Thustheword“jump”becomes“umpjay,”theword“the”becomes“hetay”andtheword“computer”becomes“omputercay.”Blanksbetweenwordsremainasblanks.Assumethefollowing:TheEnglishphraseconsistsofwordsseparatedbyblanks,therearenopunctuationmarks,andallwordshavetwoormoreletters.FunctionprintLatinWordshoulddisplayeachword.[Hint:Eachtimeatokenisfoundinacalltostrtok,passthetokenpointertofunctionprintLatinWord,andprintthepigLatinword.]ANS:1/*Exercise8.13Solution*/2#include3#include45voidprintLatinWord(char*word);/*functionprototype*/67intmain()8{9charsentence[80];/*sentenceinputbyuser*/10char*tokenPtr;/*pointertocurrenttoken*/1112printf("Enterasentence:n");13gets(sentence);14printf("nThesentenceinPigLatinis:n");1516/*callfunctionstrtoktoalterthesentence*/17tokenPtr=strtok(sentence,".,;");1819/*iftokenPtrdoesnotequalNULL*/20while(tokenPtr){2122/*passthetokentoprintLatinWordandgetnexttoken*/23printLatinWord(tokenPtr);24tokenPtr=strtok(NULL,".,;");2526/*iftokenPtrnotNULL,printspace*/27if(tokenPtr){28printf("");29}/*endif*/3031}/*endwhile*/3233printf(".");3435return0;/*indicatessuccessfultermination*/3637}/*endmain*/3839/*printouttheEnglishwordinpigLatinform*/40voidprintLatinWord(char*word)41{42unsignedinti;/*loopcounter*/4344/*loopthroughtheword*/45for(i=1;i3#include4#include56intmain()7{8charp[20];/*completephonenumber*/9charphoneNumber[10]={""};/*longintegerphonenumber*/10char*tokenPtr;/*storetemporarytoken*/11intareaCode;/*storeareacode*/12longphone;/*storephonenumber*/1314printf("Enteraphonenumberintheform(555)"15"555-5555:n");16gets(p);1718/*convertareacodetokentoaninteger*/19areaCode=atoi(strtok(p,"()"));2021/*takenexttokenandcopytophoneNumber*/22tokenPtr=strtok(NULL,"-");23strcpy(phoneNumber,tokenPtr);2425/*takelasttokenandconcatenatetophoneNumber*/26tokenPtr=strtok(NULL,"");27strcat(phoneNumber,tokenPtr);2829/*convertphoneNumbertolonginteger*/30phone=atol(phoneNumber);3132printf("nTheintegerareacodeis%dn",areaCode);33printf("Thelongintegerphonenumberis%ldn",phone);3435return0;/*indicatesuccessfultermination*/3637}/*endmain*/Enteraphonenumberintheform(555)555-5555:(800)555-1212Theintegerareacodeis800Thelongintegerphonenumberis5551212©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com292CCharactersandStrings:SolutionsChapter88.15Writeaprogramthatinputsalineoftext,tokenizesthelinewithfunctionstrtokandoutputsthetokensinreverseorder..ANS:1/*Exercise8.15solution*/2#include3#include45voidreverseTokens(char*sentence);/*functionprototype*/67intmain()8{9chartext[80];/*lineoftextfromuser*/1011printf("Enteralineoftext:n");12gets(text);1314reverseTokens(text);/*calltofunctionreverseTokens*/1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/1920/*functiontoreversetheindividualtokens*/21voidreverseTokens(char*sentence)22{23char*pointers[50];/*arraytostoreentiresentence*/24char*temp;/*pointertoeachtoken*/25intcount=0;/*tokencounter*/26inti;/*loopcounter*/2728/*functionstrtoktakesfirstwordofsentence*/29temp=strtok(sentence,"");3031/*whiletempdoesnotequalNULL*/32while(temp){3334/*addthewordintothearrayandgetnexttoken*/35pointers[count++]=temp;36temp=strtok(NULL,"");37}/*endwhile*/3839printf("Thetokensinreverseorderare:n");4041/*loopthroughthearraybackwards*/42for(i=count-1;i>=0;i--){43printf("%s",pointers[i]);44}/*endfor*/4546}/*endfunctionreverseTokens*/Enteralineoftext:testing123Thetokensinreverseorderare:321testing©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions2938.16Writeaprogramthatinputsalineoftextandasearchstringfromthekeyboard.Usingfunctionstrstr,locatethefirstoccurrenceofthesearchstringinthelineoftext,andassignthelocationtovariablesearchPtroftypechar*.Ifthesearchstringisfound,printtheremainderofthelineoftextbeginningwiththesearchstring.Then,usestrstragaintolocatethenextoc-currenceofthesearchstringinthelineoftext.Ifasecondoccurrenceisfound,printtheremainderofthelineoftextbeginningwiththesecondoccurrence.[Hint:ThesecondcalltostrstrshouldcontainsearchPtr+1asitsfirstargument.]ANS:1/*Exercise8.16Solution*/2#include3#include4intmain()5{6chartext[80];/*lineoftext*/7charsearch[15];/*searchstring*/8char*searchPtr;/*poinertosearchstring*/910/*getlineoftextfromuser*/11printf("Enteralineoftext:n");12gets(text);1314/*getsearchstringfromuser*/15printf("Enterasearchstring:");16scanf("%s",search);1718/*searchforsearchstringintext*/19searchPtr=strstr(text,search);2021/*ifsearchPtrisnotNULL*/22if(searchPtr){23printf("n%sn%s"%s":n%sn",24"Theremainderofthelinebeginningwith",25"thefirstoccurrenceof",search,searchPtr);2627/*searchforasecondoccurrence*/28searchPtr=strstr(searchPtr+1,search);2930/*ifsearchPtrisnotNULL*/31if(searchPtr){32printf("n%sn%s"%s":n%sn",33"Theremainderofthelinebeginningwith",34"thesecondoccurrenceof",search,searchPtr);35}/*endif*/36else{37printf("Thesearchstringappearedonlyonce.n");38}/*endelse*/3940}/*endif*/41else{42printf(""%s"notfound.n",search);43}/*endelse*/4445return0;/*indicatesuccessfultermination*/4647}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com294CCharactersandStrings:SolutionsChapter8Enteralineoftext:Tobeornottobe;thatisthequestion.Enterasearchstring:beTheremainderofthelinebeginningwiththefirstoccurrenceof"be":beornottobe;thatisthequestion.Theremainderofthelinebeginningwiththesecondoccurrenceof"be":be;thatisthequestion.8.17WriteaprogrambasedontheprogramofExercise8.16thatinputsseverallinesoftextandasearchstring,andusesfunctionstrstrtodeterminethetotaloccurrencesofthestringinthelinesoftext.Printtheresult.ANS:1/*Exercise8.17Solution*/2#include3#include4#include56intmain()7{8chartext[3][80];/*arraytoholdtextenteredbyuser*/9charsearch[20];/*searchstring*/10char*searchPtr;/*pointertosearchstring*/11intcount=0;/*totaloccurrencesofsearchstring*/12inti;/*loopcounter*/13intj;/*loopcounter*/1415printf("Enterthreelinesoftext:n");1617/*readin3linesoftext*/18for(i=0;i<=2;i++){19gets(&text[i][0]);20}/*endfor*/2122/*makeallcharacterslowercase*/23for(i=0;i<=2;i++){2425/*loopthrougheachcharacter*/26for(j=0;text[i][j]!="";j++){27text[i][j]=tolower(text[i][j]);28}/*endfor*/2930}/*endfor*/3132printf("nEnterasearchstring:");/*getsearchstring*/33scanf("%s",search);3435/*loopthroughallthreestrings*/36for(i=0;i<=2;i++){3738/*setpointertofirstcharacterofstring*/39searchPtr=&text[i][0];4041/*loopwhilestrstrdoesnotreturnNULL*/42while(searchPtr=strstr(searchPtr,search)){43++count;44searchPtr++;45}/*endwhile*/4647}/*endfor*/48©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions29549printf("nThetotaloccurrencesof"%s"inthetextis%dn",50search,count);5152return0;/*indicatesuccessfultermination*/5354}/*endmain*/Enterthreelinesoftext:Thisprograminputsthreelinesoftextandcountsthenumberofoccurrencesofthesearchstringinthethreelinesoftext.Enterasearchstring:thThetotaloccurrencesof"th"inthetextis68.18Writeaprogramthatinputsseverallinesoftextandasearchcharacter,andusesfunctionstrchrtodeterminethetotaloccurrencesofthecharacterinthelinesoftext.ANS:1/*Exercise8.18Solution*/2#include3#include4#include56intmain()7{8chartext[3][80];/*arraytoholdtextenteredbyuser*/9charsearch;/*searchcharacter*/10char*searchPtr;/*pointertosearchcharacter*/11intcount=0;/*totalsearchcharactersfound*/12inti;/*loopcounter*/13intj;/*loopcounter*/1415printf("Enterthreelinesoftext:n");1617/*read3linesoftext*/18for(i=0;i<=2;i++){19gets(&text[i][0]);20}/*endfor*/2122/*convertallletterstolowercase*/23for(i=0;i<=2;i++){2425/*loopthrougheachcharacter*/26for(j=0;text[i][j]!="";j++){27text[i][j]=tolower(text[i][j]);28}/*endfor*/2930}/*endfor*/3132/*getsearchcharacter*/33printf("nEnterasearchcharacter:");34scanf("%c",&search);3536/*loopthrough3linesoftext*/37for(i=0;i<=2;i++){3839/*setpointertofirstcharacterinline*/40searchPtr=&text[i][0];4142/*loopwhilestrchrdoesnotreturnNULL*/43while(searchPtr=strchr(searchPtr,search)){44++count;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com296CCharactersandStrings:SolutionsChapter845searchPtr++;46}/*endwhile*/4748}/*endfor*/4950printf("nThetotaloccurrencesof"%c"inthetextis%dn",51search,count);5253return0;/*indicatesuccessfultermination*/5455}/*endmain*/Enterthreelinesoftext:ThisprograminputsthreelinesoftextandcountsthenumberofoccurrencesofthespecifiedsearchcharacterinthetextEnterasearchcharacter:eThetotaloccurrencesof"e"inthetextis15©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions2978.19WriteaprogrambasedontheprogramofExercise8.18thatinputsseverallinesoftextandusesfunctionstrchrtodeter-minethetotaloccurrencesofeachletterofthealphabetinthelinesoftext.Uppercaseandlowercaselettersshouldbecountedtogether.Storethetotalsforeachletterinanarrayandprintthevaluesintabularformatafterthetotalshavebeendetermined.ANS:1/*Exercise8.19Solution*/2#include3#include4#include56intmain()7{8chartext[3][80];/*3linesoftext*/9char*searchPtr;/*pointertosearchcharacter*/10charcharacters[26]={0};/*totalsforeachletter*/11intcount=0;/*totalforcurrentletter*/12inti;/*loopcounter*/13intj;/*loopcounter*/1415printf("Enterthreelinesoftext:n");1617/*readthreelinesoftext*/18for(i=0;i<=2;i++){19gets(&text[i][0]);20}/*endfor*/2122/*convertletterstolowercase*/23for(i=0;i<=2;i++){2425/*loopthrougheachcharacterofline*/26for(j=0;text[i][j]!="";j++){27text[i][j]=tolower(text[i][j]);28}/*endfor*/2930}/*endfor*/3132/*loopthroughalphabet*/33for(i=0;i<=25;i++){3435/*loopthrough3linesoftext*/36for(j=0,count=0;j<=2;j++){37searchPtr=&text[j][0];3839/*whilestrchrdoesnotreturnNULL*/40while(searchPtr=strchr(searchPtr,"a"+i)){41++count;42searchPtr++;43}/*endwhile*/4445}/*endfor*/4647characters[i]=count;48}/*endfor*/4950printf("nThetotaloccurrencesofeachcharacter:n");5152/*displaytotalsforeachcharacter*/53for(i=0;i<=25;i++){54printf("%c:%3dn","a"+i,characters[i]);55}/*endfor*/5657return0;/*indicatesuccessfultermination*/5859}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com298CCharactersandStrings:SolutionsChapter8Enterthreelinesoftext:Thisprograminputsthreelinesoftextanddeterminesthenumberofoccurrencesofeachcharacterinthethreelines.Thetotaloccurrencesofeachcharacter:a:5b:1c:6d:2e:17f:3g:1h:7i:6j:0k:0l:2m:3n:8o:5p:2q:0r:10s:6t:10u:3v:0w:0x:1y:0z:0©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions2998.20Writeaprogramthatinputsseverallinesoftextandusesstrtoktocountthetotalnumberofwords.Assumethatthewordsareseparatedeitherbyspacesornewlinecharacters.ANS:1/*Exercise8.20Solution*/2#include3#include45intmain()6{7chartext[4][80];/*textenteredbyuser*/8char*tokenPtr;/*pointertocurrenttoken*/9inti;/*loopcounter*/10intcounter=0;/*tokencounter*/1112printf("Enter4linesoftext:n");1314/*read4linesoftext*/15for(i=0;i<=3;i++){16gets(&text[i][0]);17}/*endfor*/1819/*loopthrough4linesoftext*/20for(i=0;i<=3;i++){2122/*getfirsttoken*/23tokenPtr=strtok(&text[i][0],"n");2425/*whiletokenPtrdoesnotequalNULL*/26while(tokenPtr){27++counter;28tokenPtr=strtok(NULL,"n");/*getnexttoken*/29}/*endwhile*/3031}/*endfor*/3233printf("nThetotalnumberofwordsis%dn",counter);3435return0;/*indicatesuccessfultermination*/3637}/*endmain*/Enter4linesoftext:ThislineoftexthassevenwordsThislinehasfivewordsTherearetwowordsonthenextlineIamThetotalnumberofwordsis22©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com300CCharactersandStrings:SolutionsChapter88.21UsethestringcomparisonfunctionsdiscussedinSection8.6andthetechniquesforsortingarraysdevelopedinChapter6towriteaprogramthatalphabetizesalistofstrings.Usethenamesof10or15townsinyourareaasdataforyourprogram.ANS:1/*Exercise8.21solution*/2#include3#include45voidbubbleSort(chara[][50]);/*functionprototype*/67intmain()8{9chararray[10][50];/*10linesoftextfromuser*/10inti;/*counter*/1112/*readin10linesoftext*/13for(i=0;i<=9;i++){14printf("Enterastring:");15scanf("%s",&array[i][0]);16}/*endfor*/1718bubbleSort(array);/*sortthearrayofstrings*/19printf("nThestringsinsortedorderare:n");2021/*displaytextinsortedorder*/22for(i=0;i<=9;i++){23printf("%sn",&array[i][0]);24}/*endfor*/2526return0;/*indicatesuccessfultermination*/2728}/*endmain*/2930/*sortthearray*/31voidbubbleSort(chara[][50])32{33inti;/*loopcounter*/34intj;/*loopcounter*/35chartemp[50];/*temporaryarray*/3637/*make9passes*/38for(i=0;i<=8;i++){3940for(j=0;j<=8;j++){4142/*swapstringsifnecessary*/43if(strcmp(&a[j][0],&a[j+1][0])>0){44strcpy(temp,&a[j][0]);45strcpy(&a[j][0],&a[j+1][0]);46strcpy(&a[j+1][0],temp);47}/*endif*/4849}/*endfor*/5051}/*endfor*/5253}/*endfunctionbubbleSort*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions301Enterastring:WestboroughEnterastring:WellesleyEnterastring:NatickEnterastring:WalthamEnterastring:FraminghamEnterastring:MarlboroughEnterastring:BostonEnterastring:AshlandEnterastring:HopkingtonEnterastring:ShrewsburyThestringsinsortedorderare:AshlandBostonFraminghamHopkingtonMarlboroughNatickShrewsburyWalthamWellesleyWestborough8.22ThechartinAppendixDshowsthenumericcoderepresentationsforthecharactersintheASCIIcharacterset.Studythischartandthenstatewhethereachofthefollowingistrueorfalse.a)Theletter“A”comesbeforetheletter“B.”ANS:True.b)Thedigit“9”comesbeforethedigit“0.”ANS:False.c)Thecommonlyusedsymbolsforaddition,subtraction,multiplicationanddivisionallcomebeforeanyofthedigits.ANS:True.d)Thedigitscomebeforetheletters.ANS:True.e)Ifasortprogramsortsstringsintoascendingsequence,thentheprogramwillplacethesymbolforarightparenthesisbeforethesymbolforaleftparenthesis.ANS:False.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com302CCharactersandStrings:SolutionsChapter88.23Writeaprogramthatreadsaseriesofstringsandprintsonlythosestringsbeginningwiththeletter“b.”ANS:1/*Exercise8.23solution*/2#include34intmain()5{6inti;/*loopcounter*/7chararray[5][20];/*5stringsfromuser*/89/*read5stringsfromuser*/10for(i=0;i<=4;i++){11printf("Enterastring:");12scanf("%s",&array[i][0]);13}/*endfor*/1415printf("nThestringsstartingwith"b"are:n");1617/*loopthroughstrings*/18for(i=0;i<=4;i++){1920/*printiffirstcharacteris"b"*/21if(array[i][0]=="b"){22printf("%sn",&array[i][0]);23}/*endif*/2425}/*endfor*/2627return0;/*indicatesuccessfultermination*/2829}/*endmain*/Enterastring:theEnterastring:bigEnterastring:badEnterastring:boyEnterastring:singsThestringsstartingwith"b"are:bigbadboy©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions3038.24Writeaprogramthatreadsaseriesofstringsandprintsonlythosestringsthatendwiththeletters“ed.”ANS:1/*Exercise8.24solution*/2#include3#include45intmain()6{7inti;/*loopcounter*/8intlength;/*lengthofcurrentstring*/9chararray[5][20];/*5stringsfromuser*/1011/*readin5stringsfromuser*/12for(i=0;i<=4;i++){13printf("Enterastring:");14scanf("%s",&array[i][0]);15}/*endfor*/1617printf("nThestringsendingwith"ED"are:n");1819/*loopthrough5strings*/20for(i=0;i<=4;i++){2122/*findlengthofcurrentstring*/23length=strlen(&array[i][0]);2425/*printstringifitendswith"ED"*/26if(strcmp(&array[i][length-2],"ED")==0){27printf("%sn",&array[i][0]);28}/*endif*/2930}/*endfor*/3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/Enterastring:WALKEDEnterastring:SKIPPEDEnterastring:JUMPEDEnterastring:FLEWEnterastring:DROVEThestringsendingwith"ED"are:WALKEDSKIPPEDJUMPED©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com304CCharactersandStrings:SolutionsChapter88.25WriteaprogramthatinputsanASCIIcodeandprintsthecorrespondingcharacter.Modifythisprogramsothatitgeneratesallpossiblethree-digitcodesintherange000to255andattemptstoprintthecorrespondingcharacters.Whathappenswhenthisprogramisrun?ANS:1/*Exercise8.25solution*/2#include34intmain()5{6intc;/*ASCIIcharacter*/78printf("EnteranASCIIcharactercode(EOFtoend):");910/*whileuserdoesnotenterEOF*/11while(scanf("%d",&c)!=EOF){1213/*checkifcharactercodeisvalid*/14if(c>=0&&c<=255){15printf("Thecorrespondingcharacteris"%c"n",c);16}/*endif*/17else{18printf("Invalidcharactercoden");19}/*endelse*/2021printf("nEnteranASCIIcharactercode(EOFtoend):");22}/*endwhile*/2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/EnteranASCIIcharactercode(EOFtoend):90Thecorrespondingcharacteris"Z"EnteranASCIIcharactercode(EOFtoend):116Thecorrespondingcharacteris"t"EnteranASCIIcharactercode(EOFtoend):130Thecorrespondingcharacteris"é"EnteranASCIIcharactercode(EOFtoend):45Thecorrespondingcharacteris"-"EnteranASCIIcharactercode(EOFtoend):40Thecorrespondingcharacteris"("EnteranASCIIcharactercode(EOFtoend):^Z©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions3058.26UsingtheASCIIcharacterchartinAppendixDasaguide,writeyourownversionsofthecharacterhandlingfunctionsinFig.8.1.ANS:1/*Exercise8.26Solution*/2#include34/*functionprototypes*/5intisDigit(intc);6intisAlpha(intc);7intisAlNum(intc);8intisLower(intc);9intisUpper(intc);10inttoLower(intc);11intisSpace(intc);12intisPunct(intc);13intisPrint(intc);14intisGraph(intc);15inttoLower(intc);16inttoUpper(intc);1718intmain()19{20intv;/*functionresult*/21chararray[2]={""};/*characterfromuser*/2223/*readacharacterfromtheuser*/24printf("Enteracharacter:");25scanf("%c",&array[0]);2627/*testisDigitfunction*/28v=isDigit((int)array[0]);29printf("AccordingtoisDigit");30v==0?printf("%cisnotadigitn",array[0]):31printf("%cisadigitn",array[0]);3233/*testisAlphafunction*/34v=isAlpha((int)array[0]);35printf("AccordingtoisAlpha");36v==0?printf("%cisnotalettern",array[0]):37printf("%cisalettern",array[0]);3839/*testisAlNumfunction*/40v=isAlNum((int)array[0]);41printf("AccordingtoisAlNum");42v==0?printf("%cisnotaletterordigitn",array[0]):43printf("%cisaletterordigitn",array[0]);4445/*testisLowerfunction*/46v=isLower((int)array[0]);47printf("AccordingtoisLower");48v==0?printf("%cisnotalowercaselettern",array[0]):49printf("%cisalowercaselettern",array[0]);5051/*testisUpperfunction*/52v=isUpper((int)array[0]);53printf("AccordingtoisUpper");54v==0?printf("%cisnotanuppercaselettern",array[0]):55printf("%cisanuppercaselettern",array[0]);5657/*testisSpacefunction*/58v=isSpace((int)array[0]);59printf("AccordingtoisSpace");60v==0?printf("%cisnotawhite-spacecharactern",array[0]):61printf("characterisawhite-spacecharactern");62©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com306CCharactersandStrings:SolutionsChapter863/*testisPunctfunction*/64v=isPunct((int)array[0]);65printf("AccordingtoisPunct");66v==0?printf("%cisnotapunctuationcharactern",array[0]):67printf("%cisapunctuationcharactern",array[0]);6869/*testisPrintfunction*/70v=isPrint((int)array[0]);71printf("AccordingtoisPrint");72v==0?printf("%cisnotaprintingcharactern",array[0]):73printf("%cisaprintingcharactern",array[0]);7475/*testisGraphfunction*/76v=isGraph((int)array[0]);77printf("AccordingtoisGraph");78v==0?printf("%cisnotaprintingcharactern",array[0]):79printf("%cisaprintingcharacterotherthanspacen",array[0]);8081/*testtoLowerfunction*/82v=toLower((int)array[0]);83printf("AccordingtotoLower");84v==0?printf("%cisunchangedn",array[0]):85printf("%chasbeenconvertedtolowercasen",v);8687/*testtoUpperfunction*/88v=toUpper((int)array[0]);89printf("AccordingtotoUpper");90v==0?printf("%cisunchangedn",array[0]):91printf("%chasbeenconvertedtouppercasen",v);9293return0;/*indicatesuccessfultermination*/9495}/*endmain*/9697/*determineswhetherargumentisadigit*/98intisDigit(intc)99{100return(c>=48&&c<=57)?1:0;101102}/*endfunctionisDigit*/103104/*determineswhetherargumentisaletter*/105intisAlpha(intc)106{107return((c>=65&&c<=90)||(c>=97&&c<=122))?1:0;108109}/*endfunctionisAlpha*/110111/*determineswhetherargumentisaletterordigit*/112intisAlNum(intc)113{114return(isDigit(c)==1||isAlpha(c)==1)?1:0;115116}/*endfunctionisAlNum*/117118/*determineswhetherargumentisalowercaseletter*/119intisLower(intc)120{121return(c>=97&&c<=122)?1:0;122123}/*endfunctionisLower*/124125/*determineswhetherargumentisanuppercaseletter*/126intisUpper(intc)127{128return(c>=65&&c<=90)?1:0;129130}/*endfunctionisUpper*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions307131132/*determineswhetherargumentisawhitespacecharacter*/133intisSpace(intc)134{135return((c==32)||(c>=9&&c<=13))?1:0;136137}/*endfunctionisSpace*/138139/*determineswhetherargumentisaprintingcharacter140otherthanaspace,adigitoraletter*/141intisPunct(intc)142{143return(isAlNum(c)==0&&isSpace(c)==0)?1:0;144145}/*endfunctionisPunct*/146147/*determineswhetherargumentisaprintingcharacter148includingthespacecharacter*/149intisPrint(intc)150{151return(c>=32&&c<=126)?1:0;152153}/*endfunctionisPrint*/154155/*determineswhetherargumentisaprintingcharacter156otherthanthespacecharacter*/157intisGraph(intc)158{159return(c>=33&&c<=126)?1:0;160161}/*endfunctionisGraph*/162163/*convertsanduppercaselettertolowercase*/164inttoLower(intc)165{166return(isUpper(c)==1)?c+32:c;167168}/*endfunctiontoLower*/169170/*convertsalowercaselettertouppercase*/171inttoUpper(intc)172{173return(isLower(c)==1)?c-32:c;174175}/*endfunctiontoUpper*/176Enteracharacter:mAccordingtoisDigitmisnotadigitAccordingtoisAlphamisaletterAccordingtoisAlNummisaletterordigitAccordingtoisLowermisalowercaseletterAccordingtoisUppermisnotanuppercaseletterAccordingtoisSpacemisnotawhite-spacecharacterAccordingtoisPunctmisnotapunctuationcharacterAccordingtoisPrintmisaprintingcharacterAccordingtoisGraphmisaprintingcharacterotherthanspaceAccordingtotoLowermhasbeenconvertedtolowercaseAccordingtotoUpperMhasbeenconvertedtouppercase©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com308CCharactersandStrings:SolutionsChapter8Enteracharacter:*AccordingtoisDigit*isnotadigitAccordingtoisAlpha*isnotaletterAccordingtoisAlNum*isnotaletterordigitAccordingtoisLower*isnotalowercaseletterAccordingtoisUpper*isnotanuppercaseletterAccordingtoisSpace*isnotawhite-spacecharacterAccordingtoisPunct*isapunctuationcharacterAccordingtoisPrint*isaprintingcharacterAccordingtoisGraph*isaprintingcharacterotherthanspaceAccordingtotoLower*hasbeenconvertedtolowercaseAccordingtotoUpper*hasbeenconvertedtouppercase8.27WriteyourownversionsofthefunctionsinFig.8.5forconvertingstringstonumbers.8.28WritetwoversionsofeachofthestringcopyandstringconcatenationfunctionsinFig.8.17.Thefirstversionshouldusearraysubscripting,andthesecondversionshouldusepointersandpointerarithmetic.8.29Writeyourownversionsofthefunctionsgetchar,gets,putcharandputsdescribedinFig.8.12.8.30WritetwoversionsofeachstringcomparisonfunctioninFig.8.20.Thefirstversionshouldusearraysubscripting,andthesecondversionshouldusepointersandpointerarithmetic.8.31WriteyourownversionsofthefunctionsinFig.8.22forsearchingstrings.8.32WriteyourownversionsofthefunctionsinFig.8.30formanipulatingblocksofmemory.8.33WritetwoversionsoffunctionstrleninFig.8.36.Thefirstversionshouldusearraysubscripting,andthesecondversionshouldusepointersandpointerarithmetic.SPECIALSECTION:ADVANCEDSTRINGMANIPULATIONEXERCISESTheprecedingexercisesarekeyedtothetextanddesignedtotestthereader"sunderstandingoffundamentalstringmanipulationconcepts.Thissectionincludesacollectionofintermediateandadvancedproblems.Thereadershouldfindtheseproblemschal-lengingyetenjoyable.Theproblemsvaryconsiderablyindifficulty.Somerequireanhourortwoofprogramwritingandimplementation.Othersareusefulforlabassignmentsthatmightrequiretwoorthreeweeksofstudyandimplementation.Somearechallengingtermprojects.8.34(TextAnalysis)Theavailabilityofcomputerswithstringmanipulationcapabilitieshasresultedinsomeratherinterestingapproachestoanalyzingthewritingsofgreatauthors.MuchattentionhasbeenfocusedonwhetherWilliamShakespeareeverlived.SomescholarsbelievethatthereissubstantialevidenceindicatingthatChristopherMarloweactuallypennedthemasterpiecesat-tributedtoShakespeare.Researchershaveusedcomputerstofindsimilaritiesinthewritingsofthesetwoauthors.Thisexerciseexaminesthreemethodsforanalyzingtextswithacomputer.a)Writeaprogramthatreadsseverallinesoftextandprintsatableindicatingthenumberofoccurrencesofeachletterofthealphabetinthetext.Forexample,thephraseTobe,ornottobe:thatisthequestion:containsone“a,”two“b’s,”no“c’s,”etc.ANS:1/*Exercise8.34PartASolution*/2#include3#include45intmain()6{7charletters[26]={0};/*lettersofthealphabet*/8chartext[3][80];/*threelinesoftext*/9inti;/*loopcounter*/10intj;/*loopcounter*/1112printf("Enterthreelinesoftext:n");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions3091314/*read3linesoftext*/15for(i=0;i<=2;i++){16gets(&text[i][0]);17}/*endfor*/1819/*loopthrough3strings*/20for(i=0;i<=2;i++){2122/*loopthrougheachcharacter*/23for(j=0;text[i][j]!="";j++){2425/*ifletter,updatecorrespondingarrayelement*/26if(isalpha(text[i][j])){27++letters[tolower(text[i][j])-"a"];28}/*endif*/2930}/*endfor*/3132}/*endfor*/3334printf("nTotallettercounts:n");3536/*printlettertotals*/37for(i=0;i<=25;i++){38printf("%c:%3dn","a"+i,letters[i]);39}/*endfor*/4041return0;/*indicatesuccessfultermination*/4243}/*endmain*/Enterthreelinesoftext:Thisprogramcountstheoccurrencesofeachletterofthealphabetintheinputtext.Then,itprintsasummaryoftheoccurrences.Totallettercounts:a:6b:1c:8d:0e:14f:3g:1h:8i:5j:0k:0l:2m:3n:7o:7p:4q:0r:9s:6t:15u:5v:0w:0x:1y:1z:0©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com310CCharactersandStrings:SolutionsChapter8b)Writeaprogramthatreadsseverallinesoftextandprintsatableindicatingthenumberofone-letterwords,two-letterwords,three-letterwords,etc.,appearinginthetext.Forexample,thephraseWhether"tisnoblerinthemindtosuffercontainsWordlengthOccurrences10223142(including"tis)506271ANS:1/*Exercise8.34PartBsolution*/2#include3#include45intmain()6{7chartext[3][80];/*3stringsfromuser*/8char*temp;/*tokenpointer*/9intlengths[20]={0};/*arrayoflengthcounts*/10inti;/*loopcounter*/1112printf("Enterthreelinesoftext:n");1314/*read3linesoftext*/15for(i=0;i<=2;i++){16gets(&text[i][0]);17}/*endfor*/1819/*loopthrougheachstring*/20for(i=0;i<=2;i++){2122/*getfirsttoken*/23temp=strtok(&text[i][0],".n");2425/*whiletempdoesnotequalNULL*/26while(temp){2728/*incrementcorrespondingarrayelement*/29++lengths[strlen(temp)];30temp=strtok(NULL,".n");31}/*endwhile*/3233}/*endfor*/3435putchar("n");3637/*displayresultsinarray*/38for(i=1;i<=19;i++){3940/*iflengthisnotzero*/41if(lengths[i]){42printf("%dword%soflength%dn",43lengths[i],lengths[i]==1?"":"s",i);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions31144}/*endif*/4546}/*endfor*/4748return0;/*indicatesuccessfultermination*/4950}/*endmain*/Enterthreelinesoftext:Thisprogramdeterminesthelengthofeachwordintheinputtext.Theinputtextherehaswordsofseveraldifferentlengths.3wordsoflength24wordsoflength36wordsoflength43wordsoflength51wordoflength63wordsoflength71wordoflength91wordoflength10c)Writeaprogramthatreadsseverallinesoftextandprintsatableindicatingthenumberofoccurrencesofeachdifferentwordinthetext.Thefirstversionofyourprogramshouldincludethewordsinthetableinthesameorderinwhichtheyappearinthetext.Amoreinteresting(anduseful)printoutshouldthenbeattemptedinwhichthewordsaresortedal-phabetically.Forexample,thelinesTobe,ornottobe:thatisthequestion:Whether"tisnoblerinthemindtosuffercontainthewords“to”threetimes,theword“be”twotimes,theword“or”once,etc.ANS:1/*Exercise8.34PartCsolution*/2#include3#include45intmain()6{7chartext[3][80];/*3stringfromuser*/8char*temp;/*tokenpointer*/9charwords[100][20]={""};/*arrayofwords*/10inti;/*loopcounter*/11intj;/*loopcounter*/12intcount[100]={0};/*arrayofwordcounts*/1314printf("Enterthreelinesoftext:n");1516/*readthreelinesoftext*/17for(i=0;i<=2;i++){18gets(&text[i][0]);19}/*endfor*/2021/*loopthrough3strings*/22for(i=0;i<=2;i++){2324/*getfirsttoken*/25temp=strtok(&text[i][0],".n");2627/*whiletempdoesnotequalNULL*/28while(temp){29©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com312CCharactersandStrings:SolutionsChapter830/*loopthroughwordsformatch*/31for(j=0;words[j][0]&&strcmp(temp,32&words[j][0])!=0;j++){33;/*emptybody*/34}/*endfor*/3536++count[j];/*incrementcount*/3738/*iftempcouldnotbefoundinwordsarray*/39if(!words[j][0]){40strcpy(&words[j][0],temp);41}/*endif*/4243temp=strtok(NULL,".n");44}/*endwhile*/4546}/*endfor*/4748putchar("n");4950/*loopthroughwordsarray*/51for(j=0;words[j][0]!=""&&j<=99;j++){52printf(""%s"appeared%dtime%sn",53&words[j][0],count[j],count[j]==1?"":"s");54}/*endfor*/5556return0;/*indicatesuccessfultermination*/5758}/*endmain*/Enterthreelinesoftext:Thisprogramcountsthenumberofoccurrencesofeachwordintheinputtext."This"appeared1time"program"appeared1time"counts"appeared1time"the"appeared2times"number"appeared1time"of"appeared2times"occurrences"appeared1time"each"appeared1time"word"appeared1time"in"appeared1time"input"appeared1time"text"appeared1time8.35(WordProcessing)Thedetailedtreatmentofstringmanipulationinthistextisgreatlyattributabletotheexcitinggrowthinwordprocessinginrecentyears.Oneimportantfunctioninwordprocessingsystemsistype-justification—thealignmentofwordstoboththeleftandrightmarginsofapage.Thisgeneratesaprofessional-lookingdocumentthatgivestheappearanceofbeingsetintype,ratherthanpreparedonatypewriter.Type-justificationcanbeaccomplishedoncomputersystemsbyinsertingoneormoreblankcharactersbetweeneachofthewordsinalinesothattherightmostwordalignswiththerightmargin.Writeaprogramthatreadsseverallinesoftextandprintsthistextintype-justifiedformat.Assumethatthetextistobeprintedon81/2-inch-widepaperandthatone-inchmarginsaretobeallowedonboththeleftandrightsidesoftheprintedpage.Assumethatthecomputerprints10characterstothehorizontalinch.Therefore,yourprogramshouldprint61/2inchesoftextor65charactersperline.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions3138.36(PrintingDatesinVariousFormats)Datesarecommonlyprintedinseveraldifferentformatsinbusinesscorrespondence.Twoofthemorecommonformatsare07/21/2003andJuly21,2003Writeaprogramthatreadsadateinthefirstformatandprintsthatdateinthesecondformat.ANS:1/*Exercise8.36solution*/2#include34intmain()5{67/*arrayofmonthnames*/8char*months[13]={"","January","February","March",9"April","May","June","July",10"August","September","October",11"November","December"};12intm;/*integermonth*/13intd;/*integerday*/14inty;/*integeryear*/1516/*readadatefromuser*/17printf("Enteradateintheformmm/dd/yyyy:");18scanf("%d/%d/%d",&m,&d,&y);1920/*outputdateinnewformat*/21printf("Thedateis:%s%d,%dn",months[m],d,y);2223return0;/*indicatesuccessfultermination*/2425}/*endmain*/Enteradateintheformmm/dd/yyyy:06/18/2003Thedateis:June18,20038.37(CheckProtection)Computersarefrequentlyusedincheck-writingsystems,suchaspayrollandaccountspayableappli-cations.Manystrangestoriescirculateregardingweeklypaychecksbeingprinted(bymistake)foramountsinexcessof$1million.Weirdamountsareprintedbycomputerizedcheck-writingsystemsbecauseofhumanerrorand/ormachinefailure.Systemsdesign-ers,ofcourse,makeeveryefforttobuildcontrolsintotheirsystemstopreventerroneouschecksfrombeingissued.Anotherseriousproblemistheintentionalalterationofacheckamountbysomeonewhointendstocashacheckfraudulently.Topreventadollaramountfrombeingaltered,mostcomputerizedcheck-writingsystemsemployatechniquecalledcheckprotec-tion.Checksdesignedforimprintingbycomputercontainafixednumberofspacesinwhichthecomputermayprintanamount.Supposeapaycheckcontainsnineblankspacesinwhichthecomputerissupposedtoprinttheamountofaweeklypaycheck.Iftheamountislarge,thenallnineofthosespaceswillbefilled,forexample:11,230.60(checkamount)---------123456789(positionnumbers)99.87---------123456789containsthreeblankspaces.Ifacheckisprintedwithblankspaces,itiseasierforsomeonetoaltertheamountofthecheck.Topreventacheckfrombeingaltered,manycheck-writingsystemsinsertleadingasteriskstoprotecttheamountasfollows:****99.87---------123456789©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com314CCharactersandStrings:SolutionsChapter8Writeaprogramthatinputsadollaramounttobeprintedonacheckandthenprintstheamountincheck-protectedformatwithleadingasterisksifnecessary.Assumethatninespacesareavailableforprintinganamount.ANS:1/*Exercise8.37solution*/2#include34intmain()5{6doubleamount;/*checkamount*/7doublebase=100000.0;/*basetochecknumberofdigits*/8inti;/*loopcounter*/9intj;/*loopcounter*/1011/*getcheckamount*/12printf("Entercheckamount:");13scanf("%lf",&amount);1415printf("Theprotectedamountis$");1617/*loopuntilamountislessthanbase*/18for(i=0;amount56intmain()7{89/*wordequivalentsofsingledigits*/10char*digits[10]={"","ONE","TWO","THREE","FOUR",11"FIVE","SIX","SEVEN","EIGHT","NINE"};1213/*wordequivalentsof10-19*/14char*teens[10]={"TEN","ELEVEN","TWELVE","THIRTEEN",15"FOURTEEN","FIFTEEN","SIXTEEN",16"SEVENTEEN","EIGHTEEN","NINETEEN"};1718/*wordequivalentsoftensdigits*/19char*tens[10]={"","TEN","TWENTY","THIRTY","FORTY",20"FIFTY","SIXTY","SEVENTY","EIGHTY",21"NINETY"};2223intdollars;/*checkdollaramount*/24intcents;/*checkcentsamount*/25intdigit1;/*onesdigit*/26intdigit2;/*tensdigit*/2728/*getcheckamount*/29printf("Enterthecheckamount(0.00to99.99):");30scanf("%d.%d",&dollars,¢s);31printf("nThecheckamountinwordsis:n");3233/*printequivalentwords*/34if(dollars<10){35printf("%s",digits[dollars]);36}/*endif*/37elseif(dollars<20){38printf("%s",teens[dollars-10]);39}/*endelseif*/40else{41digit1=dollars/10;/*onesdigit*/42digit2=dollars%10;/*tensdigit*/4344/*ifonesdigitiszero*/45if(digit2==0){46printf("%s",tens[digit1]);47}/*endif*/48else{49printf("%s-%s",tens[digit1],digits[digit2]);50}/*endelse*/5152}/*endelse*/5354printf("and%d/100n",cents);5556return0;/*indicatesuccessfultermination*/5758}/*endmain*/Enterthecheckamount(0.00to99.99):72.63Thecheckamountinwordsis:SEVENTY-TWOand63/100©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com316CCharactersandStrings:SolutionsChapter8Enterthecheckamount(0.00to99.99):13.22Thecheckamountinwordsis:THIRTEENand22/100Enterthecheckamount(0.00to99.99):5.75Thecheckamountinwordsis:FIVEand75/100ANS:8.39(MorseCode)PerhapsthemostfamousofallcodingschemesisMorsecode,developedbySamuelMorsein1832forusewiththetelegraphsystem.Morsecodeassignsaseriesofdotsanddashestoeachletterofthealphabet,eachdigit,andafewspecialcharacters(suchasperiod,comma,colonandsemicolon).Insound-orientedsystems,thedotrepresentsashortsoundandthedashrepresentsalongsound.Otherrepresentationsofdotsanddashesareusedwithlight-orientedsystemsandsignal-flagsystems.Separationbetweenwordsisindicatedbyaspace,—quitesimply,theabsenceofadotordash.Inasound-orientedsystem,aspaceisindicatedbyashortperiodoftimeduringwhichnosoundistransmitted.TheinternationalversionofMorsecodeappearsinFig.8.39.WriteaprogramthatreadsanEnglish-languagephraseandencodesthephraseintoMorsecode.AlsowriteaprogramthatreadsaphraseinMorsecodeandconvertsthephraseintotheEnglish-languageequivalent.UseoneblankbetweeneachMorse-codedletterandthreeblanksbetweeneachMorse-codedword.CharacterCodeCharacterCodeA.-T-B-...U..-C-.-.V...-D-..W.--E.X-..-F..-.Y-.--G--.Z--..H....I..DigitsJ.---1.----K-.-2..---L.-..3...--M--4....-N-.5.....O---6-....P.--.7--...Q--.-8---..R.-.9----.S...0-----Fig.8.1ThelettersofthealphabetasexpressedininternationalMorsecode.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter8CCharactersandStrings:Solutions3178.40(AMetricConversionProgram)Writeaprogramthatwillassisttheuserwithmetricconversions.Yourprogramshouldallowtheusertospecifythenamesoftheunitsasstrings(i.e.,centimeters,liters,grams,etc.,forthemetricsystemandinches,quarts,pounds,etc.,fortheEnglishsystem)andshouldrespondtosimplequestionssuchas"Howmanyinchesarein2meters?""Howmanylitersarein10quarts?"Yourprogramshouldrecognizeinvalidconversions.Forexample,thequestion"Howmanyfeetin5kilograms?"isnotmeaningful,because"feet"areunitsoflengthwhile"kilograms"areunitsofmass.8.41(DunningLetters)Manybusinessesspendagreatdealoftimeandmoneycollectingoverduedebts.Dunningistheprocessofmakingrepeatedandinsistentdemandsuponadebtorinanattempttocollectadebt.Computersareoftenusedtogeneratedunninglettersautomaticallyandinincreasingdegreesofseverityasadebtages.Thetheoryisthatasadebtbecomesolder,itbecomesmoredifficulttocollect,andthereforethedunninglettersmustbecomemorethreatening.Writeaprogramthatcontainsthetextsoffivedunninglettersofincreasingseverity.Yourprogramshouldacceptasinputthefollowing:a)Debtor’snameb)Debtor’saddressc)Debtor’saccountd)Amountowede)Ageoftheamountowed(i.e.,onemonthoverdue,twomonthsoverdue,etc.).Usetheageoftheamountowedtoselectoneofthefivemessagetexts,andthenprintthedunningletterinsertingtheotheruser-suppliedinformationwhereappropriate.ACHALLENGINGSTRINGMANIPULATIONPROJECT8.42(ACrossword-PuzzleGenerator)Mostpeoplehaveworkedacrosswordpuzzleatonetimeoranother,butfewhaveeverattemptedtogenerateone.Generatingacrosswordpuzzleisadifficultproblem.Itissuggestedhereasastringmanipulationprojectrequiringsubstantialsophisticationandeffort.Therearemanyissuestheprogrammermustresolvetogeteventhesimplestcrossword-puzzlegeneratorprogramworking.Forexample,howdoesonerepresentthegridofacrosswordpuzzleinsidethecom-puter?Shouldoneuseaseriesofstrings,orshoulddouble-subscriptedarraysbeused?Theprogrammerneedsasourceofwords(i.e.,acomputerizeddictionary)thatcanbedirectlyreferencedbytheprogram.Inwhatformshouldthesewordsbestoredtofacil-itatethecomplexmanipulationsrequiredbytheprogram?Thereallyambitiousreaderwillwanttogeneratethe“clues”portionofthepuzzleinwhichthebriefhintsforeach“across”wordandeach“down”wordareprintedforthepuzzleworker.Merelyprintingaversionoftheblankpuzzleitselfisnotasimpleproblem.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com318CCharactersandStrings:SolutionsChapter8©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com9CFormattedInput/Output:SolutionsSOLUTIONS9.4Writeaprintforscanfstatementforeachofthefollowing:a)Printunsignedinteger40000leftjustifiedina15-digitfieldwith8digits.ANS:printf(“%-15.8u”,(unsigned)40000);b)Readahexadecimalvalueintovariablehex.ANS:scanf(“%x”,hex);c)Print200withandwithoutasign.ANS:printf(“%+d%dn”,200,200);d)Print100inhexadecimalformprecededby0x.ANS:printf(%#xn”,100);e)Readcharactersintoarraysuntiltheletterpisencountered.ANS:scanf(“%[^p]”,s);f)Print1.234ina9-digitfieldwithprecedingzeros.ANS:printf(“%09.3fn”,1.234);g)Readatimeoftheformhh:mm:ss,storingthepartsofthetimeintheintegervariableshour,minuteandsecond.Skipthecolons(:)intheinputstream.Usetheassignmentsuppressioncharacter.ANS:scanf(“%d%*c%d%*c%d”,&hour,&minute,&second);h)Readastringoftheform"characters"fromthestandardinput.Storethestringincharacterarrays.Eliminatethequotationmarksfromtheinputstream.ANS:scanf(“”%[^”]”,s);i)Readatimeoftheformhh:mm:ss,storingthepartsofthetimeintheintegervariableshour,minuteandsecond.Skipthecolons(:)intheinputstream.Donotusetheassignment-suppressioncharacter.ANS:scanf(“%d:%d:%d:”,&hour,&minute,&second);9.5Showwhatisprintedbyeachofthefollowingstatements.Ifastatementisincorrect,indicatewhy.a)printf("%-10dn",10000);ANS:10000b)printf("%cn","Thisisastring");ANS:Astringcannotbeprintedwiththe%cspecifier.c)printf("%*.*lfn",8,3,1024.987654);ANS:1024.988d)printf("%#on%#Xn%#en",17,17,1008.83689);ANS:021©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com320CFormattedInput/Output:SolutionsChapter90X111.008837e+03e)printf("%ldn%+ldn",1000000,1000000);ANS:1000000+1000000f)printf("%10.2En",444.93738);ANS:4.45E+02precededbytwospacesg)printf("%10.2gn",444.93738);ANS:4.4e+02precededbythreespacesh)printf("%dn",10.987);ANS:Afloatingpointvaluecannotbeprintedwiththe%dconversionspecifier.9.6Findtheerror(s)ineachofthefollowingprogramsegments.Explainhoweacherrorcanbecorrected.a)printf("%sn","HappyBirthday");ANS:printf(“%sn”,“HappyBirthday”);b)printf("%cn","Hello");ANS:printf(“%sn”,“Hello”);c)printf("%cn","Thisisastring");ANS:printf(“%sn”,“Thisisastring”);d)Thefollowingstatementshouldprint"BonVoyage":printf(""%s"","BonVoyage");ANS:printf(““%s””,“BonVoyage”);e)charday[]="Sunday";printf("%sn",day[3]);ANS:printf(“%sn”,day);f)printf("Enteryourname:");ANS:printf(“Enteryourname:“);g)printf(%f,123.456);ANS:printf(“%f”,123.456);h)Thefollowingstatementshouldprintthecharacters"O"and"K":printf("%s%sn","O","K");ANS:printf(“%c%cn”,‘O’,‘K’);i)chars[10];scanf("%c",s[7]);ANS:scanf(“%c”,&s[7]);9.7Writeaprogramthatloads10-elementarraynumberwithrandomintegersfrom1to1000.Foreachvalue,printthevalueandarunningtotalofthenumberofcharactersprinted.Usethe%nconversionspecifiertodeterminethenumberofcharactersoutputforeachvalue.Printthetotalnumberofcharactersoutputforallvaluesuptoandincludingthecurrentvalueeachtimethecurrentvalueisprinted.Theoutputshouldhavethefollowingformat:ValueTotalcharacters34231000796310611etc.ANS:1/*Exercise9.7Solution*/2#include3#include4#include56intmain()7{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter9CFormattedInput/Output:Solutions3218inta[10]={0};/*randomintegersfrom1to1000*/9inti;/*loopcounter*/10intcount;/*numberofcharactersincurrentvalue*/11inttotalCount=0;/*totalcharactersinarray*/1213srand(time(NULL));1415/*fillthearraywithrandomnumbers*/16for(i=0;i<=9;i++){17a[i]=1+rand()%1000;18}/*endfor*/1920/*printtableheaders*/21printf("%st%sn","Value","Totalcharacters");2223/*loopthrough10elements*/24for(i=0;i<=9;i++){25printf("%d%n",a[i],&count);26totalCount+=count;/*updatetotalCount*/27printf("t%dn",totalCount);28}/*endfor*/2930return0;/*indicatesuccessfultermination*/3132}/*endmain*/ValueTotalcharacters84231852208658112751464717657206232324226471299.8Writeaprogramtotestthedifferencebetweenthe%dand%iconversionspecifierswhenusedinscanfstatements.Usethestatementsscanf("%i%d",&x,&y);printf("%d%dn",x,y);toinputandprintthevalues.Testtheprogramwiththefollowingsetsofinputdata:1010-10-100100100x100x10ANS:1/*Exercise9.8Solution*/2#include34intmain()5{6inti;/*loopcounter*/7intx;/*firstintegerfromuser*/8inty;/*secondintegerfromuser*/9©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com322CFormattedInput/Output:SolutionsChapter910/*loopfourtimes*/11for(i=1;i<=4;i++){12printf("nEntertwointegers:");13scanf("%i%d",&x,&y);14printf("%d%dn",x,y);15}/*endfor*/1617return0;/*indicatesuccessfultermination*/1819}/*endmain*/Entertwointegers:10101010Entertwointegers:-10-10-10-10Entertwointegers:010010810Entertwointegers:0x100x101609.9Writeaprogramthatprintspointervaluesusingalltheintegerconversionspecifiersandthe%pconversionspecifier.Whichonesprintstrangevalues?Whichonescauseerrors?Inwhichformatdoesthe%pconversionspecifierdisplaytheaddressonyoursystem?ANS:1/*Exercise9.9Solution*/2#include34intmain()5{6intx;/*definexfortesting*/78printf("%on",&x);9printf("%lon",&x);10printf("%dn",&x);11printf("%ldn",&x);12printf("%xn",&x);13printf("%lxn",&x);14printf("%pn",&x);1516return0;/*indicatesuccessfultermination*/1718}/*endmain*/457757445775741245052124505212ff7c12ff7c0012FF7C©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter9CFormattedInput/Output:Solutions3239.10Writeaprogramtotesttheresultsofprintingtheintegervalue12345andthefloating-pointvalue1.2345invarioussizefields.Whathappenswhenthevaluesareprintedinfieldscontainingfewerdigitsthanthevalues?ANS:1/*Exercise9.10Solution*/2#include34intmain()5{67/*printtheinteger12345*/8printf("%10dn",12345);9printf("%5dn",12345);10printf("%2dnn",12345);1112/*printthefloating-pointvalue1.2345*/13printf("%10fn",1.2345);14printf("%6fn",1.2345);15printf("%2fn",1.2345);1617return0;/*indicatesuccessfultermination*/1819}/*endmain*/1234512345123451.2345001.2345001.2345009.11Writeaprogramthatprintsthevalue100.453627roundedtothenearestdigit,tenth,hundredth,thousandthandtenthou-sandth.ANS:1/*Exercise9.11Solution*/2#include34intmain()5{6printf("%.0fn",100.453627);7printf("%.1fn",100.453627);8printf("%.2fn",100.453627);9printf("%.3fn",100.453627);10printf("%.4fn",100.453627);1112return0;/*indicatesuccessfultermination*/1314}/*endmain*/100100.5100.45100.454100.4536©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com324CFormattedInput/Output:SolutionsChapter99.12Writeaprogramthatinputsastringfromthekeyboardanddeterminesthelengthofthestring.Printthestringusingtwicethelengthasthefieldwidth.ANS:1/*Exercise9.12Solution*/2#include34intmain()5{6intcount;/*lengthofstring*/7charstring[20];/*stringenteredbyuser*/89/*readstringfromuserandfindlength*/10printf("Enterastring:n");11scanf("%s%n",string,&count);1213printf("%*sn",2*count,string);/*printthestring*/1415return0;/*indicatesuccessfultermination*/1617}/*endmain*/Enterastring:hellohello©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter9CFormattedInput/Output:Solutions3259.13WriteaprogramthatconvertsintegerFahrenheittemperaturesfrom0to212degreestofloating-pointCelsiustemperatureswith3digitsofprecision.Usetheformulacelsius=5.0/9.0*(fahrenheit-32);toperformthecalculation.Theoutputshouldbeprintedintworight-justifiedcolumnsof10characterseach,andtheCelsiustem-peraturesshouldbeprecededbyasignforbothpositiveandnegativevalues.ANS:1/*Exercise9.13Solution*/2#include34intmain()5{6intfahrenheit;/*holdsfahrenheittemperature*/7doublecelcius;/*holdscelciustemperature*/89printf("%10s%12sn","Fahrenheit","Celcius");1011/*convertfahrenheittocelsiusanddisplaytemperatures12showingthesignforcelsiustemperatures*/13for(fahrenheit=0;fahrenheit<=212;fahrenheit++){14celcius=5.0/9.0*(fahrenheit-32);15printf("%10d%+12.3fn",fahrenheit,celcius);16}/*endfor*/1718return0;/*indicatesuccessfultermination*/1920}/*endmain*/FahrenheitCelcius0-17.7781-17.2222-16.6673-16.1114-15.5565-15.0006-14.4447-13.889...204+95.556205+96.111206+96.667207+97.222208+97.778209+98.333210+98.889211+99.444212+100.000©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com326CFormattedInput/Output:SolutionsChapter99.14WriteaprogramtotestalltheescapesequencesinFigure9.16.Fortheescapesequencesthatmovethecursor,printachar-acterbeforeandafterprintingtheescapesequencesoitisclearwherethecursorhasmoved.ANS:1/*Exercise9.14Solution*/2#include34intmain()5{67/*testallescapesequences*/8printf("Thesinglequote:"n");9printf("Thedoublequote:"n");10printf("Thequestionmark:?n");11printf("Thebackslash:\n");1213printf("Thebell.ann");1415printf("Movecursorbackonepositiononcurrentline.*b*n");16printf("Movecursortostartofnextlogicalpage.*f*n");1718printf("Movecursortothebeginningofnextline.*n*n");19printf("Movecursortothebeginningofcurrentline.*r*n");2021printf("Movecursortothenexthorizontaltabposition.*t*n");22printf("Movecursortothenextverticaltabposition.*v*n");2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/Thesinglequote:"Thedoublequote:"Thequestionmark:?Thebackslash:Thebell.Movecursorbackonepositiononcurrentline.*Movecursortostartofnextlogicalpage.*?*Movecursortothebeginningofnextline.***ovecursortothebeginningofcurrentline.*Movecursortothenexthorizontaltabposition.**Movecursortothenextverticaltabposition.*?*©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter9CFormattedInput/Output:Solutions3279.15Writeaprogramthatdetermineswhether?canbeprintedaspartofaprintfformatcontrolstringasaliteralcharacterratherthanusingthe?escapesequence.ANS:1/*Exercise9.15Solution*/2#include34intmain()5{6printf("Didthe?printattheendofthesentence?n");78return0;/*indicatesuccessfultermination*/910}/*endmain*/Didthe?printattheendofthesentence?©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com328CFormattedInput/Output:SolutionsChapter99.16Writeaprogramthatinputsthevalue437usingeachofthescanfintegerconversionspecifiers.Printeachinputvalueusingalltheintegerconversionspecifiers.ANS:1/*Exercise9.16Solution*/2#include34intmain()5{6intarray[5];/*holdsthevalue437fivetimes*/7intloop;/*loopcounter*/89/*arrayoftableheaders*/10char*s[]={"Readwith%d:","Readwith%i:","Readwith%o:",11"Readwith%u:","Readwith%x:"};1213/*prompttheuserandread5values*/14printf("Enterthevalue437fivetimes:");15scanf("%d%i%o%u%x",&array[0],&array[1],&array[2],16&array[3],&array[4]);1718/*loopthroughall5values*/19for(loop=0;loop<=4;loop++){2021/*printeachofthe5values*/22printf("%sn%d%i%o%u%xnn",s[loop],array[loop],23array[loop],array[loop],array[loop],array[loop]);24}/*endfor*/2526return0;/*indicatesuccessfultermination*/2728}/*endmain*/Enterthevalue437fivetimes:437437437437437Readwith%d:4374376654371b5Readwith%i:4374376654371b5Readwith%o:28728743728711fReadwith%u:4374376654371b5Readwith%x:1079107920671079437©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter9CFormattedInput/Output:Solutions3299.17Writeaprogramthatuseseachoftheconversionspecifierse,fandgtoinputthevalue1.2345.Printthevaluesofeachvariabletoprovethateachconversionspecifiercanbeusedtoinputthissamevalue.ANS:1/*Exercise9.17Solution*/2#include34intmain()5{6floata[3];/*holdsthevalue1.2345threetimes*/78/*arrayoftableheaders*/9char*s[]={"Readwith%e:","Readwith%f:","Readwith%g:"};1011/*prompttheuserandread3values*/12printf("Enterthevalue1.2345threetimes:");13scanf("%e%f%g",&a[0],&a[1],&a[2]);1415printf("%s%enn",s[0],a[0]);16printf("%s%fnn",s[1],a[1]);17printf("%s%gnn",s[2],a[2]);1819return0;/*indicatesuccessfultermination*/2021}/*endmain*/Enterthevalue1.2345threetimes:1.23451.23451.2345Readwith%e:1.234500e+000Readwith%f:1.234500Readwith%g:1.2345©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com330CFormattedInput/Output:SolutionsChapter99.18Insomeprogramminglanguages,stringsareenteredsurroundedbyeithersingleordoublequotationmarks.Writeapro-gramthatreadsthethreestringssuzy,"suzy"and"suzy".ArethesingleanddoublequotesignoredbyCorreadaspartofthestring?ANS:22/*Exercise9.18Solution*/23#include2425intmain()26{27chara[10];/*firststring*/28charb[10];/*secondstring*/29charc[10];/*thirdstring*/3031/*promptuserandreadthreestrings*/32printf("Enterthestringssuzy,"suzy",and"suzy":n");33scanf("%s%s%s",a,b,c);3435printf("%s%s%sn",a,b,c);/*displaystrings*/3637return0;/*indicatesuccessfultermination*/3839}/*endmain*/Enterthestringssuzy,"suzy",and"suzy":suzy"suzy""suzy"suzy"suzy""suzy"9.19Writeaprogramthatdetermineswhether?canbeprintedasthecharacterconstant"?"ratherthanthecharacterconstantescapesequence"?"usingconversionspecifier%cintheformatcontrolstringofaprintfstatement.ANS:1/*Exercise9.19Solution*/2#include34intmain()5{6constcharquestionMark="?";/*define"?"asacharconstant*/78printf("This%ccanbeprintedwithoutusingthe\?n",9questionMark);1011return0;/*indicatesuccessfultermination*/1213}/*endmain*/This?canbeprintedwithoutusingthe?©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter9CFormattedInput/Output:Solutions3319.20Writeaprogramthatusestheconversionspecifiergtooutputthevalue9876.12345.Printthevaluewithprecisionsrang-ingfrom1to9.ANS:1/*Exercise9.20Solution*/2#include34intmain()5{67/*outputthevalue9876.12345withprecisionsfrom1to9*/8printf("Precision:%d,value=%.1gn",1,9876.12345);9printf("Precision:%d,value=%.2gn",2,9876.12345);10printf("Precision:%d,value=%.3gn",3,9876.12345);11printf("Precision:%d,value=%.4gn",4,9876.12345);12printf("Precision:%d,value=%.5gn",5,9876.12345);13printf("Precision:%d,value=%.6gn",6,9876.12345);14printf("Precision:%d,value=%.7gn",7,9876.12345);15printf("Precision:%d,value=%.8gn",8,9876.12345);16printf("Precision:%d,value=%.9gn",9,9876.12345);1718return0;/*indicatesuccessfultermination*/1920}/*endmain*/Precision:1,value=1e+004Precision:2,value=9.9e+003Precision:3,value=9.88e+003Precision:4,value=9876Precision:5,value=9876.1Precision:6,value=9876.12Precision:7,value=9876.123Precision:8,value=9876.1234Precision:9,value=9876.12345©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com332CFormattedInput/Output:SolutionsChapter9©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com10Structures,Unions,BitManipulationsandEnumerations:SolutionsSolutions10.5Providethedefinitionforeachofthefollowingstructuresandunions:a)StructureinventorycontainingcharacterarraypartName[30],integerpartNumber,floatingpointprice,integerstockandintegerreorder.ANS:structinventory{charpartName[30];intpartNumber;floatprice;intstock;intreorder;};b)Uniondatacontainingcharc,shorts,longb,floatfanddoubled.ANS:uniondata{charc;shorts;longl;floatf;doubled;};c)AstructurecalledaddressthatcontainscharacterarraysstreetAddress[25],city[20],state[3]andzipCode[6].ANS:structaddress{charstreetAddress[25];charcity[20];charstate[3];charzipCode[6];};d)StructurestudentthatcontainsarraysfirstName[15]andlastName[15]andvariablehomeAddressoftypestructaddressfrompart(c).ANS:structstudent{charfirstName[15];©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com334Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter10charlastName[15];structaddresshomeAddress;};e)Structuretestcontaining16bitfieldswithwidthsof1bit.Thenamesofthebitfieldsarethelettersatop.ANS:structtest{unsigneda:1,b:1,c:1,d:1,e:1,f:1,g:1,h:1,i:1,j:1,k:1,l:1,m:1,n:1,o:1,p:1;};10.6Giventhefollowingstructureandvariabledefinitions,structcustomer{charlastName[15];charfirstName[15];intcustomerNumber;struct{charphoneNumber[11];charaddress[50];charcity[15];charstate[3];charzipCode[6];}personal;}customerRecord,*customerPtr;customerPtr=&customerRecord;writeanexpressionthatcanbeusedtoaccessthestructuremembersineachofthefollowingparts:a)MemberlastNameofstructurecustomerRecord.ANS:customerRecord.lastNameb)MemberlastNameofthestructurepointedtobycustomerPtr.ANS:customerPtr->lastNamec)MemberfirstNameofstructurecustomerRecord.ANS:customerRecord.firstNamed)MemberfirstNameofthestructurepointedtobycustomerPtr.ANS:customerPtr->firstNamee)MembercustomerNumberofstructurecustomerRecord.ANS:customerRecord.customerNumberf)MembercustomerNumberofthestructurepointedtobycustomerPtr.ANS:customerRecord->customerNumberg)MemberphoneNumberofmemberpersonalofstructurecustomerRecord.ANS:customerRecord.personal.phoneNumberh)MemberphoneNumberofmemberpersonalofthestructurepointedtobycustomerPtr.ANS:customerRecord->personal.phoneNumberi)MemberaddressofmemberpersonalofstructurecustomerRecord.ANS:customerRecord.personal.addressj)MemberaddressofmemberpersonalofthestructurepointedtobycustomerPtr.ANS:customerRecord->personal.addressk)MembercityofmemberpersonalofstructurecustomerRecord.ANS:customerRecord.personal.cityl)MembercityofmemberpersonalofthestructurepointedtobycustomerPtr.ANS:customerRecord->personal.citym)MemberstateofmemberpersonalofstructurecustomerRecord.ANS:customerRecord.personal.staten)MemberstateofmemberpersonalofthestructurepointedtobycustomerPtr.ANS:customerRecord->personal.stateo)MemberzipCodeofmemberpersonalofcustomerRecord.ANS:customerRecord.personal.zipCodep)MemberzipCodeofmemberpersonalofthestructurepointedtobycustomerPtr.ANS:customerRecord->personal.zipCode©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions33510.7ModifytheprogramofFig.10.16toshufflethecardsusingahighperformanceshuffle(asshowninFig.10.3).PrinttheresultingdeckintwocolumnformatasinFig.10.4.Precedeeachcardwithitscolor.ANS:1/*Exercise10.7Solution*/2#include3#include4#include56/*bitCardstructuredefinition*/7structbitCard{8unsignedface:4;/*4bits;0-15*/9unsignedsuit:2;/*2bits;0-3*/10unsignedcolor:1;/*1bit;0-1*/11};/*endstructurebitCard*/1213/*newtypenameCard*/14typedefstructbitCardCard;1516/*prototypes*/17voidfillDeck(Card*wDeck);18voidshuffle(Card*wDeck);19voiddeal(Card*wDeck2);2021intmain()22{23Carddeck[52];/*createarrayofCards*/2425srand(time(NULL));/*randomize*/2627fillDeck(deck);28shuffle(deck);29deal(deck);3031return0;/*indicatesuccessfultermination*/3233}/*endmain*/3435/*create52cards*/36voidfillDeck(Card*wDeck)37{38inti;/*loopcounter*/3940/*loop52timesandcreatecards*/41for(i=0;i<=51;i++){42wDeck[i].face=i%13;43wDeck[i].suit=i/13;44wDeck[i].color=i/26;45}/*endfor*/4647}/*endfunctionfillDeck*/4849/*shufflecards*/50voidshuffle(Card*wDeck)51{52inti;/*currentcard*/53intj;/*randomcardtoswapwithcurrentcard*/54Cardtemp;/*temporaryCard*/55©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com336Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1056/*loopthroughdeck*/57for(i=0;i<=51;i++){58j=rand()%52;5960/*swapcardsifnotequal*/61if(i!=j){62temp=wDeck[i];63wDeck[i]=wDeck[j];64wDeck[j]=temp;65}/*endif*/6667}/*endfor*/6869}/*endfunctionshuffle*/7071/*dealthecards*/72voiddeal(Card*wDeck2)73{7475/*arraysface,suitandcolorholdallpossiblestring76descriptionsofthecards*/77char*face[]={"Ace","Deuce","Three","Four","Five","Six",78"Seven","Eight","Nine","Ten","Jack","Queen","King"};79char*suit[]={"Hearts","Diamonds","Clubs","Spades"};80char*color[]={"Red","Black"};81inti;/*loopcounter*/8283/*loopthroughdeckandprintstringdescriptionofeachcard*/84for(i=0;i<=51;i++){85printf("%5s:%5sof%-8s",color[wDeck2[i].color],86face[wDeck2[i].face],suit[wDeck2[i].suit]);87putchar((i+1)%2?"t":"n");88}/*endfor*/8990}/*endfunctiondeal*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions337Red:EightofDiamondsRed:QueenofHeartsRed:JackofHeartsRed:SevenofHeartsRed:ThreeofDiamondsBlack:EightofSpadesBlack:TenofSpadesBlack:ThreeofClubsBlack:JackofSpadesBlack:DeuceofSpadesRed:DeuceofDiamondsRed:TenofHeartsRed:QueenofDiamondsRed:KingofDiamondsBlack:NineofClubsBlack:AceofSpadesRed:SevenofDiamondsRed:ThreeofHeartsBlack:NineofSpadesRed:FiveofDiamondsBlack:JackofClubsBlack:SixofSpadesBlack:FiveofClubsBlack:QueenofClubsBlack:AceofClubsRed:NineofHeartsRed:TenofDiamondsRed:AceofDiamondsBlack:DeuceofClubsRed:FourofDiamondsBlack:SevenofClubsRed:KingofHeartsRed:SixofHeartsRed:DeuceofHeartsRed:JackofDiamondsBlack:ThreeofSpadesRed:FourofHeartsBlack:FourofClubsBlack:TenofClubsBlack:SixofClubsRed:NineofDiamondsBlack:KingofSpadesRed:AceofHeartsBlack:FiveofSpadesBlack:FourofSpadesBlack:QueenofSpadesBlack:SevenofSpadesRed:FiveofHeartsRed:EightofHeartsBlack:KingofClubsBlack:EightofClubsRed:SixofDiamonds©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com338Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1010.8Createunionintegerwithmemberscharc,shorts,intiandlongb.Writeaprogramthatinputsvalueoftypechar,short,intandlongandstoresthevaluesinunionvariablesoftypeunioninteger.Eachunionvariableshouldbeprintedasachar,ashort,anintandalong.Dothevaluesalwaysprintcorrectly?ANS:1/*Exercise10.8Solution*/2/*NOTE:Theprogramoutputismachinedependent*/3#include45/*integeruniondefinition*/6unioninteger{7charc;/*characterinputbyuser*/8shorts;/*shortintegerinputbyuser*/9inti;/*integerinputbyuser*/10longl;/*longintegerinputbyuser*/11};/*endunioninteger*/1213intmain()14{15unionintegera;/*defineuniona*/1617/*readacharacterfromuserintotheunion*/18printf("Enteracharacter:");19scanf("%c",&a.c);2021/*printeachvalueofunion*/22printf(""%c"printedasacharacteris%cn",a.c,a.c);23printf(""%c"printedasashortintegeris%hdn",a.c,a.s);24printf(""%c"printedasanintegeris%dn",a.c,a.i);25printf(""%c"printedasalongintegeris%ldn",a.c,a.l);2627/*readashortintegerfromuserintotheunion*/28printf("nEnterashortinteger:");29scanf("%hd",&a.s);3031/*printeachvalueofunion*/32printf("%hdprintedasacharacteris%cn",a.s,a.c);33printf("%hdprintedasashortintegeris%hdn",a.s,a.s);34printf("%hdprintedasanintegeris%dn",a.s,a.i);35printf("%hdprintedasalongintegeris%ldn",a.s,a.l);3637/*readanintegerfromuserintotheunion*/38printf("nEnteraninteger:");39scanf("%d",&a.i);4041/*printeachvalueofunion*/42printf("%dprintedasacharacteris%cn",a.i,a.c);43printf("%dprintedasashortintegeris%hdn",a.i,a.s);44printf("%dprintedasanintegeris%dn",a.i,a.i);45printf("%dprintedasalongintegeris%ldn",a.i,a.l);4647/*readalongintegerfromuserintotheunion*/48printf("nEnteralonginteger:");49scanf("%ld",&a.l);5051/*printeachvalueofunion*/52printf("%ldprintedasacharacteris%cn",a.l,a.c);53printf("%ldprintedasashortintegeris%hdn",a.l,a.s);54printf("%ldprintedasanintegeris%dn",a.l,a.i);55printf("%ldprintedasalongintegeris%ldn",a.l,a.l);56©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions33957return0;/*indicatesuccessfultermination*/5859}/*endmain*/Enteracharacter:A"A"printedasacharacterisA"A"printedasashortintegeris-13247"A"printedasanintegeris-858993599"A"printedasalongintegeris-858993599Enterashortinteger:9797printedasacharacterisa97printedasashortintegeris9797printedasanintegeris-85904579197printedasalongintegeris-859045791Enteraninteger:3270032700printedasacharacteris+32700printedasashortintegeris3270032700printedasanintegeris3270032700printedasalongintegeris32700Enteralonginteger:1000000010000000printedasacharacterisÇ10000000printedasashortintegeris-2700810000000printedasanintegeris1000000010000000printedasalongintegeris10000000©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com340Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1010.9CreateunionfloatingPointwithmembersfloatf,doubledandlongdoublex.Writeaprogramthatinputsvalueoftypefloat,doubleandlongdoubleandstoresthevaluesinunionvariablesoftypeunionfloatingPoint.Eachunionvariableshouldbeprintedasafloat,adoubleandalongdouble.Dothevaluesalwaysprintcorrectly?ANS:1/*Exercise10.9Solution*/2/*NOTE:Theprogramoutputismachinedependent*/3#include45/*floatingPointuniondefinition*/6unionfloatingPoint{7floatf;/*floating-pointvalueinputbyuser*/8doubled;/*doublevalueinputbyuser*/9longdoublel;/*longdoublevalueinputbyuser*/10};/*endunionfloatingPoint*/1112intmain()13{14unionfloatingPointa;/*defineuniona*/1516/*readafloating-pointvaluefromuserintotheunion*/17printf("Enterafloat:");18scanf("%f",&a.f);1920/*printeachvalueofunion*/21printf("%fprintedasafloatis%fn",a.f,a.f);22printf("%fprintedasadoubleis%fn",a.f,a.d);23printf("%fprintedasalongdoubleis%Lfn",a.f,a.l);2425/*readadoublevaluefromuserintotheunion*/26printf("nEnteradouble:");27scanf("%lf",&a.d);2829/*printeachvalueofunion*/30printf("%lfprintedasafloatis%fn",a.d,a.f);31printf("%lfprintedasadoubleis%fn",a.d,a.d);32printf("%lfprintedasalongdoubleis%Lfn",a.d,a.l);3334/*readalongdoublevaluefromuserintotheunion*/35printf("nEnteralongdouble:");36scanf("%Lf",&a.l);3738/*printeachvalueofunion*/39printf("%Lfprintedasafloatis%fn",a.l,a.f);40printf("%Lfprintedasadoubleis%fn",a.l,a.d);41printf("%Lfprintedasalongdoubleis%Lfn",a.l,a.l);4243return0;/*indicatesuccessfultermination*/4445}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions341Enterafloat:7.27.200000printedasafloatis7.2000007.200000printedasadoubleis-92559604549802064000000000000000000000000000000000000000000000.0000007.200000printedasalongdoubleis-92559604549802064000000000000000000000000000000000000000000000.000000Enteradouble:3884.293823874233884.293824printedasafloatis184710340379508400000000000000.0000003884.293824printedasadoubleis3884.2938243884.293824printedasalongdoubleis3884.293824Enteralongdouble:833738.9384434797833738.938443printedasafloatis-72537143835359183000.000000833738.938443printedasadoubleis833738.938443833738.938443printedasalongdoubleis833738.938443©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com342Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1010.10Writeaprogramthatrightshiftsanintegervariable4bits.Theprogramshouldprinttheintegerinbitsbeforeandaftertheshiftoperation.Doesyoursystemplace0sor1sinthevacatedbits?ANS:1/*Exercise10.10Solution*/2#include34voiddisplayBits(unsignedvalue);/*prototype*/56intmain()7{8unsignedval;/*valuefromuser*/910/*promptuserandreadvalue*/11printf("Enteraninteger:");12scanf("%u",&val);1314/*displayvaluebeforeshifting*/15printf("%ubeforerightshifting4bitsis:n",val);16displayBits(val);1718/*displayvalueaftershifting*/19printf("%uafterrightshifting4bitsis:n",val);20displayBits(val>>4);2122return0;/*indicatesuccessfultermination*/2324}/*endmain*/2526/*functiondisplayBitsprintseachbitofvalue*/27voiddisplayBits(unsignedvalue)28{29unsignedc;/*bitcounter*/30unsigneddisplayMask=1<<15;/*bitmask*/3132printf("%7u=",value);3334/*loopthroughbits*/35for(c=1;c<=16;c++){36value&displayMask?putchar("1"):putchar("0");37value<<=1;/*shiftvalue1bittotheleft*/3839if(c%8==0){/*printaspace*/40putchar("");41}/*endif*/4243}/*endfor*/4445putchar("n");46}/*endfunctiondisplayBits*/Enteraninteger:12341234beforerightshifting4bitsis:1234=00000100110100101234afterrightshifting4bitsis:77=0000000001001101©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions34310.11Ifyourcomputeruses2-byteintegers,modifytheprogramofFig.10.7sothatitworkswith2-byteintegers.10.12Leftshiftinganunsignedintegerby1bitisequivalenttomultiplyingthevalue2.Writefunctionpower2thattakestwointegerargumentsnumberandpowandcalculatesnumber*2powUsetheshiftoperatortocalculatetheresult.Printthevaluesasintegersandasbits.ANS:1/*Exercise10.12Solution*/2#include34/*prototypes*/5voiddisplayBits(unsignedvalue);6unsignedpower2(unsignedn,unsignedp);78intmain()9{10unsignednumber;/*valuefromuser*/11unsignedpow;/*numberofbitstoleftshift*/12unsignedresult;/*resultofshift*/1314/*promptuserandreadtwointegers*/15printf("Entertwointegers:");16scanf("%u%u",&number,&pow);1718/*displaybitsofnumber*/19printf("number:n");20displayBits(number);2122/*displaybitsofpow*/23printf("npow:n");24displayBits(pow);2526/*performshiftanddisplayresults*/27result=power2(number,pow);28printf("n%u*2^%u=%un",number,pow,result);29displayBits(result);3031return0;/*indicatesuccessfultermination*/3233}/*endmain*/3435/*functionpower2leftshiftsnbyp*/36unsignedpower2(unsignedn,unsignedp)37{38returnn<34/*prototypes*/5unsignedpackCharacters(charx,chary);6voiddisplayBits(unsignedvalue);78intmain()9{10chara;/*firstcharacterfromuser*/11charb;/*secondcharacterfromuser*/12unsignedresult;/*resultofpackingbothcharacters*/1314/*promptuserandreadtwocharacters*/15printf("Entertwocharacters:");16scanf("%c%c",&a,&b);1718/*displayfirstcharacterasbits*/19printf(""%c"inbitsasanunsignedintegersis:n",a);20displayBits(a);2122/*displaysecondcharacterasbits*/23printf("n"%c"inbitsasanunsignedintegersis:n",b);24displayBits(b);2526/*packcharactersanddisplayresult*/27result=packCharacters(a,b);28printf("n"%c"and"%c"packedinanunsignedinteger:n",29a,b);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions34530displayBits(result);3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/3536/*functionpackCharacterspackstwocharactersintoanunsignedint*/37unsignedpackCharacters(charx,chary)38{39unsignedpack=x;/*initializepacktox*/4041pack<<=8;/*shiftpack8bitstotheleft*/42pack|=y;/*packyusinginclusiveORoperator*/43returnpack;4445}/*endfunctionpackCharacters*/4647/*displaythebitsofvalue*/48voiddisplayBits(unsignedvalue)49{50unsignedc;/*bitcounter*/51unsigneddisplayMask=1<<15;/*bitmask*/5253printf("%7u=",value);5455/*loopthroughbits*/56for(c=1;c<=16;c++){57value&displayMask?putchar("1"):putchar("0");58value<<=1;/*shiftvalue1bittotheleft*/5960if(c%8==0){/*printaspace*/61putchar("");62}/*endif*/6364}/*endfor*/6566putchar("n");67}/*endfunctiondisplayBits*/Entertwocharacters:AB"A"inbitsasanunsignedintegersis:65=0000000001000001"B"inbitsasanunsignedintegersis:66=0000000001000010"A"and"B"packedinanunsignedinteger:16706=0100000101000010©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com346Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1010.14Usingtheright-shiftoperator,thebitwiseANDoperatorandamask,writefunctionunpackCharactersthattakestheunsignedintegerfromExercise10.13andunpacksitintotwocharacters.Tounpacktwocharactersfromanunsignedinteger,combinetheunsignedintegerwiththemask65280(00000000000000001111111100000000)andrightshifttheresult8bits.Assigntheresultingvaluetoacharvariable.Thencombinetheunsignedintegerwiththemask255(00000000000000000000000011111111).Assigntheresulttoanothercharvariable.Theprogramshouldprinttheunsignedintegerinbitsbeforeitisunpacked,thenprintthecharactersinbitstoconfirmthattheywereunpackedcorrectly.ANS:1/*Exercise10.14Solution*/2#include34/*prototypes*/5voidunpackCharacters(char*aPtr,char*bPtr,unsignedpack);6voiddisplayBits(unsignedvalue);78intmain()9{10chara;/*firstcharacterunpacked*/11charb;/*secondcharacterunpacked*/12unsignedpacked=16706;/*initializepackedvalue*/1314/*displaybitsofpacked*/15printf("Thepackedcharacterrepresentationis:n");16displayBits(packed);1718/*unpackpackedanddisplayresults*/19unpackCharacters(&a,&b,packed);20printf("nTheunpackedcharactersare"%c"and"%c"n",a,b);21displayBits(a);22displayBits(b);2324return0;/*indicatesuccessfultermination*/2526}/*endmain*/2728/*unpacktwocharactersfrompack*/29voidunpackCharacters(char*aPtr,char*bPtr,unsignedpack)30{31unsignedmask1=65280;/*maskforfirstcharacter*/32unsignedmask2=255;/*maskforsecondcharacter*/3334*aPtr=(pack&mask1)>>8;/*separatefirstcharacter*/35*bPtr=(pack&mask2);/*separatesecondcharacter*/36}/*endfunctionunpackCharacters*/3738/*displaythebitsofvalue*/39voiddisplayBits(unsignedvalue)40{41unsignedc;/*bitcounter*/42unsigneddisplayMask=1<<15;/*bitmask*/4344printf("%7u=",value);4546/*loopthroughbits*/47for(c=1;c<=16;c++){48value&displayMask?putchar("1"):putchar("0");49value<<=1;/*shiftvalue1bittotheleft*/5051if(c%8==0){/*printaspace*/52putchar("");53}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions3475455}/*endfor*/5657putchar("n");58}/*endfunctiondisplayBits*/Thepackedcharacterrepresentationis:16706=0100000101000010Theunpackedcharactersare"A"and"B"65=000000000100000166=000000000100001010.15Ifyoursystemuses4-byteintegers,rewritetheprogramofExercise10.13topack4characters.10.16Ifyoursystemuses4-byteintegers,rewritethefunctionunpackCharactersofExercise10.14tounpack4characters.Createthemasksyouneedtounpackthe4charactersbyleftshiftingthevalue255inthemaskvariableby8bits0,1,2or3times(dependingonthebyteyouareunpacking).©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com348Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1010.17Writeaprogramthatreversestheorderofthebitsinanunsignedintegervalue.TheprogramshouldinputthevaluefromtheuserandcallfunctionreverseBitstoprintthebitsinreverseorder.Printthevalueinbitsbothbeforeandafterthebitsarereversedtoconfirmthatthebitsarereversedproperly.ANS:1/*Exercise10.17Solution*/2#include34/*prototypes*/5unsignedreverseBits(unsignedvalue);6voiddisplayBits(unsignedvalue);78intmain()9{10unsigneda;/*unsignedintegerfromuser*/1112/*promptuserandreadvalue*/13printf("Enteranunsignedinteger:");14scanf("%u",&a);1516/*displaybitsofabeforereversed*/17printf("nBeforebitsarereversed:n");18displayBits(a);1920/*reversebitsanddisplayresults*/21a=reverseBits(a);22printf("nAfterbitsarereversed:n");23displayBits(a);2425return0;/*indicatesuccessfultermination*/2627}/*endmain*/2829/*reverseBitsreversesthebitsofvalue*/30unsignedreverseBits(unsignedvalue)31{32unsignedmask=1;/*bitmask*/33unsignedtemp=0;/*reversedbits*/34inti;/*loopcounter*/3536/*loopthroughbitsofvalue*/37for(i=0;i<=15;i++){38temp<<=1;/*rightshift1bit*/39temp|=(value&mask);/*separatebitandplaceintemp*/40value>>=1;/*leftshift1bit*/41}/*endfor*/4243returntemp;4445}/*endfunctionreverseBits*/4647/*displaythebitsofvalue*/48voiddisplayBits(unsignedvalue)49{50unsignedc;/*bitcounter*/51unsigneddisplayMask=1<<15;/*bitmask*/5253printf("%7u=",value);5455/*loopthroughbits*/56for(c=1;c<=16;c++){©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions34957value&displayMask?putchar("1"):putchar("0");58value<<=1;/*shiftvalue1bittotheleft*/5960if(c%8==0){/*printaspace*/61putchar("");62}/*endif*/6364}/*endfor*/6566putchar("n");67}/*endfunctiondisplayBits*/Enteranunsignedinteger:2127Beforebitsarereversed:2127=0000100001001111Afterbitsarereversed:61968=1111001000010000©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com350Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1010.18ModifyfunctiondisplayBitsofFig.10.7soitisportablebetweensystemsusing2-byteintegersandsystemsusing4-byteintegers.[Hint:Usethesizeofoperatortodeterminethesizeofanintegeronaparticularmachine.]ANS:1/*Exercise10.18Solution*/2#include34voiddisplayBits(unsignedvalue);/*prototype*/56intmain()7{8unsignedx;/*valuefromuser*/910/*promptuserandreadvalue*/11printf("Enteranunsignedinteger:");12scanf("%u",&x);13displayBits(x);1415return0;/*indicatesuccessfultermination*/1617}/*endmain*/1819/*displaythebitsofvalue*/20voiddisplayBits(unsignedvalue)21{22unsignedc;/*bitcounter*/23unsigneddisplayMask;/*bitmask*/2425/*ifsystemuses4-byteintegers*/26if(sizeof(int)==4){27displayMask=1<<31;28}/*endif*/29else{/*assumedefaultof2-byteintegers*/30displayMask=1<<15;31}/*endelse*/3233printf("%7u=",value);3435/*loopthroughbits*/36for(c=1;c<=sizeof(int)*8;c++){37putchar(value&displayMask?"1":"0");38value<<=1;/*shiftvalue1bittotheleft*/3940if(c%8==0){/*printaspace*/41putchar("");42}/*endif*/4344}/*endfor*/4546putchar("n");47}/*endfunctiondisplayBits*/Enteranunsignedinteger:23452345=00000000000000000000100100101001©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter10Structures,Unions,BitManipulationsandEnumerations:Solutions35110.19ThefollowingprogramusesfunctionmultipletodetermineiftheintegerenteredfromthekeyboardisamultipleofsomeintegerX.Examinethefunctionmultiple,thendeterminethevalueofX.1/*ex10_19.c*/2/*ThisprogramdeterminesifavalueisamultipleofX.*/3#include45intmultiple(intnum);/*prototype*/67intmain()8{9inty;/*ywillholdanintegerenteredbytheuser*/1011printf("Enteranintegerbetween1and32000:");12scanf("%d",&y);1314/*ifyisamultipleofX*/15if(multiple(y)){16printf("%disamultipleofXn",y);17}/*endif*/18else{19printf("%disnotamultipleofXn",y);20}/*endelse*/2122return0;/*indicatessuccessfultermination*/23}/*endmain*/2425/*determineifnumisamultipleofX*/26intmultiple(intnum)27{28inti;/*counter*/29intmask=1;/*initializemask*/30intmult=1;/*initializemult*/3132for(i=1;i<=10;i++,mask<<=1){3334if((num&mask)!=0){35mult=0;36break;37}/*endif*/3839}/*endfor*/4041returnmult;42}/*endfunctionmultiple*/ANS:Enteranintegerbetween1and32000:10241024isamultipleofX©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com352Structures,Unions,BitManipulationsandEnumerations:SolutionsChapter1010.20Whatdoesthefollowingprogramdo?1/*ex10_20.c*/2#include34intmystery(unsignedbits);/*prototype*/56intmain()7{8unsignedx;/*xwillholdanintegerenteredbytheuser*/910printf("Enteraninteger:");11scanf("%u",&x);1213printf("Theresultis%dn",mystery(x));1415return0;/*indicatessuccessfultermination*/16}/*endmain*/1718/*Whatdoesthisfunctiondo?*/19intmystery(unsignedbits)20{21unsignedi;/*counter*/22unsignedmask=1<<31;/*initializemask*/23unsignedtotal=0;/*initializetotal*/2425for(i=1;i<=32;i++,bits<<=1){2627if((bits&mask)==mask){28total++;29}/*endif*/3031}/*endfor*/3233return!(total%2)?1:0;34}/*endfunctionmystery*/ANS:Enteraninteger:5678Theresultis0Enteraninteger:65Theresultis1©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com11CFileProcessing:SolutionsSOLUTIONS11.5Fillintheblanksineachofthefollowing:a)Computersstorelargeamountsofdataonsecondarystoragedevicesas.ANS:files.b)A(n)iscomposedofseveralfields.ANS:record.c)Afieldthatmaycontaindigits,lettersandblanksiscalleda(n)field.ANS:alphanumeric.d)Tofacilitatetheretrievalofspecificrecordsfromafile,onefieldineachrecordischosenasa(n).ANS:key.e)Thevastmajorityofinformationstoredincomputersystemsisstoredinfiles.ANS:sequentialf)Agroupofrelatedcharactersthatconveysmeaningiscalleda(n).ANS:field.g)Thefilepointersforthethreefilesthatareopenedautomaticallywhenprogramexecutionbeginsarenamed,and.ANS:stdin,stdout,stderr.h)Functionwritesacharactertoaspecifiedfile.ANS:fputc.i)Functionwritesalinetoaspecifiedfile.ANS:fputs.j)Functionisgenerallyusedtowritedatatoarandom-accessfile.ANS:fwrite.k)Functionrepositionsthefilepositionpointertothebeginningofthefile.ANS:rewind.11.6Statewhichofthefollowingaretrueandwhicharefalse.Iffalse,explainwhy.a)Theimpressivefunctionsperformedbycomputersessentiallyinvolvethemanipulationofzerosandones.ANS:True.b)Peopleprefertomanipulatebitsinsteadofcharactersandfieldsbecausebitsaremorecompact.ANS:False.Peopleprefertomanipulatecharactersandfieldsbecausetheyarelesscumbersomeandmoreunderstandable.c)Peoplespecifyprogramsanddataitemsascharacters;computersthenmanipulateandprocessthesecharactersasgroupsofzerosandones.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com354CFileProcessing:SolutionsChapter11ANS:True.d)Aperson’szipcodeisanexampleofanumericfield.ANS:True.e)Aperson’sstreetaddressisgenerallyconsideredtobeanalphabeticfieldincomputerapplications.ANS:False.Astreetaddressisgenerallyconsideredtobealphanumeric.f)Dataitemsprocessedbyacomputerformadatahierarchyinwhichdataitemsbecomelargerandmorecomplexasweprogressfromfieldstocharacterstobitsetc.ANS:Dataitemsprocessbyacomputerformadatahierarchyinwhichdataitemsbecomelargerandmorecomplexasweprogressfrombitstocharacterstofields,etc.g)Arecordkeyidentifiesarecordasbelongingtoaparticularfield.ANS:False.Arecordkeyidentifiesarecordasbelongingtoaparticularpersonorentity.h)Mostorganizationsstorealltheirinformationinasinglefiletofacilitatecomputerprocessing.ANS:False.Mostorganizationshavemanyfilesinwhichtheystoretheirinformation.i)FilesarealwaysreferredtobynameinCprograms.ANS:False.Apointertoeachfileisusedtorefertothefile.j)Whenaprogramcreatesafile,thefileisautomaticallyretainedbythecomputerforfuturereference.ANS:True.11.7Exercise11.3askedthereadertowriteaseriesofsinglestatements.Actually,thesestatementsformthecoreofanimportanttypeoffile-processingprogram,namely,afile-matchingprogram.Incommercialdataprocessing,itiscommontohaveseveralfilesineachsystem.Inanaccountsreceivablesystem,forexample,thereisgenerallyamasterfilecontainingdetailedinformationabouteachcustomersuchasthecustomer’sname,address,telephonenumber,outstandingbalance,creditlimit,discountterms,contractarrangementsandpossiblyacondensedhistoryofrecentpurchasesandcashpayments.Astransactionsoccur(i.e.,salesaremadeandcashpaymentsarriveinthemail),theyareenteredintoafile.Attheendofeachbusinessperiod(i.e.,amonthforsomecompanies,aweekforothersandadayinsomecases)thefileoftransactions(called"trans.dat"inExercise11.3)isappliedtothemasterfile(called"oldmast.dat"inExercise11.3),thusupdatingeachaccount"srecordofpurchasesandpayments.Aftereachoftheseupdatingsrun,themasterfileisrewrittenasanewfile("new-mast.dat"),whichisthenusedattheendofthenextbusinessperiodtobegintheupdatingprocessagain.File-matchingprogramsmustdealwithcertainproblemsthatdonotexistinsingle-fileprograms.Forexample,amatchdoesnotalwaysoccur.Acustomeronthemasterfilemightnothavemadeanypurchasesorcashpaymentsinthecurrentbusinessperiod,andthereforenorecordforthiscustomerwillappearonthetransactionfile.Similarly,acustomerwhodidmakesomepur-chasesorcashpaymentsmighthavejustmovedtothiscommunity,andthecompanymaynothavehadachancetocreateamasterrecordforthiscustomer.UsethestatementswritteninExercise11.3asabasisforwritingacompletefile-matchingaccountsreceivableprogram.Usetheaccountnumberoneachfileastherecordkeyformatchingpurposes.Assumethateachfileisasequentialfilewithrecordsstoredinincreasingaccountnumberorder.Whenamatchoccurs(i.e.,recordswiththesameaccountnumberappearonboththemasterfileandthetransactionfile),addthedollaramountonthetransactionfiletothecurrentbalanceonthemasterfileandwritethe"newmast.dat"record.(Assumethatpurchasesareindicatedbypositiveamountsonthetransactionfile,andthatpaymentsareindicatedbynegativeamounts.)Whenthereisamasterrecordforaparticularaccountbutnocorrespondingtransactionrecord,merelywritethemasterrecordto"newmast.dat".Whenthereisatransactionrecordbutnocorrespondingmasterrecord,printthemessage"Unmatchedtrans-actionrecordforaccountnumber…"(fillintheaccountnumberfromthetransactionrecord).ANS:1/*Exercise11.7Solution*/2/*NOTE:Thisprogramwasrunusingthe*/3/*datainExercise11.8*/4#include5#include67intmain()8{9intmasterAccount;/*accountfromoldmasterfile*/10inttransactionAccount;/*accountfromtransactionsfile*/11doublemasterBalance;/*balancefromoldmasterfile*/12doubletransactionBalance;/*balancefromtransactionsfile*/13charmasterName[30];/*namefrommasterfile*/14FILE*ofPtr;/*oldmasterfilepointer*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter11CFileProcessing:Solutions35515FILE*tfPtr;/*transactionsfilepointer*/16FILE*nfPtr;/*newmasterfilepointer*/1718/*terminateapplicationifoldmasterfilecannotbeopened*/19if((ofPtr=fopen("oldmast.dat","r"))==NULL){20printf("Unabletoopenoldmast.datn");21exit(1);22}/*endif*/2324/*terminateapplicationiftransactionsfilecannotbeopened*/25if((tfPtr=fopen("trans.dat","r"))==NULL){26printf("Unabletoopentrans.datn");27exit(1);28}/*endif*/2930/*terminateapplicationifnewmasterfilecannotbeopened*/31if((nfPtr=fopen("newmast.dat","w"))==NULL){32printf("Unabletoopennewmast.datn");33exit(1);34}/*endif*/3536/*displayaccountcurrentlybeingprocessed*/37printf("Processing....n");38fscanf(tfPtr,"%d%lf",&transactionAccount,&transactionBalance);3940/*whilenottheendoftransactionsfile*/41while(!feof(tfPtr)){4243/*readnextrecordfromoldmasterfile*/44fscanf(ofPtr,"%d%[^0-9-]%lf",&masterAccount,masterName,45&masterBalance);4647/*displayaccountsfrommasterfileuntilnumberof48newaccountisreached*/49while(masterAccounttransactionAccount){73printf("Unmatchedtransactionrecordforaccount%dn",74transactionAccount);75fprintf(nfPtr,"%d%s%.2fn",masterAccount,masterName,76masterBalance);77printf("%d%s%.2fn",masterAccount,masterName,78masterBalance);79}/*endelseif*/80else{81printf("Unmatchedtransactionrecordforaccount%dn",82transactionAccount);83}/*endelse*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com356CFileProcessing:SolutionsChapter118485/*getnextaccountandbalancefromtransactionsfile*/86fscanf(tfPtr,"%d%lf",&transactionAccount,&transactionBalance);87}/*endwhile*/8889/*loopthroughfileanddisplayaccountnumber,nameandbalance*/90while(!feof(ofPtr)){91fscanf(ofPtr,"%d%[^0-9-]%lf",&masterAccount,masterName,92&masterBalance);93fprintf(nfPtr,"%d%s%.2f",masterAccount,masterName,94masterBalance);95printf("%d%s%.2f",masterAccount,masterName,masterBalance);96}/*endwhile*/9798fclose(ofPtr);/*closeallfilepointers*/99fclose(tfPtr);100fclose(nfPtr);101102return0;/*indicatesuccessfultermination*/103104}/*endmain*/Processing....100AlanJones375.31300MarySmith89.30Unmatchedtransactionrecordforaccount400500SamSharp0.00700SuzyGreen-14.22Unmatchedtransactionrecordforaccount90011.8AfterwritingtheprogramofExercise11.7,writeasimpleprogramtocreatesometestdataforcheckingouttheprogramofExercise11.7.Usethefollowingsampleaccountdata:MasterFile:AccountnumberNameBalance100AlanJones348.17300MarySmith27.19500SamSharp0.00700SuzyGreen-14.22TransactionFile:AccountnumberDollaramount10027.1430062.11400100.5690082.17ANS:1/*Exercise11.8Solution*/2#include34intmain()5{6intaccount;/*accountnumber*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter11CFileProcessing:Solutions3577charname[30];/*accountname*/8doublebalance;/*accountbalance*/9doubleamount;/*transactionamount*/10FILE*ofPtr;/*oldmasterfilepointer*/11FILE*tfPtr;/*transactionfilepointer*/1213/*openbothfilesforwriting*/14ofPtr=fopen("oldmast.dat","w");15tfPtr=fopen("trans.dat","w");1617/*promptuserforsampledata*/18printf("Sampledataforfileoldmast.dat:n");19printf("Enteraccount,name,andbalance(EOFtoend):");2021/*loopwhileEOFcharacternotenteredbyuser*/22while(scanf("%d%[^0-9-]%lf",&account,name,23&balance)!=EOF){2425/*writedatatooldmasterfile*/26fprintf(ofPtr,"%d%s%.2fn",account,name,balance);27printf("Enteraccount,name,andbalance(EOFtoend):");28}/*endwhile*/2930fclose(ofPtr);/*closefilepointer*/3132/*promptuserforsampledata*/33printf("nSampledataforfiletrans.dat:n");34printf("Enteraccountandtransactionamount(EOFtoend):");3536/*loopwhileEOFcharacternotenteredbyuser*/37while(scanf("%d%lf",&account,&amount)!=EOF){3839/*writedatatotransactionsfile*/40fprintf(tfPtr,"%d%.2fn",account,amount);41printf("Enteraccountandtransactionamount(EOFtoend):");42}/*endwhile*/4344fclose(tfPtr);/*closefilepointer*/4546return0;/*indicatesuccessfultermination*/4748}/*endmain*/Sampledataforfileoldmast.dat:Enteraccount,name,andbalance(EOFtoend):100AlanJones348.17Enteraccount,name,andbalance(EOFtoend):300MarySmith27.19Enteraccount,name,andbalance(EOFtoend):500SamSharp0.00Enteraccount,name,andbalance(EOFtoend):700SuzyGreen-14.22Enteraccount,name,andbalance(EOFtoend):^ZSampledataforfiletrans.dat:Enteraccountandtransactionamount(EOFtoend):10027.14Enteraccountandtransactionamount(EOFtoend):30062.11Enteraccountandtransactionamount(EOFtoend):400100.56Enteraccountandtransactionamount(EOFtoend):90082.17Enteraccountandtransactionamount(EOFtoend):^Z©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com358CFileProcessing:SolutionsChapter1111.9RuntheprogramofExercise11.7usingthefilesoftestdatacreatedinExercise11.8.UsethelistingprogramofSection11.7toprintthenewmasterfile.Checktheresultscarefully.11.10Itispossible(actuallycommon)tohaveseveraltransactionrecordswiththesamerecordkey.Thisoccursbecauseapar-ticularcustomermightmakeseveralpurchasesandcashpaymentsduringabusinessperiod.Rewriteyouraccountsreceivablefile-matchingprogramofExercise11.7toprovideforthepossibilityofhandlingseveraltransactionrecordswiththesamerecordkey.ModifythetestdataofExercise11.8toincludethefollowingadditionaltransactionrecords:AccountnumberDollaramount30083.8970080.787001.53ANS:1/*Exercise11.10Solution*/2#include3#include45intmain()6{7intmasterAccount;/*accountfromoldmasterfile*/8inttransactionAccount;/*accountfromtransactionsfile*/9doublemasterBalance;/*balancefromoldmasterfile*/10doubletransactionBalance;/*balancefromtransactionsfile*/11charmasterName[30];/*namefrommasterfile*/12FILE*ofPtr;/*oldmasterfilepointer*/13FILE*tfPtr;/*transactionsfilepointer*/14FILE*nfPtr;/*newmasterfilepointer*/1516/*terminateapplicationifoldmasterfilecannotbeopened*/17if((ofPtr=fopen("oldmast.dat","r"))==NULL){18printf("Unabletoopenoldmast.datn");19exit(1);20}/*endif*/2122/*terminateapplicationiftransactionsfilecannotbeopened*/23if((tfPtr=fopen("trans.dat","r"))==NULL){24printf("Unabletoopentrans.datn");25exit(1);26}/*endif*/2728/*terminateapplicationifnewmasterfilecannotbeopened*/29if((nfPtr=fopen("newmast.dat","w"))==NULL){30printf("Unabletoopennewmast.datn");31exit(1);32}/*endif*/3334/*displayaccountcurrentlybeingprocessed*/35printf("Processing....n");36fscanf(tfPtr,"%d%lf",&transactionAccount,&transactionBalance);3738/*whilenottheendoftransactionsfile*/39while(!feof(tfPtr)){4041/*readnextrecordfromoldmasterfile*/42fscanf(ofPtr,"%d%[^0-9-]%lf",&masterAccount,masterName,43&masterBalance);4445/*displayaccountsfrommasterfileuntilnumberof46newaccountisreached*/47while(masterAccounttransactionAccount){80printf("Unmatchedtransactionrecordforaccount%dn",81transactionAccount);82fprintf(nfPtr,"%d%s%.2fn",masterAccount,masterName,masterBalance);83printf("%d%s%.2fn",masterAccount,masterName,masterBalance);84fscanf(tfPtr,"%d%lf",&transactionAccount,&transactionBalance);85}/*endelseif*/86else{87printf("Unmatchedtransactionrecordforaccount%dn",88transactionAccount);89fscanf(tfPtr,"%d%lf",&transactionAccount,&transactionBalance);90}/*endelse*/9192}/*endwhile*/9394/*loopthroughfileanddisplayaccountnumber,nameandbalance*/95while(!feof(ofPtr)){96fscanf(ofPtr,"%d%[^0-9-]%lf",&masterAccount,masterName,97&masterBalance);98fprintf(nfPtr,"%d%s%.2f",masterAccount,masterName,99masterBalance);100printf("%d%s%.2f",masterAccount,masterName,masterBalance);101}/*endwhile*/102103fclose(ofPtr);/*closeallfilepointers*/104fclose(tfPtr);105fclose(nfPtr);106107return0;/*indicatesuccessfultermination*/108109}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com360CFileProcessing:SolutionsChapter11Processing....100AlanJones375.31300MarySmith173.19Unmatchedtransactionrecordforaccount400500SamSharp0.00700SuzyGreen68.09Unmatchedtransactionrecordforaccount90011.11Writestatementsthataccomplisheachofthefollowing.Assumethatthestructurestructperson{charlastName[15];charfirstName[15];charage[4];};hasbeendefinedandthatthefileisalreadyopenforwriting.a)Initializethefile"nameage.dat"sothatthereare100recordswithlastName="unassigned",firstname=""andage="0".b)Input10lastnames,firstnamesandages,andwritethemtothefile.c)Updatearecord;ifthereisnoinformationintherecord,telltheuser"Noinfo".d)Deletearecordthathasinformationbyreinitializingthatparticularrecord.11.12Youaretheownerofahardwarestoreandneedtokeepaninventorythatcantellyouwhattoolsyouhave,howmanyyouhaveandthecostofeachone.Writeaprogramthatinitializesthefile"hardware.dat"to100emptyrecords,letsyouinputthedataconcerningeachtool,enablesyoutolistallyourtools,letsyoudeletearecordforatoolthatyounolongerhaveandletsyouupdateanyinformationinthefile.Thetoolidentificationnumbershouldbetherecordnumber.Usethefollowinginformationtostartyourfile:Record#ToolnameQuantityCost3Electricsander757.9817Hammer7611.9924Jigsaw2111.0039Lawnmower379.5056Powersaw1899.9968Screwdriver1066.9977Sledgehammer1121.5083Wrench347.5011.13TelephoneNumberWordGenerator.Standardtelephonekeypadscontainthedigits0through9.Thenumbers2through9eachhavethreelettersassociatedwiththem,asisindicatedbythefollowingtable:DigitLetter2ABC3DEF4GHI5JKL6MNO7PRS8TUV9WXY©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter11CFileProcessing:Solutions361Manypeoplefinditdifficulttomemorizephonenumbers,sotheyusethecorrespondencebetweendigitsandletterstodevelopseven-letterwordsthatcorrespondtotheirphonenumbers.Forexample,apersonwhosetelephonenumberis686-2377mightusethecorrespondenceindicatedintheabovetabletodeveloptheseven-letterword“NUMBERS.”Businessesfrequentlyattempttogettelephonenumbersthatareeasyfortheirclientstoremember.Ifabusinesscanadvertiseasimplewordforitscustomerstodial,thennodoubtthebusinesswillreceiveafewmorecalls.Eachseven-letterwordcorrespondstoexactlyoneseven-digittelephonenumber.Therestaurantwishingtoincreaseitstake-homebusinesscouldsurelydosowiththenumber825-3688(i.e.,“TAKEOUT”).Eachseven-digitphonenumbercorrespondstomanyseparateseven-letterwords.Unfortunately,mostoftheserepresentunrecognizablejuxtapositionsofletters.Itispossible,however,thattheownerofabarbershopwouldbepleasedtoknowthattheshop’stelephonenumber,424-7288,correspondsto“HAIRCUT.”Theownerofaliquorstorewould,nodoubt,bedelightedtofindthatthestore’stelephonenumber,233-7226,correspondsto“BEERCAN.”Aveterinarianwiththephonenumber738-2273wouldbepleasedtoknowthatthenumbercorrespondstotheletters“PETCARE.”WriteaCprogramthat,givenaseven-digitnumber,writestoafileeverypossibleseven-letterwordcorrespondingtothatnumber.Thereare2187(3totheseventhpower)suchwords.Avoidphonenumberswiththedigits0and1.ANS:1/*Exercise11.13Solution*/2#include34voidwordGenerator(intnumber[]);/*prototype*/56intmain()7{8intloop;/*loopcounter*/9intphoneNumber[7]={0};/*holdsphonenumber*/1011/*promptusertoenterphonenumber*/12printf("Enteraphonenumberonedigitatatime");13printf("usingthedigits2thru9:n");1415/*loop7timestogetnumber*/16for(loop=0;loop<=6;loop++){17printf("?");18scanf("%d",&phoneNumber[loop]);1920/*testifnumberisbetween0and9*/21while(phoneNumber[loop]<2||phoneNumber[loop]>9){22printf("nInvalidnumberentered.Pleaseenteragain:");23scanf("%d",&phoneNumber[loop]);24}/*endwhile*/2526}/*endfor*/2728wordGenerator(phoneNumber);/*formwordsfromphonenumber*/2930return0;/*indicatesuccessfultermination*/3132}/*endmain*/3334/*functiontoformwordsbasedonphonenumber*/35voidwordGenerator(intnumber[])36{37intloop;/*loopcounter*/38intloop1;/*loopcounterforfirstdigitofphonenumber*/39intloop2;/*loopcounterforseconddigitofphonenumber*/40intloop3;/*loopcounterforthirddigitofphonenumber*/41intloop4;/*loopcounterforfourthdigitofphonenumber*/42intloop5;/*loopcounterforfifthdigitofphonenumber*/43intloop6;/*loopcounterforsixthdigitofphonenumber*/44intloop7;/*loopcounterforseventhdigitofphonenumber*/45FILE*foutPtr;/*outputfilepointer*/46©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com362CFileProcessing:SolutionsChapter1147/*letterscorrespondingtoeachnumber*/48char*phoneLetters[10]={"","","ABC","DEF","GHI","JKL",49"MNO","PRS","TUV","WXY"};5051/*openoutputfile*/52if((foutPtr=fopen("phone.out","w"))==NULL){53printf("Outputfilewasnotopened.n");54}/*endif*/55else{/*printallpossiblecombinations*/5657for(loop1=0;loop1<=2;loop1++){5859for(loop2=0;loop2<=2;loop2++){6061for(loop3=0;loop3<=2;loop3++){6263for(loop4=0;loop4<=2;loop4++){6465for(loop5=0;loop5<=2;loop5++){6667for(loop6=0;loop6<=2;loop6++){6869for(loop7=0;loop7<=2;loop7++){70fprintf(foutPtr,"%c%c%c%c%c%c%cn",71phoneLetters[number[0]][loop1],72phoneLetters[number[1]][loop2],73phoneLetters[number[2]][loop3],74phoneLetters[number[3]][loop4],75phoneLetters[number[4]][loop5],76phoneLetters[number[5]][loop6],77phoneLetters[number[6]][loop7]);78}/*endfor*/7980}/*endfor*/8182}/*endfor*/8384}/*endfor*/8586}/*endfor*/8788}/*endfor*/8990}/*endfor*/9192/*outputphonenumber*/93fprintf(foutPtr,"nPhonenumberis");9495/*loopthroughdigits*/96for(loop=0;loop<=6;loop++){9798/*inserthyphen*/99if(loop==3){100fprintf(foutPtr,"-");101}/*endif*/102103fprintf(foutPtr,"%d",number[loop]);104}/*endfor*/105106}/*endelse*/107108fclose(foutPtr);/*closefilepointer*/109}/*endfunctionwordGenerator©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter11CFileProcessing:Solutions363Enteraphonenumberonedigitatatimeusingthedigits2thru9:?8?4?3?2?6?7?7Thecontentsofphone.outare:TGDAMPPTGDAMPRTGDAMPSTGDAMRPTGDAMRRTGDAMRSTGDAMSPTGDAMSR...VIFCORPVIFCORRVIFCORSVIFCOSPVIFCOSRVIFCOSSPhonenumberis843-267711.14Ifyouhaveacomputerizeddictionaryavailable,modifytheprogramyouwroteinExercise11.13tolookupthewordsinthedictionary.Someseven-lettercombinationscreatedbythisprogramconsistoftwoormorewords(thephonenumber843-2677produces“THEBOSS”).©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com364CFileProcessing:SolutionsChapter1111.15ModifytheexampleofFig.8.14tousefunctionsfgetcandfputsratherthangetcharandputs.Theprogramshouldgivetheusertheoptiontoreadfromthestandardinputandwritetothestandardoutputortoreadfromaspecifiedfileandwritetoaspecifiedfile.Iftheuserchoosesthesecondoption,havetheuserenterthefilenamesfortheinputandoutputfiles.ANS:1/*Exercise11.15Solution*/2#include3#include45intmain()6{7charc;/*currentcharacter*/8charsentence[80];/*textfromuserorinputfile*/9charinput[20];/*inputfile*/10charoutput[20];/*outputfile*/11charchoice[2];/*user"smenuchoice*/12inti=0;/*charactercounter*/13FILE*infilePtr;/*inputfilepointer*/14FILE*outfilePtr;/*outputfilepointer*/1516/*displaychoicestouser*/17printf("%s%sn%sn%s","1Readfromstandardinput;",18"writetostandardoutput","2Readfromafile;writetofile",19"Enterchoice:");20scanf("%s",choice);2122/*whileuserdoesnotenteravalidchoice*/23while(choice[0]!="1"&&choice[0]!="2"){24printf("Invalidchoice.Chooseagain:");25scanf("%s",choice);26}/*endwhile*/2728/*ifuserchoosesoption2*/29if(choice[0]=="2"){30printf("Enterinputfilename:");/*getinputfilename*/31scanf("%s",input);3233printf("Enteroutputfilename:");/*getoutputfilename*/34scanf("%s",output);3536/*exitprogramifunabletoopeninputfile*/37if((infilePtr=fopen(input,"r"))==NULL){38printf("Unabletoopen%sn",input);39exit(1);40}/*endif*/4142/*exitprogramifunabletoopenoutputfile*/43elseif((outfilePtr=fopen(output,"w"))==NULL){44printf("Unabletoopen%sn",output);45fclose(infilePtr);46exit(1);47}/*endif*/4849}/*endif*/50else{/*ifuserchoosesoption1*/51infilePtr=stdin;52outfilePtr=stdout;53}/*endelse*/5455/*ifuserchoosesoption1*/56if(choice[0]=="1"){5758/*promptuserfortext*/59printf("Enteralineoftext:n");60scanf("");/*Eliminatespacesandnewlinesatthe61startoftheinputstream*/62}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter11CFileProcessing:Solutions3656364/*readeachcharacterusingfgetc*/65while((c=fgetc(infilePtr))!="n"&&!feof(infilePtr)){66sentence[i++]=c;67}/*endwhile*/6869/*addterminatingcharacterandoutputtextwithfputs*/70sentence[i]="";71fprintf(outfilePtr,"nThelineenteredwas:n");72fputs(sentence,outfilePtr);7374/*closefilepointers*/75if(choice[0]=="2"){76fclose(infilePtr);77fclose(outfilePtr);78}/*endif*/7980return0;/*indicatesuccessfultermination*/8182}/*endmain*/1Readfromstandardinput;writetostandardoutput2Readfromafile;writetofileEnterchoice:1Enteralineoftext:Thisisatest.Thelineenteredwas:Thisisatest.1Readfromstandardinput;writetostandardoutput2Readfromafile;writetoafileEnterchoice:2Enterinputfilename:test.datEnteroutputfilename:output.datContentsoftest.datThisisatestfileforexercise11.15.Contentsofoutput.datThelineenteredwas:Thisisatestfileforexercise11.15.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com366CFileProcessing:SolutionsChapter1111.16Writeaprogramthatusesthesizeofoperatortodeterminethesizesinbytesofthevariousdatatypesonyourcomputersystem.Writetheresultstothefile"datasize.dat"soyoumayprinttheresultslater.Theformatfortheresultsinthefileshouldbeasfollows:DatatypeSizechar1unsignedchar1shortint2unsignedshortint2int4unsignedint4longint4unsignedlongint4float4double8longdouble16[Note:Thetypesizesonyourcomputermightbedifferentfromthoselistedabove.]ANS:1/*Exercise11.16Solution*/2#include34intmain()56{7FILE*outPtr;/*outputfilepointer*/89/*opendatasize.datforwriting*/10outPtr=fopen("datasize.dat","w");1112/*writesizeofvariousdatatypes*/13fprintf(outPtr,"%s%16sn","Datatype","Size");14fprintf(outPtr,"%s%21dn","char",sizeof(char));15fprintf(outPtr,"%s%12dn","unsignedchar",16sizeof(unsignedchar));17fprintf(outPtr,"%s%16dn","shortint",sizeof(shortint));18fprintf(outPtr,"%s%7dn","unsignedshortint",19sizeof(unsignedshortint));20fprintf(outPtr,"%s%22dn","int",sizeof(int));21fprintf(outPtr,"%s%13dn","unsignedint",22sizeof(unsignedint));23fprintf(outPtr,"%s%17dn","longint",sizeof(longint));24fprintf(outPtr,"%s%8dn","unsignedlongint",25sizeof(unsignedlongint));26fprintf(outPtr,"%s%20dn","float",sizeof(float));27fprintf(outPtr,"%s%19dn","double",sizeof(double));28fprintf(outPtr,"%s%14dn","longdouble",sizeof(longdouble));2930fclose(outPtr);/*closefilepointer*/3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter11CFileProcessing:Solutions367Contentsofdatasize.datDatatypeSizechar1unsignedchar1shortint2unsignedshortint2int4unsignedint4longint4unsignedlongint4float4double8longdouble8©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com368CFileProcessing:SolutionsChapter1111.17InExercise7.19,youwroteasoftwaresimulationofacomputerthatusedaspecialmachinelanguagecalledSimpletronMachineLanguage(SML).Inthesimulation,eachtimeyouwantedtorunanSMLprogram,youenteredtheprogramintothesim-ulatorfromthekeyboard.IfyoumadeamistakewhiletypingtheSMLprogram,thesimulatorwasrestartedandtheSMLcodewasreentered.ItwouldbenicetobeabletoreadtheSMLprogramfromafileratherthantypeiteachtime.ThiswouldreducetimeandmistakesinpreparingtorunSMLprograms.a)ModifythesimulatoryouwroteinExercise7.19toreadSMLprogramsfromafilespecifiedbytheuseratthekeyboard.b)AftertheSimpletronexecutes,itoutputsthecontentsofitsregistersandmemoryonthescreen.Itwouldbenicetocapturetheoutputinafile,somodifythesimulatortowriteitsoutputtoafileinadditiontodisplayingtheoutputonthescreen.ANS:1/*Exercise11.17Solution*/2#include34/*definecommands*/5#defineSIZE1006#defineTRUE17#defineFALSE08#defineREAD109#defineWRITE1110#defineLOAD2011#defineSTORE2112#defineADD3013#defineSUBTRACT3114#defineDIVIDE3215#defineMULTIPLY3316#defineBRANCH4017#defineBRANCHNEG4118#defineBRANCHZERO4219#defineHALT432021/*functionprototype*/22voidload(int*loadMemory);23voidexecute(int*memory,int*acPtr,int*icPtr,int*irPtr,24int*opCodePtr,int*opPtr);25voiddump(int*memory,intaccumulator,intinstructionCounter,26intinstructionRegister,intoperationCode,27intoperand);28intvalidWord(intword);2930intmain()31{32intmemory[SIZE];/*definememoryarray*/33intac=0;/*accumulator*/34intic=0;/*instructioncounter*/35intopCode=0;/*operationcode*/36intop=0;/*operand*/37intir=0;/*instructionregister*/38inti;/*counter*/3940/*clearmemory*/41for(i=0;i=-9999&&word<=9999;321322}/*endfunctionvalidWord*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter11CFileProcessing:Solutions373Enterinputfile:simple.in************STARTSIMPLETRONEXECUTION************Enteraninteger:5Enteraninteger:2Contentsof09:7*************ENDSIMPLETRONEXECUTION*************Enteroutputfilename:simple.outREGISTERS:accumulator+0007instructioncounter06instructionregister+4300operationcode43operand00MEMORY:01234567890+1007+1008+2007+3008+2109+1109+4300+0005+0002+000710+0000+0000+0000+0000+0000+0000+0000+0000+0000+000020+0000+0000+0000+0000+0000+0000+0000+0000+0000+000030+0000+0000+0000+0000+0000+0000+0000+0000+0000+000040+0000+0000+0000+0000+0000+0000+0000+0000+0000+000050+0000+0000+0000+0000+0000+0000+0000+0000+0000+000060+0000+0000+0000+0000+0000+0000+0000+0000+0000+000070+0000+0000+0000+0000+0000+0000+0000+0000+0000+000080+0000+0000+0000+0000+0000+0000+0000+0000+0000+000090+0000+0000+0000+0000+0000+0000+0000+0000+0000+0000Contentsofsimple.in(asimpleadditionprogram)1007100820073008210911094300000000000000©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com374CFileProcessing:SolutionsChapter11©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com12DataStructures:SolutionsSOLUTIONS12.6Writeaprogramthatconcatenatestwolinkedlistsofcharacters.Theprogramshouldincludefunctionconcatenatethattakespointerstobothlistsasargumentsandconcatenatesthesecondlisttothefirstlist.ANS:1/*Exercise12.6Solution*/2#include3#include45/*ListNodestructuredefinition*/6structListNode{7chardata;/*nodedata*/8structListNode*nextPtr;/*pointertonextnode*/9};/*endstructListNode*/1011typedefstructListNodeListNode;12typedefListNode*ListNodePtr;1314/*functionprototypes*/15voidconcatenate(ListNodePtra,ListNodePtrb);16voidinsert(ListNodePtr*sPtr,charvalue);17voidprintList(ListNodePtrcurrentPtr);1819intmain()20{21ListNodePtrlist1Ptr=NULL;/*pointertofirstlist*/22ListNodePtrlist2Ptr=NULL;/*pointertosecondlist*/23chari;/*loopcounter*/2425/*assignlettersfromAtoCintofirstlist*/26for(i="A";i<="C";i++){27insert(&list1Ptr,i);28}/*endfor*/2930printf("List1is:");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com376DataStructures:SolutionsChapter1231printList(list1Ptr);3233/*assignlettersfromDtoFintosecondlist*/34for(i="D";i<="F";i++){35insert(&list2Ptr,i);36}/*endfor*/3738printf("List2is:");39printList(list2Ptr);4041concatenate(list1Ptr,list2Ptr);42printf("Theconcatenatedlistis:");43printList(list1Ptr);4445return0;/*indicatesuccessfultermination*/4647}/*endmain*/4849/*Concatenatetwolists*/50voidconcatenate(ListNodePtra,ListNodePtrb)51{52ListNodePtrcurrentPtr;/*temporarypointer*/5354currentPtr=a;/*setcurrentPtrtofirstlinkedlist*/5556/*whilecurrentPtrdoesnotequalNULL*/57while(currentPtr->nextPtr!=NULL){58currentPtr=currentPtr->nextPtr;59}/*endwhile*/6061currentPtr->nextPtr=b;/*concatenatebothlists*/62}/*endfunctionconcatenate*/6364/*Insertanewvalueintothelistinsortedorder*/65voidinsert(ListNodePtr*sPtr,charvalue)66{67ListNodePtrnewPtr;/*newnode*/68ListNodePtrpreviousPtr;/*previousnode*/69ListNodePtrcurrentPtr;/*currentnode*/7071/*dynamicallyallocatememory*/72newPtr=malloc(sizeof(ListNode));7374/*ifnewPtrdoesnotequalNULL*/75if(newPtr){76newPtr->data=value;77newPtr->nextPtr=NULL;7879previousPtr=NULL;80currentPtr=*sPtr;/*setcurrentPtrtostartoflist*/8182/*looptofindcorrectlocationinlist*/83while(currentPtr!=NULL&&value>currentPtr->data){84previousPtr=currentPtr;85currentPtr=currentPtr->nextPtr;86}/*endwhile*/8788/*insertatbeginningoflist*/89if(previousPtr==NULL){90newPtr->nextPtr=*sPtr;91*sPtr=newPtr;92}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions37793else{/*insertnodebetweenpreviousPtrandcurrentPtr*/94previousPtr->nextPtr=newPtr;95newPtr->nextPtr=currentPtr;96}/*endelse*/9798}/*endif*/99else{100printf("%cnotinserted.Nomemoryavailable.n",value);101}/*endelse*/102103}/*endfunctioninsert*/104105/*Printthelist*/106voidprintList(ListNodePtrcurrentPtr)107{108109/*iflistisempty*/110if(!currentPtr){111printf("Listisempty.nn");112}/*endif*/113else{114115/*loopwhilecurrentPtrdoesnotequalNULL*/116while(currentPtr){117printf("%c",currentPtr->data);118currentPtr=currentPtr->nextPtr;119}/*endwhile*/120121printf("*nn");122}/*endelse*/123124}/*endfunctionprintList*/List1is:ABC*List2is:DEF*Theconcatenatedlistis:ABCDEF*©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com378DataStructures:SolutionsChapter1212.7Writeaprogramthatmergestwoorderedlistsofintegersintoasingleorderedlistofintegers.Functionmergeshouldre-ceivepointerstothefirstnodeofeachoftheliststobemergedandshouldreturnapointertothefirstnodeofthemergedlist.ANS:1/*Exercise12.7Solution*/2#include3#include45/*ListNodestructuredefinition*/6structListNode{7intdata;/*nodedata*/8structListNode*nextPtr;/*pointertonextnode*/9};/*endstructListNode*/1011typedefstructListNodeListNode;12typedefListNode*ListNodePtr;1314/*functionprototype*/15voidinsert(ListNodePtr*sPtr,intvalue);16voidprintList(ListNodePtrcurrentPtr);17ListNodePtrmerge(ListNodePtra,ListNodePtrb);1819intmain()20{21ListNodePtrlist1Ptr=NULL;/*pointertofirstlist*/22ListNodePtrlist2Ptr=NULL;/*pointertosecondlist*/23ListNodePtrlist3Ptr;/*pointertomergedlist*/24inti;/*loopcounter*/2526/*buildfirstlist*/27for(i=2;i<=10;i+=2){28insert(&list1Ptr,i);29}/*endfor*/3031printf("List1is:");32printList(list1Ptr);3334/*buildsecondlist*/35for(i=1;i<=9;i+=2){36insert(&list2Ptr,i);37}/*endfor*/3839printf("List2is:");40printList(list2Ptr);4142/*mergebothlistsandprintresults*/43list3Ptr=merge(list1Ptr,list2Ptr);44printf("Themergedlistis:");45printList(list3Ptr);4647return0;/*indicatesuccessfultermination*/4849}/*endmain*/5051/*Mergetwolistsofintegers*/52ListNodePtrmerge(ListNodePtra,ListNodePtrb)53{54ListNodePtrcurrentPtr1;/*pointertofirstlist*/55ListNodePtrcurrentPtr2;/*pointertosecondlist*/56ListNodePtrc=NULL;/*pointertomergedlist*/57©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions37958currentPtr1=a;/*setcurrentPtr1tofirstlinkedlist*/59currentPtr2=b;/*setcurrentPtr2tosecondlinkedlist*/6061/*whilecurrentPtr1doesnotequalNULL*/62while(currentPtr1!=NULL){6364/*comparecurrentPtr1andcurrentPtr2,insertlessernode*/65if(currentPtr2==NULL||currentPtr1->data<66currentPtr2->data){6768/*insertcurrentPtr1node*/69insert(&c,currentPtr1->data);70currentPtr1=currentPtr1->nextPtr;71}/*endif*/72else{7374/*insertcurrentPtr2node*/75insert(&c,currentPtr2->data);76currentPtr2=currentPtr2->nextPtr;77}/*endelse*/7879}/*endwhile*/8081/*insertanyremainingnodesincurrentPtr2list*/82while(currentPtr2!=NULL){83insert(&c,currentPtr2->data);84currentPtr2=currentPtr2->nextPtr;85}/*endwhile*/8687returnc;/*returnmergedlist*/8889}/*endfunctionmerge*/9091/*Insertanewvalueintothelistinsortedorder*/92voidinsert(ListNodePtr*sPtr,intvalue)93{94ListNodePtrnewPtr;/*newnode*/95ListNodePtrpreviousPtr;/*previousnode*/96ListNodePtrcurrentPtr;/*currentnode*/9798/*dynamicallyallocatememory*/99newPtr=malloc(sizeof(ListNode));100101/*ifnewPtrdoesnotequalNULL*/102if(newPtr){103newPtr->data=value;104newPtr->nextPtr=NULL;105106previousPtr=NULL;107currentPtr=*sPtr;/*setcurrentPtrtostartoflist*/108109/*looptofindcorrectlocationinlist*/110while(currentPtr!=NULL&&value>currentPtr->data){111previousPtr=currentPtr;112currentPtr=currentPtr->nextPtr;113}/*endwhile*/114115/*insertatbeginningoflist*/116if(previousPtr==NULL){117newPtr->nextPtr=*sPtr;118*sPtr=newPtr;119}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com380DataStructures:SolutionsChapter12120else{/*insertnodebetweenpreviousPtrandcurrentPtr*/121previousPtr->nextPtr=newPtr;122newPtr->nextPtr=currentPtr;123}/*endelse*/124125}/*endif*/126else{127printf("%cnotinserted.Nomemoryavailable.n",value);128}/*endelse*/129130}/*endfunctioninsert*/131132/*Printthelist*/133voidprintList(ListNodePtrcurrentPtr)134{135136/*iflistisempty*/137if(!currentPtr){138printf("Listisempty.nn");139}/*endif*/140else{141142/*loopwhilecurrentPtrdoesnotequalNULL*/143while(currentPtr){144printf("%d",currentPtr->data);145currentPtr=currentPtr->nextPtr;146}/*endwhile*/147148printf("*nn");149}/*endelse*/150151}/*endfunctionprintList*/List1is:246810*List2is:13579*Themergedlistis:12345678910*©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions38112.8Writeaprogramthatinserts25randomintegersfrom0to100inorderinalinkedlist.Theprogramshouldcalculatethesumoftheelementsandthefloating-pointaverageoftheelements.ANS:.1/*Exercise12.8Solution*/2#include3#include4#include56/*ListNodestructuredefinition*/7typedefstructListNode{8intdata;/*nodedata*/9structListNode*nextPtr;/*pointertonextnode*/10}ListNode;/*endstructListNode*/1112typedefListNode*ListNodePtr;1314/*functionprototypes*/15intsumList(ListNodePtra);16doubleaverageList(ListNodePtra);17voidinsert(ListNodePtr*sPtr,intvalue);18voidprintList(ListNodePtrcurrentPtr);1920intmain()21{22ListNodePtrlistPtr=NULL;/*listpointer*/23inti;/*loopcounter*/2425srand(time(NULL));/*randomize*/2627/*buildlistwithrandomnumbersfrom0to100*/28for(i=1;i<=25;i++){29insert(&listPtr,rand()%101);30}/*endfor*/3132printf("Thelistis:n");33printList(listPtr);3435/*calculateanddisplaythesumandaverageoflistvalues*/36printf("Thesumis%dn",sumList(listPtr));37printf("Theaverageis%fn",averageList(listPtr));3839return0;/*indicatesuccessfultermination*/4041}/*endmain*/4243/*Sumtheintegersinalist*/44intsumList(ListNodePtra)45{46ListNodePtrcurrentPtr;/*temporarypointertolista*/47inttotal=0;/*sumofnodevalues*/4849currentPtr=a;/*setcurrentPtrtolista*/5051/*loopthroughlist*/52while(currentPtr!=NULL){5354/*addnodevaluetototal*/55total+=currentPtr->data;56currentPtr=currentPtr->nextPtr;57}/*endwhile*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com382DataStructures:SolutionsChapter125859returntotal;6061}/*endfunctionsumList*/6263/*Averagetheintegersinalist*/64doubleaverageList(ListNodePtra)65{66ListNodePtrcurrentPtr;/*temporarypointertolista*/67doubletotal=0.0;/*sumofnodevalues*/68intcount=0;/*numberofnodesinlist*/6970currentPtr=a;/*setcurrentPtrtolista*/7172/*loopthroughlist*/73while(currentPtr!=NULL){74++count;/*incrementcount*/75total+=currentPtr->data;/*updatetotal*/76currentPtr=currentPtr->nextPtr;77}/*endwhile*/7879returntotal/count;/*returnaverage*/8081}/*endfunctionaverageList*/8283/*Insertanewvalueintothelistinsortedorder*/84voidinsert(ListNodePtr*sPtr,intvalue)85{86ListNodePtrnewPtr;/*newnode*/87ListNodePtrpreviousPtr;/*previousnode*/88ListNodePtrcurrentPtr;/*currentnode*/8990/*dynamicallyallocatememory*/91newPtr=malloc(sizeof(ListNode));9293/*ifnewPtrdoesnotequalNULL*/94if(newPtr){95newPtr->data=value;96newPtr->nextPtr=NULL;9798previousPtr=NULL;99currentPtr=*sPtr;/*setcurrentPtrtostartoflist*/100101/*looptofindcorrectlocationinlist*/102while(currentPtr!=NULL&&value>currentPtr->data){103previousPtr=currentPtr;104currentPtr=currentPtr->nextPtr;105}/*endwhile*/106107/*insertatbeginningoflist*/108if(previousPtr==NULL){109newPtr->nextPtr=*sPtr;110*sPtr=newPtr;111}/*endif*/112else{/*insertnodebetweenpreviousPtrandcurrentPtr*/113previousPtr->nextPtr=newPtr;114newPtr->nextPtr=currentPtr;115}/*endelse*/116117}/*endif*/118else{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions383119printf("%cnotinserted.Nomemoryavailable.n",value);120}/*endelse*/121122}/*endfunctioninsert*/123124/*Printthelist*/125voidprintList(ListNodePtrcurrentPtr)126{127128/*iflistisempty*/129if(!currentPtr){130printf("Listisempty.nn");131}/*endif*/132else{133134/*loopwhilecurrentPtrdoesnotequalNULL*/135while(currentPtr){136printf("%d",currentPtr->data);137currentPtr=currentPtr->nextPtr;138}/*endwhile*/139140printf("*nn");141}/*endelse*/142143}/*endfunctionprintList*/Thelistis:6121420273131343738565963667273737677798894959697*Thesumis1414Theaverageis56.560000©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com384DataStructures:SolutionsChapter1212.9Writeaprogramthatcreatesalinkedlistof10characters,thencreatesacopyofthelistinreverseorder.ANS:1/*Exercise12.9Solution*/2#include3#include45/*ListNodestructuredefinition*/6structListNode{7chardata;/*nodedata*/8structListNode*nextPtr;/*pointertonextnode*/9};/*endstructListNode*/1011typedefstructListNodeListNode;12typedefListNode*ListNodePtr;1314/*functionprototypes*/15ListNodePtrreverseList(ListNodePtrcurrentPtr);16voidinsert(ListNodePtr*sPtr,charvalue);17voidprintList(ListNodePtrcurrentPtr);18voidpush(ListNodePtr*topPtr,charinfo);1920intmain()21{22ListNodePtrlistPtr=NULL;/*listpointer*/23chari;/*loopcounter*/2425/*buildlistwithcharactersAtoJ*/26for(i="A";i<="J";i++){27insert(&listPtr,i);28}/*endfor*/2930printf("Thelistis:n");31printList(listPtr);3233/*reversethelistanddisplayresult*/34printf("Thelistinreverseis:n");35printList(reverseList(listPtr));3637return0;/*indicatesuccessfultermination*/3839}/*endmain*/4041/*Createalistinthereverseorderofthelistargument*/42ListNodePtrreverseList(ListNodePtrcurrentPtr)43{44ListNodePtrstack=NULL;/*pointertoreversedlist*/4546/*loopthroughlistcurrentPtr*/47while(currentPtr!=NULL){4849/*pushcurrentelementontostack*/50push(&stack,currentPtr->data);51currentPtr=currentPtr->nextPtr;52}/*endwhile*/5354returnstack;/*returnreversedlist*/5556}/*endfunctionreverseList*/57©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions38558/*Insertanewvalueintothelistinsortedorder*/59voidinsert(ListNodePtr*sPtr,charvalue)60{61ListNodePtrnewPtr;/*newnode*/62ListNodePtrpreviousPtr;/*previousnode*/63ListNodePtrcurrentPtr;/*currentnode*/6465/*dynamicallyallocatememory*/66newPtr=malloc(sizeof(ListNode));6768/*ifnewPtrdoesnotequalNULL*/69if(newPtr){70newPtr->data=value;71newPtr->nextPtr=NULL;7273previousPtr=NULL;74currentPtr=*sPtr;/*setcurrentPtrtostartoflist*/7576/*looptofindcorrectlocationinlist*/77while(currentPtr!=NULL&&value>currentPtr->data){78previousPtr=currentPtr;79currentPtr=currentPtr->nextPtr;80}/*endwhile*/8182/*insertatbeginningoflist*/83if(previousPtr==NULL){84newPtr->nextPtr=*sPtr;85*sPtr=newPtr;86}/*endif*/87else{/*insertnodebetweenpreviousPtrandcurrentPtr*/88previousPtr->nextPtr=newPtr;89newPtr->nextPtr=currentPtr;90}/*endelse*/9192}/*endif*/93else{94printf("%cnotinserted.Nomemoryavailable.n",value);95}/*endelse*/9697}/*endfunctioninsert*/9899/*Insertanodeatthestacktop*/100voidpush(ListNodePtr*topPtr,charinfo)101{102ListNodePtrnewPtr;/*temporarynodepointer*/103104/*dynamicallyallocatememory*/105newPtr=malloc(sizeof(ListNode));106107/*ifmemorywasallocated,insertnodeattopoflist*/108if(newPtr){109newPtr->data=info;110newPtr->nextPtr=*topPtr;111*topPtr=newPtr;112}/*endif*/113else{114printf("%cnotinserted.Nomemoryavailable.n",info);115}/*endelse*/116117}/*endfunctionpush*/118©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com386DataStructures:SolutionsChapter12119/*Printthelist*/120voidprintList(ListNodePtrcurrentPtr)121{122123/*iflistisempty*/124if(!currentPtr){125printf("Listisempty.nn");126}/*endif*/127else{128129/*loopwhilecurrentPtrdoesnotequalNULL*/130while(currentPtr){131printf("%c",currentPtr->data);132currentPtr=currentPtr->nextPtr;133}/*endwhile*/134135printf("*nn");136}/*endelse*/137138}/*endfunctionprintList*/Thelistis:ABCDEFGHIJ*Thelistinreverseis:JIHGFEDCBA*©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions38712.10Writeaprogramthatinputsalineoftextandusesastacktoprintthelinereversed.ANS:1/*Exercise12.10Solution*/2#include3#include45/*stackNodestructuredefinition*/6structstackNode{7chardata;/*nodedata*/8structstackNode*nextPtr;/*pointertonextnode*/9};/*endstructstackNode*/1011typedefstructstackNodeStackNode;12typedefStackNode*StackNodePtr;1314/*functionprototypes*/15voidpush(StackNodePtr*topPtr,charinfo);16charpop(StackNodePtr*topPtr);17intisEmpty(StackNodePtrtopPtr);1819intmain()20{21StackNodePtrstackPtr=NULL;/*pointstothestacktop*/22charc;/*currentcharacterfromtext*/2324printf("Enteralineoftext:n");2526/*readeachletterwithgetcharandpushonstack*/27while((c=getchar())!="n"){28push(&stackPtr,c);29}/*endwhile*/3031printf("nThelineisreverseis:n");3233/*whilethestackisnotempty,popnextcharacter*/34while(!isEmpty(stackPtr)){35printf("%c",pop(&stackPtr));36}/*endwhile*/3738return0;/*indicatesuccessfultermination*/3940}/*endmain*/4142/*Insertanodeatthestacktop*/43voidpush(StackNodePtr*topPtr,charinfo)44{45StackNodePtrnewPtr;/*temporarynodepointer*/4647/*dynamicallyallocatememory*/48newPtr=malloc(sizeof(StackNode));4950/*ifmemorywasallocated,insertnodeattopofstack*/51if(newPtr){52newPtr->data=info;53newPtr->nextPtr=*topPtr;54*topPtr=newPtr;55}/*endif*/56else{57printf("%dnotinserted.Nomemoryavailable.n",info);58}/*endelse*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com388DataStructures:SolutionsChapter125960}/*endfunctionpush*/6162/*Removeanodefromthestacktop*/63charpop(StackNodePtr*topPtr)64{65StackNodePtrtempPtr;/*temporarynodepointer*/66intpopValue;/*valueofpoppednode*/6768tempPtr=*topPtr;69popValue=(*topPtr)->data;70*topPtr=(*topPtr)->nextPtr;/*resettopPtr*/71free(tempPtr);/*freememory*/7273returnpopValue;/*returnvalueofpoppednode*/7475}/*endfunctionpop*/7677/*Isthestackempty?*/78intisEmpty(StackNodePtrtopPtr)79{80return!topPtr;/*returnNULLifstackisempty*/8182}/*endfunctionisEmpty*/Enteralineoftext:thisisalineoftextThelineisreverseis:txetfoenilasisiht©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions38912.11Writeaprogramthatusesastacktodetermineifastringisapalindrome(i.e.,thestringisspelledidenticallybackwardandforward).Theprogramshouldignorespacesandpunctuation.ANS:1/*Exercise12.11Solution*/2#include3#include4#include56#defineYES17#defineNO089/*stackNodestructuredefinition*/10structstackNode{11chardata;/*nodedata*/12structstackNode*nextPtr;/*pointertonextnode*/13};/*endstructstackNode*/1415typedefstructstackNodeSTACKNODE;16typedefSTACKNODE*STACKNODEPTR;1718/*functionprototypes*/19voidpush(STACKNODEPTR*topPtr,charinfo);20charpop(STACKNODEPTR*topPtr);21intisEmpty(STACKNODEPTRtopPtr);2223intmain()24{25STACKNODEPTRstackPtr=NULL;/*pointstothestacktop*/26charc;/*currentcharacterfromtext*/27charline[50];/*textfromuser*/28charcondensedLine[50];/*textwithonlyletters*/29inti=0;/*lengthofcondensedline*/30intj=0;/*lengthofline*/31intpalindrome=YES;/*resultofpalindrometest*/3233printf("Enteralineoftext:n");3435/*readeachletterwithgetcharandaddtoline*/36while((c=getchar())!="n"){37line[j++]=c;3839/*removeallspacesandpunctuation*/40if(isalpha(c)){41condensedLine[i++]=tolower(c);42push(&stackPtr,tolower(c));43}/*endif*/4445}/*endwhile*/4647line[j]="";4849/*loopthroughcondensedLine*/50for(j=0;jdata=info;83newPtr->nextPtr=*topPtr;84*topPtr=newPtr;85}/*endif*/86else{87printf("%dnotinserted.Nomemoryavailable.n",info);88}/*endelse*/8990}/*endfunctionpush*/9192/*Removeanodefromthestacktop*/93charpop(STACKNODEPTR*topPtr)94{95STACKNODEPTRtempPtr;/*temporarynodepointer*/96intpopValue;/*valueofpoppednode*/9798tempPtr=*topPtr;99popValue=(*topPtr)->data;100*topPtr=(*topPtr)->nextPtr;/*resettopPtr*/101free(tempPtr);/*freememory*/102103returnpopValue;/*returnvalueofpoppednode*/104105}/*endfunctionpop*/106107/*Isthestackempty?*/108intisEmpty(STACKNODEPTRtopPtr)109{110return!topPtr;/*returnNULLifstackisempty*/111112}/*endfunctionisEmpty*/Enteralineoftext:ablewasiereisawelba"ablewasiereisawelba"isapalindrome©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions391Enteralineoftext:thisisnotapalindrome"thisisnotapalindrome"isnotapalindrome©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com392DataStructures:SolutionsChapter1212.12Stacksareusedbycompilerstohelpintheprocessofevaluatingexpressionsandgeneratingmachinelanguagecode.Inthisandthenextexercise,weinvestigatehowcompilersevaluatearithmeticexpressionsconsistingonlyofconstants,operatorsandparentheses.Humansgenerallywriteexpressionslike3+4and7/9inwhichtheoperator(+or/here)iswrittenbetweenitsoperands—thisiscalledinfixnotation.Computers“prefer”postfixnotationinwhichtheoperatoriswrittentotherightofitstwooperands.Theprecedinginfixexpressionswouldappearinpostfixnotationas34+and79/,respectively.Toevaluateacomplexinfixexpression,acompilerwouldfirstconverttheexpressiontopostfixnotation,andthenevaluatethepostfixversionoftheexpression.Eachofthesealgorithmsrequiresonlyasingleleft-to-rightpassoftheexpression.Eachalgo-rithmusesastackinsupportofitsoperation,andineachthestackisusedforadifferentpurpose.Inthisexercise,youwillwriteaversionoftheinfix-to-postfixconversionalgorithm.Inthenextexercise,youwillwriteaver-sionofthepostfixexpressionevaluationalgorithm.Writeaprogramthatconvertsanordinaryinfixarithmeticexpression(assumeavalidexpressionisentered)withsingledigitintegerssuchas(6+2)*5-8/4toapostfixexpression.Thepostfixversionoftheprecedinginfixexpressionis62+5*84/-Theprogramshouldreadtheexpressionintocharacterarrayinfix,andusemodifiedversionsofthestackfunctionsimplementedinthischaptertohelpcreatethepostfixexpressionincharacterarraypostfix.Thealgorithmforcreatingapostfixexpressionisasfollows:1)Pushaleftparenthesis"("ontothestack.2)Appendarightparenthesis")"totheendofinfix.3)Whilethestackisnotempty,readinfixfromlefttorightanddothefollowing:Ifthecurrentcharacterininfixisadigit,copyittothenextelementofpostfix.Ifthecurrentcharacterininfixisaleftparenthesis,pushitontothestack.Ifthecurrentcharacterininfixisanoperator,Popoperators(ifthereareany)atthetopofthestackwhiletheyhaveequalorhigherprecedencethanthecurrentoperator,andinsertthepoppedoperatorsinpostfix.Pushthecurrentcharacterininfixontothestack.IfthecurrentcharacterininfixisarightparenthesisPopoperatorsfromthetopofthestackandinserttheminpostfixuntilaleftparenthesisisatthetopofthestack.Pop(anddiscard)theleftparenthesisfromthestack.Thefollowingarithmeticoperationsareallowedinanexpression:+addition-subtraction*multiplication/division^exponentiation%remainderThestackshouldbemaintainedwiththefollowingdeclarations:structstackNode{chardata;structstackNode*nextPtr;};typedefstructstackNodeStackNode;typedefStackNode*StackNodePtr;Theprogramshouldconsistofmainandeightotherfunctionswiththefollowingfunctionheaders:voidconvertToPostfix(charinfix[],charpostfix[])©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions393Converttheinfixexpressiontopostfixnotation.intisOperator(charc)Determineifcisanoperator.intprecedence(charoperator1,charoperator2)Determineiftheprecedenceofoperator1islessthan,equalto,orgreaterthantheprecedenceofoperator2.Thefunctionreturns-1,0and1,respectively.voidpush(StackNodePtr*topPtr,charvalue)Pushavalueonthestack.charpop(StackNodePtr*topPtr)Popavalueoffthestack.charstackTop(StackNodePtrtopPtr)Returnthetopvalueofthestackwithoutpoppingthestack.intisEmpty(StackNodePtrtopPtr)Determineifthestackisempty.voidprintStack(StackNodePtrtopPtr)Printthestack.ANS:1/*Exercise12.12Solution*/2/*Infixtopostfixconversion*/3#include4#include5#include6#include78#defineMAXCOLS100910/*stackNodestructuredefinition*/11typedefstructstackNode{12chardata;/*nodedata*/13structstackNode*nextPtr;/*pointertonextnode*/14}STACKNODE;/*endstructstackNode*/1516typedefSTACKNODE*STACKNODEPTR;1718/*functionprototypes*/19voidconvertToPostfix(charinFix[],charpostFix[]);20intisOperator(charc);21intprecedence(charoperator1,charoperator2);22voidpush(STACKNODEPTR*topPtr,charinfo);23charpop(STACKNODEPTR*topPtr);24charstackTop(STACKNODEPTRtopPtr);25intisEmpty(STACKNODEPTRtopPtr);26voidprintStack(STACKNODEPTRcurrentPtr);2728intmain()29{30charc;/*currentcharacterfromexpression*/31charinFix[MAXCOLS];/*expressionininfixnotation*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com394DataStructures:SolutionsChapter1232charpostFix[MAXCOLS];/*expressioninpostfixnotation*/33intpos=0;/*indexingvariable*/3435printf("Entertheinfixexpression.n");3637/*readeachcharacterwithgetchar*/38while((c=getchar())!="n"){3940/*removeanyspaces*/41if(c!=""){42inFix[pos++]=c;43}/*endif*/4445}/*endwhile*/4647inFix[pos]="";4849/*printinfixexpression,converttopostfixandprint*/50printf("%sn%sn","Theoriginalinfixexpressionis:",inFix);51convertToPostfix(inFix,postFix);52printf("Theexpressioninpostfixnotationis:n%sn",postFix);5354return0;/*indicatesuccessfultermination*/5556}/*endmain*/5758/*convertinfixexpressiontopostfixnotation*/59voidconvertToPostfix(charinFix[],charpostFix[])60{61STACKNODEPTRstackPtr=NULL;/*pointstothestacktop*/62inti;/*loopcounter*/63intj;/*indexingvariable*/64inthigher;/*operatorflag*/65charpopValue;/*valueofpoppednode*/6667/*pushleftparenthesisontothestack*/68push(&stackPtr,"(");69printStack(stackPtr);7071/*addarightparenthesistoinfix*/72strcat(inFix,")");7374/*converttheinfixexpressiontopostfix*/75for(i=0,j=0;stackTop(stackPtr);i++){7677/*ifcurrentcharacterisadigit*/78if(isdigit(inFix[i])){79postFix[j++]=inFix[i];80}/*endif*/8182/*ifcharacterisleftparenthesis,pushonstack*/83elseif(inFix[i]=="("){84push(&stackPtr,"(");85printStack(stackPtr);86}/*endelseif*/8788/*ifcharacterisanoperator*/89elseif(isOperator(inFix[i])){90higher=1;/*usedtostorevalueofprecedencetest*/91©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions39592/*loopwhilecurrentoperatordoesnothave93thehighestprecedence*/94while(higher){9596/*ifthetopofthestackisanoperator*/97if(isOperator(stackTop(stackPtr))){9899/*compareprecedenceofoperators*/100if(precedence(stackTop(stackPtr),inFix[i])){101postFix[j++]=pop(&stackPtr);102printStack(stackPtr);103}/*endif*/104else{105higher=0;/*resetflag*/106}/*endelse*/107108}/*endif*/109else{110higher=0;/*resetflag*/111}/*endelse*/112113}/*endwhile*/114115push(&stackPtr,inFix[i]);116printStack(stackPtr);117}/*endelseif*/118119/*ifcharacterisarightparenthesis*/120elseif(inFix[i]==")"){121122/*popstackuntilpoppedvalueisaleftparenthesis*/123while((popValue=pop(&stackPtr))!="("){124printStack(stackPtr);125postFix[j++]=popValue;126}/*endwhile*/127128printStack(stackPtr);129}/*endelseif*/130131}/*endfor*/132133postFix[j]="";134}/*endfunctionconvertToPostfix*/135136/*checkifcisanoperator*/137intisOperator(charc)138{139140/*ifcisanoperatorreturntrue*/141if(c=="+"||c=="-"||c=="*"||c=="/"||c=="^"){142return1;143144}/*endif*/145else{/*returnfalse*/146return0;147148}/*endelse*/149150}/*endfunctionisOperator*/151©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com396DataStructures:SolutionsChapter12152/*iftheprecedenceofoperator1is>=operator2,153return1(true),elsereturn0(false)*/154intprecedence(charoperator1,charoperator2)155{156157/*compareprecedenceofoperator1andoperator2*/158if(operator1=="^"){159return1;160}/*endif*/161elseif(operator2=="^"){162return0;163}/*endelseif*/164elseif(operator1=="*"||operator1=="/"){165return1;166}/*endelseif*/167elseif(operator1=="+"||operator1=="-"){168169/*ifoperator2is*or/thanreturntrue*/170if(operator2=="*"||operator2=="/"){171return0;172}/*endif*/173else{174return1;175}/*endelse*/176177}/*endelseif*/178179return0;/*default*/180181}/*endfunctionprecedence*/182183/*Insertanodeatthestacktop*/184voidpush(STACKNODEPTR*topPtr,charinfo)185{186STACKNODEPTRnewPtr;/*temporarynodepointer*/187188/*dynamicallyallocatememory*/189newPtr=malloc(sizeof(STACKNODE));190191/*ifmemorywasallocated,insertnodeattopofstack*/192if(newPtr){193newPtr->data=info;194newPtr->nextPtr=*topPtr;195*topPtr=newPtr;196}/*endif*/197else{198printf("%cnotinserted.Nomemoryavailable.n",info);199}/*endelse*/200201}/*endfunctionpush*/202203/*Removeanodefromthestacktop*/204charpop(STACKNODEPTR*topPtr)205{206STACKNODEPTRtempPtr;/*temporarynodepointer*/207charpopValue;/*valueofpoppednode*/208209tempPtr=*topPtr;210popValue=(*topPtr)->data;211*topPtr=(*topPtr)->nextPtr;/*resettopPtr*/212free(tempPtr);/*freememory*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions397213214returnpopValue;/*returnvalueofpoppednode*/215216}/*endfunctionpop*/217218/*Viewthetopelementofthestack*/219charstackTop(STACKNODEPTRtopPtr)220{221222/*ifthestackisnotempty*/223if(!isEmpty(topPtr)){224returntopPtr->data;225}/*endif*/226else{227return0;228}/*endelse*/229230}/*endfunctionstackTop*/231232/*Isthestackempty?*/233intisEmpty(STACKNODEPTRtopPtr)234{235return!topPtr;/*returnNULLifstackisempty*/236237}/*endfunctionisEmpty*/238239/*Printthestack*/240voidprintStack(STACKNODEPTRcurrentPtr)241{242243/*ifthestackisempty*/244if(currentPtr==NULL){245printf("Thestackisempty.nn");246}/*endif*/247else{/*printstack*/248249/*loopthroughstack*/250while(currentPtr!=NULL){251printf("%c",currentPtr->data);252currentPtr=currentPtr->nextPtr;253}/*endwhile*/254255printf("NULLn");256}/*endelse*/257258}/*endfunctionprintStack*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com398DataStructures:SolutionsChapter12Entertheinfixexpression.1+(2*3-(4/5^6)*7)*8Theoriginalinfixexpressionis:1+(2*3-(4/5^6)*7)*8(NULL+(NULL(+(NULL*(+(NULL(+(NULL-(+(NULL(-(+(NULL/(-(+(NULL^/(-(+(NULL/(-(+(NULL(-(+(NULL-(+(NULL*-(+(NULL-(+(NULL(+(NULL+(NULL*+(NULL+(NULL(NULLThestackisempty.Theexpressioninpostfixnotationis:123*456^/7*-8*+©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions39912.13Writeaprogramthatevaluatesapostfixexpression(assumeitisvalid)suchas62+5*84/-Theprogramshouldreadapostfixexpressionconsistingofdigitsandoperatorsintoacharacterarray.Usingmodifiedversionsofthestackfunctionsimplementedearlierinthischapter,theprogramshouldscantheexpressionandevaluateit.Thealgorithmisasfollows:1)Appendthenullcharacter("")totheendofthepostfixexpression.Whenthenullcharacterisencountered,nofurtherprocessingisnecessary.2)While""hasnotbeenencountered,readtheexpressionfromlefttoright.Ifthecurrentcharacterisadigit,Pushitsintegervalueontothestack(theintegervalueofadigitcharacterisitsvalueinthecomputer’scharactersetminusthevalueof"0"inthecomputer’scharacterset).Otherwise,ifthecurrentcharacterisanoperator,Popthetwotopelementsofthestackintovariablesxandy.Calculateyoperatorx.Pushtheresultofthecalculationontothestack.3)Whenthenullcharacterisencounteredintheexpression,popthetopvalueofthestack.Thisistheresultofthepostfixexpression.[Note:In2)above,iftheoperatoris"/",thetopofthestackis2,andthenextelementinthestackis8,thenpop2intox,pop8intoy,evaluate8/2,andpushtheresult,4,backonthestack.Thisnotealsoappliestooperator"-".]Thearithmeticoperationsallowedinanexpressionare:+addition-subtraction*multiplication/division^exponentiation%remainder]Thestackshouldbemaintainedwiththefollowingdeclarations:structstackNode{intdata;structstackNode*nextPtr;};typedefstructstackNodeStackNode;typedefStackNode*StackNodePtr;Theprogramshouldconsistofmainandsixotherfunctionswiththefollowingfunctionheaders:intevaluatePostfixExpression(char*expr)Evaluatethepostfixexpression.intcalculate(intop1,intop2,charoperator)Evaluatetheexpressionop1operatorop2.voidpush(StackNodePtr*topPtr,intvalue)Pushavalueonthestack.intpop(StackNodePtr*topPtr)Popavalueoffthestack.intisEmpty(StackNodePtrtopPtr)Determineifthestackisempty.voidprintStack(StackNodePtrtopPtr)©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com400DataStructures:SolutionsChapter12Printthestack.ANS:1/*Exercise12.13Solution*/2/*Usingastacktoevaluateanexpressioninpostfixnotation*/3#include4#include5#include6#include7#include89/*StackNodestructuredefinition*/10structStackNode{11intdata;/*nodedata*/12structStackNode*nextPtr;/*pointertonextnode*/13};/*endstructStackNode*/1415typedefstructStackNodeStackNode;16typedefStackNode*StackNodePtr;1718/*functionprototypes*/19intevaluatePostfixExpression(char*expr);20intcalculate(intop1,intop2,charoperator);21voidpush(StackNodePtr*topPtr,intinfo);22intpop(StackNodePtr*topPtr);23intisEmpty(StackNodePtrtopPtr);24voidprintStack(StackNodePtrcurrentPtr);2526intmain()27{28charexpression[100];/*postfixexpression*/29charc;/*currentcharacterfromexpression*/30intanswer;/*expressionanswer*/31inti=0;/*indexingvariable*/3233printf("Enterapostfixexpression:n");3435/*readeachcharacterwithgetchar*/36while((c=getchar())!="n"){3738/*removeanyspaces*/39if(c!=""){40expression[i++]=c;41}/*endif*/4243}/*endwhile*/4445expression[i]="";4647/*calculateanswerandprintresult*/48answer=evaluatePostfixExpression(expression);49printf("Thevalueoftheexpressionis:%dn",answer);5051return0;/*indicatesuccessfultermination*/5253}/*endmain*/5455/*evaluatethepostfixexpression*/56intevaluatePostfixExpression(char*expr)57{58inti;/*loopcounter*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions40159intpopVal1;/*rightvalueofcurrentoperation*/60intpopVal2;/*leftvalueofcurrentoperation*/61StackNodePtrstackPtr=NULL;/*pointstothestacktop*/62charc;/*currentcharacter*/6364/*loopthroughexpression*/65for(i=0;(c=expr[i])!="";i++){6667/*ifcharacterisadigit,pushitonstack*/68if(isdigit(c)){69push(&stackPtr,c-"0");70printStack(stackPtr);71}/*endif*/72else{/*calculatecurrentoperation*/73popVal2=pop(&stackPtr);74printStack(stackPtr);75popVal1=pop(&stackPtr);76printStack(stackPtr);7778/*calculateanswerandpushonstack*/79push(&stackPtr,calculate(popVal1,popVal2,c));80printStack(stackPtr);81}/*endelse*/8283}/*endfor*/8485returnpop(&stackPtr);/*returnfinalanswer*/8687}/*endfunctionevaluatePostfixExpression*/8889/*evaluatetheexpressionop1operatorop2*/90intcalculate(intop1,intop2,charoperator)91{9293/*usecorrectoperatortocalculateanswer*/94switch(operator){9596case"+":/*addition*/97returnop1+op2;9899case"-":/*subtraction*/100returnop1-op2;101102case"*":/*multiplication*/103returnop1*op2;104105case"/":/*division*/106returnop1/op2;107108case"^":/*exponentiation*/109returnpow(op1,op2);110}/*endswitch*/111112return0;/*default*/113114}/*endfunctioncalculate*/115116/*Insertanodeatthestacktop*/117voidpush(StackNodePtr*topPtr,intinfo)118{119StackNodePtrnewPtr;/*temporarynodepointer*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com402DataStructures:SolutionsChapter12120121/*dynamicallyallocatememory*/122newPtr=malloc(sizeof(StackNode));123124/*ifmemorywasallocated,insertnodeattopofstack*/125if(newPtr){126newPtr->data=info;127newPtr->nextPtr=*topPtr;128*topPtr=newPtr;129}/*endif*/130else{131printf("%dnotinserted.Nomemoryavailable.n",info);132}/*endelse*/133134}/*endfunctionpush*/135136/*Removeanodefromthestacktop*/137intpop(StackNodePtr*topPtr)138{139StackNodePtrtempPtr;/*temporarynodepointer*/140intpopValue;/*valueofpoppednode*/141142tempPtr=*topPtr;143popValue=(*topPtr)->data;144*topPtr=(*topPtr)->nextPtr;/*resettopPtr*/145free(tempPtr);/*freememory*/146147returnpopValue;/*returnvalueofpoppednode*/148149}/*endfunctionpop*/150151/*Isthestackempty?*/152intisEmpty(StackNodePtrtopPtr)153{154return!topPtr;/*returnNULLifstackisempty*/155156}/*endfunctionisEmpty*/157158/*Printthestack*/159voidprintStack(StackNodePtrcurrentPtr)160{161162/*loopthroughstack*/163while(currentPtr!=NULL){164printf("%d",currentPtr->data);165currentPtr=currentPtr->nextPtr;166}/*endwhile*/167168printf("NULLn");169}/*endfunctionprintStack*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions403Enterapostfixexpression:123*456^/7*-8*+1NULL21NULL321NULL21NULL1NULL61NULL461NULL5461NULL65461NULL5461NULL461NULL15625461NULL461NULL61NULL061NULL7061NULL061NULL61NULL061NULL61NULL1NULL61NULL861NULL61NULL1NULL481NULL1NULLNULL49NULLThevalueoftheexpressionis:4912.14ModifythepostfixevaluatorprogramofExercise12.13sothatitcanprocessintegeroperandslargerthan9.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com404DataStructures:SolutionsChapter1212.15(SupermarketSimulation)Writeaprogramthatsimulatesacheck-outlineatasupermarket.Thelineisaqueue.Customersarriveinrandomintegerintervalsof1to4minutes.Also,eachcustomerisservicedinrandomintegerintervalsof1to4minutes.Obviously,theratesneedtobebalanced.Iftheaveragearrivalrateislargerthantheaverageservicerate,thequeuewillgrowin-finitely.Evenwithbalancedrates,randomnesscanstillcauselonglines.Runthesupermarketsimulationfora12-hourday(720minutes)usingthefollowingalgorithm:Choosearandomintegerbetween1and4todeterminetheminuteatwhichthefirstcustomerarrives.2)Atthefirstcustomer’sarrivaltime:Determinecustomer’sservicetime(randomintegerfrom1to4);Beginservicingthecustomer;Schedulearrivaltimeofnextcustomer(randominteger1to4addedtothecurrenttime).3)Foreachminuteoftheday:Ifthenextcustomerarrives,Sayso;Enqueuethecustomer;Schedulethearrivaltimeofthenextcustomer;Ifservicewascompletedforthelastcustomer;Sayso;Dequeuenextcustomertobeserviced;Determinecustomer’sservicecompletiontime(randomintegerfrom1to4addedtothecurrenttime).Nowrunyoursimulationfor720minutesandanswereachofthefollowing:a)Whatisthemaximumnumberofcustomersinthequeueatanytime?b)Whatisthelongestwaitanyonecustomerexperienced?c)Whathappensifthearrivalintervalischangedfrom1to4minutesto1to3minutes?©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions40512.16ModifytheprogramofFig.12.19toallowthebinarytreetocontainduplicatevalues.ANS:1/*Exercise12.16Solution*/2/*Thisisamodificationoffigure12.19*/3/*OnlyfunctioninsertNodehasbeenmodified*/4#include5#include6#include78/*TreeNodestructuredefinition*/9structTreeNode{10structTreeNode*leftPtr;/*pointertoleftsubtree*/11intdata;/*nodedata*/12structTreeNode*rightPtr;/*pointertorightsubtree*/13};/*endstructTreeNode*/1415typedefstructTreeNodeTreeNode;16typedefTreeNode*TreeNodePtr;1718/*functionprototypes*/19voidinsertNode(TreeNodePtr*treePtr,intvalue);20voidinOrder(TreeNodePtrtreePtr);21voidpreOrder(TreeNodePtrtreePtr);22voidpostOrder(TreeNodePtrtreePtr);2324intmain()25{26inti;/*loopcounter*/27intitem;/*randomvaluetoinsertintree*/28TreeNodePtrrootPtr=NULL;/*pointstothetreeroot*/2930srand(time(NULL));/*randomize*/31printf("Thenumbersbeingplacedinthetreeare:n");3233/*insertrandomvaluesbetween1and15inthetree*/34for(i=1;i<=10;i++){35item=rand()%15;36printf("%3d",item);37insertNode(&rootPtr,item);38}/*endfor*/3940/*traversethetreepreorder*/41printf("nnThepreordertraversalis:n");42preOrder(rootPtr);4344/*traversethetreeinorder*/45printf("nnTheinordertraversalis:n");46inOrder(rootPtr);4748/*traversethetreepostorder*/49printf("nnThepostordertraversalis:n");50postOrder(rootPtr);5152return0;/*indicatesuccessfultermination*/5354}/*endmain*/5556/*insertanodeintothetree*/57voidinsertNode(TreeNodePtr*treePtr,intvalue)58{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com406DataStructures:SolutionsChapter125960/*iftreePtrisNULL*/61if(!*treePtr){6263/*dynamicallyallocatememory*/64*treePtr=malloc(sizeof(TreeNode));6566/*ifmemorywasallocated,insertnode*/67if(*treePtr){68(*treePtr)->data=value;69(*treePtr)->leftPtr=NULL;70(*treePtr)->rightPtr=NULL;71}/*endif*/72else{73printf("%dnotinserted.Nomemoryavailable.n",value);74}/*endelse*/7576return;77}/*endif*/78else{/*recursivelycallinsertNode*/7980/*insertnodeinleftsubtree*/81if(value<=(*treePtr)->data){82insertNode(&((*treePtr)->leftPtr),value);83}/*endif*/84else{/*insertnodeinrightsubtree*/85insertNode(&((*treePtr)->rightPtr),value);86}/*endelse*/8788}/*endelse*/8990}/*endfunctioninsertNode*/9192/*traversethetreeinorder*/93voidinOrder(TreeNodePtrtreePtr)94{9596/*traverseleftsubtree,printnode,traverserightsubtree*/97if(treePtr){98inOrder(treePtr->leftPtr);99printf("%3d",treePtr->data);100inOrder(treePtr->rightPtr);101}/*endif*/102103}/*endfunctioninOrder*/104105/*traversethetreepreorder*/106voidpreOrder(TreeNodePtrtreePtr)107{108109/*printnode,traverseleftsubtree,traverserightsubtree*/110if(treePtr){111printf("%3d",treePtr->data);112preOrder(treePtr->leftPtr);113preOrder(treePtr->rightPtr);114}/*endif*/115116}/*endfunctionpreOrder*/117©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions407118/*traversethetreepostorder*/119voidpostOrder(TreeNodePtrtreePtr)120{121122/*traverseleftsubtree,traverserightsubtree,printnode*/123if(treePtr){124postOrder(treePtr->leftPtr);125postOrder(treePtr->rightPtr);126printf("%3d",treePtr->data);127}/*endif*/128129}/*endfunctionpostOrder*/Thenumbersbeingplacedinthetreeare:1437731271112Thepreordertraversalis:1433127771211Theinordertraversalis:1233777111214Thepostordertraversalis:2137711127314©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com408DataStructures:SolutionsChapter1212.17WriteaprogrambasedontheprogramofFig.12.19thatinputsalineoftext,tokenizesthesentenceintoseparatewords,insertsthewordsinabinarysearchtree,andprintstheinorder,preorder,andpostordertraversalsofthetree.[Hint:Readthelineoftextintoanarray.Usestrtoktotokenizethetext.Whenatokenisfound,createanewnodeforthetree,assignthepointerreturnedbystrtoktomemberstringofthenewnode,andinsertthenodeinthetree.]ANS:1/*Exercise12.17Solution*/2#include3#include4#include56/*TreeNodestructuredefinition*/7structTreeNode{8structTreeNode*leftPtr;/*pointertoleftsubtree*/9char*token;/*nodedata*/10structTreeNode*rightPtr;/*pointertorightsubtree*/11};/*endstructTreeNode*/1213typedefstructTreeNodeTreeNode;14typedefTreeNode*TreeNodePtr;1516/*functionprototypes*/17voidinsertNode(TreeNodePtr*treePtr,char*tokenPtr);18voidinOrder(TreeNodePtrtreePtr);19voidpreOrder(TreeNodePtrtreePtr);20voidpostOrder(TreeNodePtrtreePtr);2122intmain()23{24TreeNodePtrrootPtr=NULL;/*pointstothetreeroot*/25charsentence[80];/*textfromuser*/26char*tokenPtr;/*pointertocurrenttoken*/2728/*promptuserandreadasentence*/29printf("Enterasentence:n");30gets(sentence);3132/*tokenizethesentence*/33tokenPtr=strtok(sentence,"");3435/*insertthetokensinthetree*/36while(tokenPtr){37insertNode(&rootPtr,tokenPtr);38tokenPtr=strtok(NULL,"");39}/*endwhile*/4041/*traversethetreepreorder*/42printf("nThepreordertraversalis:n");43preOrder(rootPtr);4445/*traversethetreeinorder*/46printf("nnTheinordertraversalis:n");47inOrder(rootPtr);4849/*traversethetreepostorder*/50printf("nnThepostordertraversalis:n");51postOrder(rootPtr);5253return0;/*indicatesuccessfultermination*/5455}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions4095657/*insertanodeintothetree*/58voidinsertNode(TreeNodePtr*treePtr,char*tokenPtr)59{6061/*iftreePtrisNULL*/62if(!*treePtr){6364/*dynamicallyallocatememory*/65*treePtr=malloc(sizeof(TreeNode));6667/*ifmemorywasallocated,insertnode*/68if(*treePtr){69(*treePtr)->token=tokenPtr;70(*treePtr)->leftPtr=NULL;71(*treePtr)->rightPtr=NULL;72}/*endif*/73else{74printf(""%s"notinserted.Nomemoryavailable.n",75tokenPtr);76}/*endelse*/7778return;79}/*endif*/80else{/*recursivelycallinsertNode*/8182/*insertnodeinleftsubtree*/83if(strcmp(tokenPtr,(*treePtr)->token)<=0){84insertNode(&((*treePtr)->leftPtr),tokenPtr);85}/*endif*/86else{/*insertnodeinrightsubtree*/87insertNode(&((*treePtr)->rightPtr),tokenPtr);88}/*endelse*/8990}/*endelse*/9192}/*endfunctioninsertNode*/9394/*traversethetreeinorder*/95voidinOrder(TreeNodePtrtreePtr)96{9798/*traverseleftsubtree,printnode,traverserightsubtree*/99if(treePtr){100inOrder(treePtr->leftPtr);101printf("%s",treePtr->token);102inOrder(treePtr->rightPtr);103}/*endif*/104105}/*endfunctioninOrder*/106107/*traversethetreepreorder*/108voidpreOrder(TreeNodePtrtreePtr)109{110111/*printnode,traverseleftsubtree,traverserightsubtree*/112if(treePtr){113printf("%s",treePtr->token);114preOrder(treePtr->leftPtr);115preOrder(treePtr->rightPtr);116}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com410DataStructures:SolutionsChapter12117118}/*endfunctionpreOrder*/119120/*traversethetreepostorder*/121voidpostOrder(TreeNodePtrtreePtr)122{123124/*traverseleftsubtree,traverserightsubtree,printnode*/125if(treePtr){126postOrder(treePtr->leftPtr);127postOrder(treePtr->rightPtr);128printf("%s",treePtr->token);129}/*endif*/130131}/*endfunctionpostOrder*/Enterasentence:thisprograminsertsstringsofdifferentlengthsinatreeThepreordertraversalis:thisprograminsertsdifferentainoflengthsstringstreeTheinordertraversalis:adifferentininsertslengthsofprogramstringsthistreeThepostordertraversalis:aindifferentlengthsofinsertsstringsprogramtreethis12.18Inthischapter,wesawthatduplicateeliminationisstraightforwardwhencreatingabinarysearchtree.Describehowyouwouldperformduplicateeliminationusingonlyasinglesubscriptedarray.Comparetheperformanceofarray-basedduplicateelim-inationwiththeperformanceofbinary-search-tree-basedduplicateelimination.ANS:Usingasinglesubscriptedarray,itisnecessarytocompareeachvaluetobeinsertedinthearraywithallthearrayelementsuntilamatchisfoundoruntilitisdeterminedthatthereisnotaduplicatevalueinthearray.Ifthereisnotadupli-cate,thevaluecanbeinsertedinthearray.Onaverage,halfthearrayelementsmustbesearchedwhenthevalueisadupli-cateandallthearrayelementsmustbesearchedwhenthevalueisnotaduplicate.Thebinarysearchtreeonlycomparesthevaluetobeinsertedwiththevaluesinitspathdownthetree.Ifaleafnodeisreached,andthevaluedoesnotmatchthevalueintheleafnode,thevaluecanbeinserted.Otherwisethevaluecanbediscarded.12.19Writeafunctiondepththatreceivesabinarytreeanddetermineshowmanylevelsithas.12.20(RecursivelyPrintaListBackwards)WriteafunctionprintListBackwardsthatrecursivelyoutputstheitemsinalistinreverseorder.Useyourfunctioninatestprogramthatcreatesasortedlistofintegersandprintsthelistinreverseorder.ANS:1/*Exercise12.20Solution*/2#include3#include45/*ListNodestructuredefinition*/6structListNode{7intdata;/*nodedata*/8structListNode*nextPtr;/*pointertonextnode*/9};/*endstructListNode*/1011typedefstructListNodeListNode;12typedefListNode*ListNodePtr;1314/*functionprototype*/15voidprintList(ListNodePtrcurrentPtr);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions41116voidprintListBackwards(ListNodePtrcurrentPtr);17voidinsertItem(ListNodePtr*sPtr,intvalue);1819intmain()20{21ListNodePtrstartPtr=NULL;/*listpointer*/22intitem;/*loopcounter*/2324/*insertintegersintolist*/25for(item=1;item<11;item++){26insertItem(&startPtr,item);27}/*endfor*/2829printList(startPtr);30printf("n");31printListBackwards(startPtr);3233return0;/*indicatesuccessfultermination*/3435}/*endmain*/3637/*Insertanewvalueintothelistinsortedorder*/38voidinsertItem(ListNodePtr*sPtr,intvalue)39{40ListNodePtrnewPtr;/*newnode*/41ListNodePtrpreviousPtr;/*previousnode*/42ListNodePtrcurrentPtr;/*currentnode*/4344/*dynamicallyallocatememory*/45newPtr=malloc(sizeof(ListNode));4647/*ifnewPtrdoesnotequalNULL*/48if(newPtr){49newPtr->data=value;50newPtr->nextPtr=NULL;5152previousPtr=NULL;53currentPtr=*sPtr;/*setcurrentPtrtostartoflist*/5455/*looptofindcorrectlocationinlist*/56while(currentPtr!=NULL&&value>currentPtr->data){57previousPtr=currentPtr;58currentPtr=currentPtr->nextPtr;59}/*endwhile*/6061/*insertatbeginningoflist*/62if(previousPtr==NULL){63newPtr->nextPtr=*sPtr;64*sPtr=newPtr;65}/*endif*/66else{/*insertnodebetweenpreviousPtrandcurrentPtr*/67previousPtr->nextPtr=newPtr;68newPtr->nextPtr=currentPtr;69}/*endelse*/7071}/*endif*/72else{73printf("%cnotinserted.Nomemoryavailable.n",value);74}/*endelse*/7576}/*endfunctioninsertItem*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com412DataStructures:SolutionsChapter127778/*Printthelist*/79voidprintList(ListNodePtrcurrentPtr)80{8182/*iflistisempty*/83if(!currentPtr){84printf("Listisempty.nn");85}/*endif*/86else{8788/*loopwhilecurrentPtrdoesnotequalNULL*/89while(currentPtr){90printf("%d",currentPtr->data);91currentPtr=currentPtr->nextPtr;92}/*endwhile*/9394printf("*nn");95}/*endelse*/9697}/*endfunctionprintList*/9899/*Printthelistrecursivelybackwards*/100voidprintListBackwards(ListNodePtrcurrentPtr)101{102103/*ifatendoflist*/104if(currentPtr==NULL){105printf("Thelistreversedis:n");106}/*endif*/107else{/*recursivecall*/108printListBackwards(currentPtr->nextPtr);109printf("%d",currentPtr->data);110}/*endelse*/111112}/*endfunctionprintListBackwards*/thelistis:12345678910Thelistreversedis:10987654321©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions41312.21(RecursivelySearchaList)WriteafunctionsearchListthatrecursivelysearchesalinkedlistforaspecifiedvalue.Thefunctionshouldreturnapointertothevalueifitisfound;otherwise,NULLshouldbereturned.Useyourfunctioninatestprogramthatcreatesalistofintegers.Theprogramshouldprompttheuserforavaluetolocateinthelist.ANS:1/*Exercise12.21Solution*/2#include3#include45/*ListNodestructuredefinition*/6structListNode{7intdata;/*nodedata*/8structListNode*nextPtr;/*pointertonextnode*/9};/*endstructListNode*/1011typedefstructListNodeListNode;12typedefListNode*ListNodePtr;1314/*functionprototypes*/15voidinsertItem(ListNodePtr*sPtr,intvalue);16voidprintList(ListNodePtrcurrentPtr);17voidinstructions(void);18ListNodePtrsearchList(ListNodePtrcurrentPtr,constintkey);1920intmain()21{22ListNodePtrstartPtr=NULL;/*listpointer*/23ListNodePtrsearchResultPtr;/*pointertosearchresult*/24intchoice;/*user"smenuchoice*/25intitem;/*valuetoinsertintolist*/26intsearchKey;/*valuetosearchforinlist*/2728instructions();/*displaythemenu*/29printf("?");30scanf("%d",&choice);3132/*whileuserdoesnotchoose3*/33while(choice!=3){3435/*determineuser"schoice*/36switch(choice){3738/*insertanintegerintothelist*/39case1:4041/*promptuserandreadinteger*/42printf("Enteraninteger:");43scanf("n%d",&item);4445/*insertintegerandprintlist*/46insertItem(&startPtr,item);47printList(startPtr);48break;/*exitswitch*/4950/*searchforgiveninteger*/51case2:5253/*promptuserandreadinteger*/54printf("Enterintegertorecursivelysearchfor:");55scanf("%d",&searchKey);56©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com414DataStructures:SolutionsChapter1257searchResultPtr=searchList(startPtr,searchKey);5859/*ifsearchKeynotfound*/60if(searchResultPtr==NULL){61printf("%disnotinthelist.nn",searchKey);62}/*endif*/63else{/*ifsearchKeywasfound*/64printf("%disinthelist.nn",65searchResultPtr->data);66}/*endelse*/6768break;/*exitswitch*/6970/*defaultcase*/71default:72printf("Invalidchoice.nn");73instructions();74break;/*exitswitch*/75}/*endswitch*/7677printf("?");78scanf("%d",&choice);/*getnextchoice*/79}/*endwhile*/8081printf("Endofrun.n");8283return0;/*indicatesuccessfultermination*/8485}/*endmain*/8687/*Printtheinstructions*/88voidinstructions(void)89{90printf("Enteryourchoice:n"91"1toinsertItemanelementintothelist.n"92"2torecursivelysearchlistforanelement.n"93"3toend.n");94}/*endfunctioninstructions*/9596/*Insertanewvalueintothelistinsortedorder*/97voidinsertItem(ListNodePtr*sPtr,intvalue)98{99ListNodePtrnewPtr;/*newnode*/100ListNodePtrpreviousPtr;/*previousnode*/101ListNodePtrcurrentPtr;/*currentnode*/102103/*dynamicallyallocatememory*/104newPtr=malloc(sizeof(ListNode));105106/*ifnewPtrdoesnotequalNULL*/107if(newPtr){108newPtr->data=value;109newPtr->nextPtr=NULL;110111previousPtr=NULL;112currentPtr=*sPtr;/*setcurrentPtrtostartoflist*/113114/*looptofindcorrectlocationinlist*/115while(currentPtr!=NULL&&value>currentPtr->data){116previousPtr=currentPtr;117currentPtr=currentPtr->nextPtr;118}/*endwhile*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions415119120/*insertatbeginningoflist*/121if(previousPtr==NULL){122newPtr->nextPtr=*sPtr;123*sPtr=newPtr;124}/*endif*/125else{/*insertnodebetweenpreviousPtrandcurrentPtr*/126previousPtr->nextPtr=newPtr;127newPtr->nextPtr=currentPtr;128}/*endelse*/129130}/*endif*/131else{132printf("%cnotinserted.Nomemoryavailable.n",value);133}/*endelse*/134135}/*endfunctioninsertItem*/136137/*Printthelist*/138voidprintList(ListNodePtrcurrentPtr)139{140141/*iflistisempty*/142if(!currentPtr){143printf("Listisempty.nn");144}/*endif*/145else{146147/*loopwhilecurrentPtrdoesnotequalNULL*/148while(currentPtr){149printf("%d-->",currentPtr->data);150currentPtr=currentPtr->nextPtr;151}/*endwhile*/152153printf("NULLnn");154}/*endelse*/155156}/*endfunctionprintList*/157158/*searchforkeyinlist*/159ListNodePtrsearchList(ListNodePtrcurrentPtr,constintkey)160{161162/*ifcurrentPtrisatendoflist*/163if(currentPtr==NULL){164returnNULL;/*keynotfound*/165}/*endif*/166elseif(currentPtr->data==key){167returncurrentPtr;/*keyfound*/168}/*endelseif*/169else{170searchList(currentPtr->nextPtr,key);/*keepsearching*/171}/*endelse*/172173}/*endfunctionListNodePtr*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com416DataStructures:SolutionsChapter12Enteryourchoice:1toinsertItemanelementintothelist.2torecursivelysearchlistforanelement3toend.?1Enteraninteger:7Thelistis:7-->NULL?1Enteraninteger:99Thelistis:7-->99-->NULL?1Enteraninteger:56Thelistis:7-->56-->99-->NULL?1Enteraninteger:73Thelistis:7-->56-->73-->99-->NULL?2Enterintegertorecursivelysearchfor:77isinthelist.?2Enterintegertorecursivelysearchfor:5555isnotinthelist.?2Enterintegertorecursivelysearchfor:9999isinthelist.?3Endofrun.12.22(BinaryTreeDelete)Inthisexercise,wediscussdeletingitemsfrombinarysearchtrees.Thedeletionalgorithmisnotasstraightforwardastheinsertionalgorithm.Therearethreecasesthatareencounteredwhendeletinganitem—theitemiscontainedinaleafnode(i.e.,ithasnochildren),theitemiscontainedinanodethathasonechild,ortheitemiscontainedinanodethathastwochildren.Iftheitemtobedeletediscontainedinaleafnode,thenodeisdeletedandthepointerintheparentnodeissettoNULL.Iftheitemtobedeletediscontainedinanodewithonechild,thepointerintheparentnodeissettopointtothechildnodeandthenodecontainingthedataitemisdeleted.Thiscausesthechildnodetotaketheplaceofthedeletednodeinthetree.Thelastcaseisthemostdifficult.Whenanodewithtwochildrenisdeleted,anothernodemusttakeitsplace.However,thepointerintheparentnodecannotsimplybeassignedtopointtooneofthechildrenofthenodetobedeleted.Inmostcases,theresultingbinarysearchtreewouldnotadheretothefollowingcharacteristicofbinarysearchtrees:Thevaluesinanyleftsubtreearelessthanthevalueintheparentnode,andthevaluesinanyrightsubtreearegreaterthanthevalueintheparentnode.Whichnodeisusedasareplacementnodetomaintainthischaracteristic?Eitherthenodecontainingthelargestvalueinthetreelessthanthevalueinthenodebeingdeleted,orthenodecontainingthesmallestvalueinthetreegreaterthanthevalueinthenodebeingdeleted.Letusconsiderthenodewiththesmallervalue.Inabinarysearchtree,thelargestvaluelessthanaparent’svalueislocatedintheleftsubtreeoftheparentnodeandisguaranteedtobecontainedintherightmostnodeofthesubtree.ThisnodeislocatedbywalkingdowntheleftsubtreetotherightuntilthepointertotherightchildofthecurrentnodeisNULL.Wearenowpointingtothereplacementnodewhichiseitheraleafnodeoranodewithonechildtoitsleft.Ifthereplacementnodeisaleafnode,thestepstoperformthedeletionareasfollows:©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions4171)Storethepointertothenodetobedeletedinatemporarypointervariable(thispointerisusedtodeletethedynamicallyallocatedmemory).2)Setthepointerintheparentofthenodebeingdeletedtopointtothereplacementnode.3)Setthepointerintheparentofthereplacementnodetonull.4)Setthepointertotherightsubtreeinthereplacementnodetopointtotherightsubtreeofthenodetobedeleted.5)Deletethenodetowhichthetemporarypointervariablepoints.Thedeletionstepsforareplacementnodewithaleftchildaresimilartothoseforareplacementnodewithnochildren,butthealgorithmalsomustmovethechildtothereplacementnode’sposition.Ifthereplacementnodeisanodewithaleftchild,thestepstoperformthedeletionareasfollows:1)Storethepointertothenodetobedeletedinatemporarypointervariable.2)Setthepointerintheparentofthenodebeingdeletedtopointtothereplacementnode.3)Setthepointerintheparentofthereplacementnodetopointtotheleftchildofthereplacementnode.4)Setthepointertotherightsubtreeinthereplacementnodetopointtotherightsubtreeofthenodetobedeleted.5)Deletethenodetowhichthetemporarypointervariablepoints.WritefunctiondeleteNodewhichtakesasitsargumentsapointertotherootnodeofthetreeandthevaluetobedeleted.Thefunctionshouldlocateinthetreethenodecontainingthevaluetobedeletedandusethealgorithmsdiscussedheretodeletethenode.Ifthevalueisnotfoundinthetree,thefunctionshouldprintamessagethatindicateswhetherornotthevalueisdeleted.ModifytheprogramofFig.12.19tousethisfunction.Afterdeletinganitem,calltheinOrder,preOrderandpostOrdertra-versalfunctionstoconfirmthatthedeleteoperationwasperformedcorrectly.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com418DataStructures:SolutionsChapter1212.23(BinaryTreeSearch)WritefunctionbinaryTreeSearchthatattemptstolocateaspecifiedvalueinabinarysearchtree.Thefunctionshouldtakeasargumentsapointertotherootnodeofthebinarytreeandasearchkeytobelocated.Ifthenodecon-tainingthesearchkeyisfound,thefunctionshouldreturnapointertothatnode;otherwise,thefunctionshouldreturnaNULLpoint-er.ANS:1/*Exercise12.23Solution*/2#include3#include4#include56/*TreeNodestructuredefinition*/7structTreeNode{8structTreeNode*leftPtr;/*pointertoleftsubtree*/9intdata;/*nodedata*/10structTreeNode*rightPtr;/*pointertorightsubtree*/11};/*endstructTreeNode*/1213typedefstructTreeNodeTreeNode;14typedefTreeNode*TreeNodePtr;1516/*functionprototypes*/17voidinsertNode(TreeNodePtr*treePtr,intvalue);18TreeNodePtrbinaryTreeSearch(TreeNodePtrtreePtr,constintkey);1920intmain()21{22inti;/*loopcounter*/23intitem;/*randomvaluetoinsertintree*/24intsearchKey;/*valuetosearchfor*/25TreeNodePtrrootPtr=NULL;/*pointstothetreeroot*/26TreeNodePtrsearchResultPtr;/*pointertosearchresult*/2728srand(time(NULL));/*randomize*/29printf("Thenumbersbeingplacedinthetreeare:n");3031/*insertrandomvaluesbetween1and20inthetree*/32for(i=1;i<=10;i++){33item=1+rand()%20;34printf("%3d",item);35insertNode(&rootPtr,item);36}/*endfor*/3738/*promptuserandreadintegersearchkey*/39printf("nnEnteranintegertosearchfor:");40scanf("%d",&searchKey);4142searchResultPtr=binaryTreeSearch(rootPtr,searchKey);4344/*ifsearchKeynotfound*/45if(searchResultPtr==NULL){46printf("n%dwasnotfoundinthetree.nn",searchKey);47}/*endif*/48else{/*ifkeyfound*/49printf("n%dwasfoundinthetree.nn",50searchResultPtr->data);51}/*endelse*/5253return0;/*indicatesuccessfultermination*/5455}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions4195657/*insertanodeintothetree*/58voidinsertNode(TreeNodePtr*treePtr,intvalue)59{6061/*iftreePtrisNULL*/62if(*treePtr==NULL){6364/*dynamicallyallocatememory*/65*treePtr=malloc(sizeof(TreeNode));6667/*ifmemorywasallocated,insertnode*/68if(*treePtr!=NULL){69(*treePtr)->data=value;70(*treePtr)->leftPtr=NULL;71(*treePtr)->rightPtr=NULL;72}/*endif*/73else{74printf("%dnotinserted.Nomemoryavailable.n",value);75}/*endelse*/7677}/*endif*/78else{/*recursivelycallinsertNode*/7980/*insertnodeinleftsubtree*/81if(value<(*treePtr)->data){82insertNode(&((*treePtr)->leftPtr),value);83}/*endif*/84else{8586/*insertnodeinrightsubtree*/87if(value>(*treePtr)->data){88insertNode(&((*treePtr)->rightPtr),value);89}/*endif*/90else{/*duplicatevalue*/91printf("dup");92}/*endelse*/9394}/*endelse*/9596}/*endelse*/9798}/*endfunctioninsertNode*/99100/*searchforkeyintree*/101TreeNodePtrbinaryTreeSearch(TreeNodePtrtreePtr,constintkey)102{103104/*traversethetreeinOrder*/105if(treePtr==NULL){106returnNULL;/*keynotfound*/107}/*endif*/108elseif(treePtr->data==key){109returntreePtr;/*keyfound*/110}/*endelseif*/111elseif(keydata){112binaryTreeSearch(treePtr->leftPtr,key);/*searchleft*/113}/*endelseif*/114elseif(key>treePtr->data){115binaryTreeSearch(treePtr->rightPtr,key);/*searchright*/116}/*endelseif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com420DataStructures:SolutionsChapter12117118}/*endfunctionbinaryTreeSearch*/Thenumbersbeingplacedinthetreeare:18972132dup101192dupEnteranintegertosearchfor:88wasnotfoundinthetree.12.24(LevelOrderBinaryTreeTraversal)TheprogramofFig.12.19illustratedthreerecursivemethodsoftraversingabinarytree—inordertraversal,preordertraversal,andpostordertraversal.Thisexercisepresentsthelevelordertraversalofabinarytreeinwhichthenodevaluesareprintedlevel-by-levelstartingattherootnodelevel.Thenodesoneachlevelareprintedfromlefttoright.Thelevelordertraversalisnotarecursivealgorithm.Itusesthequeuedatastructuretocontroltheoutputofthenodes.Thealgorithmisasfollows:1)Inserttherootnodeinthequeue2)Whiletherearenodesleftinthequeue,GetthenextnodeinthequeuePrintthenode’svalueIfthepointertotheleftchildofthenodeisnotnullInserttheleftchildnodeinthequeueIfthepointertotherightchildofthenodeisnotnullInserttherightchildnodeinthequeue.WritefunctionlevelOrdertoperformalevelordertraversalofabinarytree.Thefunctionshouldtakeasanargumentapointertotherootnodeofthebinarytree.ModifytheprogramofFig.12.19tousethisfunction.Comparetheoutputfromthisfunctiontotheoutputsoftheothertraversalalgorithmstoseethatitworkedcorrectly.[Note:YouwillalsoneedtomodifyandincorporatethequeueprocessingfunctionsofFig.12.13inthisprogram.]ANS:1/*Exercise12.24solution*/2#include3#include4#include56/*TreeNodestructuredefinition*/7structTreeNode{8structTreeNode*leftPtr;/*pointertoleftsubtree*/9intdata;/*nodedata*/10structTreeNode*rightPtr;/*pointertorightsubtree*/11};/*endstructTreeNode*/1213typedefstructTreeNodeTreeNode;14typedefTreeNode*TreeNodePtr;1516/*treefunctionprototypes*/17voidinsertNode(TreeNodePtr*treePtr,intvalue);18voidlevelOrderTraversal(TreeNodePtrtreePtr);1920/*QueueNodestructuredefinition*/21structQueueNode{22TreeNodePtrdata;/*nodedata*/23structQueueNode*nextPtr;/*pointertonextnode*/24};/*endstructQueueNode*/2526typedefstructQueueNodeQueueNode;27typedefQueueNode*QueueNodePtr;28©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions42129/*queuefunctionprototypes*/30intisEmpty(QueueNodePtrheadPtr);31TreeNodePtrdequeue(QueueNodePtr*headPtr,QueueNodePtr*tailPtr);32voidenqueue(QueueNodePtr*headPtr,QueueNodePtr*tailPtr,33TreeNodePtrnode);3435intmain()36{37inti;/*loopcounter*/38intitem;/*randomvaluetoinsertintree*/39TreeNodePtrrootPtr=NULL;/*pointstothetreeroot*/4041srand(time(NULL));/*randomize*/42printf("Thevaluesbeinginsertedinthetreeare:n");4344/*insertrandomvaluesbetween1and15inthetree*/45for(i=1;i<=15;i++){46item=1+rand()%20;47printf("%d",item);48insertNode(&rootPtr,item);49}/*endfor*/5051/*traversethetreelevelorder*/52printf("nnThelevelordertraversalis:n");53levelOrderTraversal(rootPtr);54printf("n");5556return0;/*indicatesuccessfultermination*/5758}/*endmain*/5960/*Levelordertraversalofabinarytree*/61voidlevelOrderTraversal(TreeNodePtrptr)62{63QueueNodePtrhead=NULL;/*pointstoqueuehead*/64QueueNodePtrtail=NULL;/*pointstoqueuetail*/65TreeNodePtrnode;/*currenttreenode*/6667/*iftreeisnotempty*/68if(ptr!=NULL){69enqueue(&head,&tail,ptr);/*enqueuerootnood*/7071/*whilequeueisnotempty*/72while(!isEmpty(head)){7374/*dequeuenextnodeandprintdata*/75node=dequeue(&head,&tail);76printf("%d",node->data);7778/*insertleftchildnodeinthequeue*/79if(node->leftPtr!=NULL){80enqueue(&head,&tail,node->leftPtr);81}/*endif*/8283/*insertrightchildnodeinthequeue*/84if(node->rightPtr!=NULL){85enqueue(&head,&tail,node->rightPtr);86}/*endif*/8788}/*endwhile*/8990}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com422DataStructures:SolutionsChapter129192}/*endfunctionlevelOrderTraversal*/9394/*insertanodeintothetree*/95voidinsertNode(TreeNodePtr*treePtr,intvalue)96{9798/*iftreePtrisNULL*/99if(*treePtr==NULL){100101/*dynamicallyallocatememory*/102*treePtr=malloc(sizeof(TreeNode));103104/*ifmemorywasallocated,insertnode*/105if(*treePtr!=NULL){106(*treePtr)->data=value;107(*treePtr)->leftPtr=NULL;108(*treePtr)->rightPtr=NULL;109}/*endif*/110else{111printf("%dnotinserted.Nomemoryavailable.n",value);112}/*endelse*/113114}/*endif*/115else{/*recursivelycallinsertNode*/116117/*insertnodeinleftsubtree*/118if(value<(*treePtr)->data){119insertNode(&((*treePtr)->leftPtr),value);120}/*endif*/121else{122123/*insertnodeinrightsubtree*/124if(value>(*treePtr)->data){125insertNode(&((*treePtr)->rightPtr),value);126}/*endif*/127else{/*duplicatevalue*/128printf("dup");129}/*endelse*/130131}/*endelse*/132133}/*endelse*/134135}/*endfunctioninsertNode*/136137/*enqueuenode*/138voidenqueue(QueueNodePtr*headPtr,QueueNodePtr*tailPtr,TreeNodePtrnode)139{140QueueNodePtrnewPtr;/*temporarynodepointer*/141142/*dynamicallyallocatememory*/143newPtr=malloc(sizeof(QueueNode));144145/*ifnewPtrdoesnotequalNULL*/146if(newPtr!=NULL){147newPtr->data=node;148newPtr->nextPtr=NULL;149150/*ifqueueisempty,insertathead*/151if(isEmpty(*headPtr)){©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions423152*headPtr=newPtr;153}/*endif*/154else{/*insertattail*/155(*tailPtr)->nextPtr=newPtr;156}/*endelse*/157158*tailPtr=newPtr;159}/*endif*/160else{161printf("Nodenotinsertedn");162}/*endelse*/163164}/*endfunctionenqueue*/165166/*dequeuenodefromqueue*/167TreeNodePtrdequeue(QueueNodePtr*headPtr,QueueNodePtr*tailPtr)168{169TreeNodePtrnode;/*dequeuednode*/170QueueNodePtrtempPtr;/*temporarynodepointer*/171172/*dequeuenodeandresetqueueheadPtr*/173node=(*headPtr)->data;174tempPtr=*headPtr;175*headPtr=(*headPtr)->nextPtr;176177/*ifqueueisempty*/178if(*headPtr==NULL){179*tailPtr=NULL;180}/*endif*/181182free(tempPtr);/*freememory*/183184returnnode;/*returndequeuednode*/185186}/*endfunctiondequeue*/187188/*isqueueempty?*/189intisEmpty(QueueNodePtrheadPtr)190{191returnheadPtr==NULL;/*returnNULLisqueueisempty*/192193}/*endfunctionisEmpty*/Thevaluesbeinginsertedinthetreeare:51075dup1191517dup20620dup4164dupThelevelordertraversalis:5110471169152016©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com424DataStructures:SolutionsChapter1212.25(PrintingTrees)WritearecursivefunctionoutputTreetodisplayabinarytreeonthescreen.Thefunctionshouldoutputthetreerow-by-rowwiththetopofthetreeattheleftofthescreenandthebottomofthetreetowardtherightofthescreen.Eachrowisoutputvertically.Forexample,thebinarytreeillustratedinFig.12.22isoutputasfollows:999792837271694944403228191811Notetherightmostleafnodeappearsatthetopoftheoutputintherightmostcolumn,andtherootnodeappearsattheleftoftheoutput.Eachcolumnofoutputstartsfivespacestotherightofthepreviouscolumn.FunctionoutputTreeshouldreceiveasargu-mentsapointertotherootnodeofthetreeandanintegertotalSpacesrepresentingthenumberofspacesprecedingthevaluetobeoutput(thisvariableshouldstartatzerosotherootnodeisoutputattheleftofthescreen).Thefunctionusesamodifiedinordertraversaltooutputthetree—itstartsattherightmostnodeinthetreeandworksbacktotheleft.Thealgorithmisasfollows:WhilethepointertothecurrentnodeisnotnullRecursivelycalloutputTreewiththerightsubtreeofthecurrentnodeandtotalSpaces+5Useaforstatementtocountfrom1tototalSpacesandoutputspacesOutputthevalueinthecurrentnodeSetthepointertothecurrentnodetopointtotheleftsubtreeofthecurrentnodeIncrementtotalSpacesby5.ANS:1/*Exercise12.25Solution*/2#include3#include4#include56/*TreeNodestructuredefinition*/7structTreeNode{8structTreeNode*leftPtr;/*pointertoleftsubtree*/9intdata;/*nodedata*/10structTreeNode*rightPtr;/*pointertorightsubtree*/11};/*endstructTreeNode*/1213typedefstructTreeNodeTreeNode;14typedefTreeNode*TreeNodePtr;1516/*functionprototypes*/17voidinsertNode(TreeNodePtr*treePtr,intvalue);18voidoutputTree(TreeNodePtrtreePtr,intspaces);1920intmain()21{22inti;/*loopcounter*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions42523intitem;/*randomvaluetobeinserted*/24inttotalSpaces=0;/*spacespreceedingoutput*/25TreeNodePtrrootPtr=NULL;/*pointstothetreeroot*/2627srand(time(NULL));/*randomize*/28printf("Thenumbersbeingplacedinthetreeare:n");2930/*insertrandomvaluesbetween1and10inthetree*/31for(i=1;i<=10;i++){32item=rand()%15;33printf("%3d",item);34insertNode(&rootPtr,item);35}/*endfor*/3637printf("nn");38outputTree(rootPtr,totalSpaces);/*displaytree*/3940return0;/*indicatesuccessfultermination*/4142}/*endmain*/4344/*insertanodeintothetree*/45voidinsertNode(TreeNodePtr*treePtr,intvalue)46{4748/*iftreePtrisNULL*/49if(*treePtr==NULL){5051/*dynamicallyallocatememory*/52*treePtr=malloc(sizeof(TreeNode));5354/*ifmemorywasallocated,insertnode*/55if(*treePtr!=NULL){56(*treePtr)->data=value;57(*treePtr)->leftPtr=NULL;58(*treePtr)->rightPtr=NULL;59}/*endif*/60else{61printf("%dnotinserted.Nomemoryavailable.n",value);62}/*endelse*/6364}/*endif*/65else{/*recursivelycallinsertNode*/6667/*insertnodeinleftsubtree*/68if(value<(*treePtr)->data){69insertNode(&((*treePtr)->leftPtr),value);70}/*endif*/71else{7273/*insertnodeinrightsubtree*/74if(value>(*treePtr)->data){75insertNode(&((*treePtr)->rightPtr),value);76}/*endif*/77else{/*duplicatevalue*/78printf("dup");79}/*endelse*/8081}/*endelse*/8283}/*endelse*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com426DataStructures:SolutionsChapter128485}/*endfunctioninsertNode*/8687/*displaythetree*/88voidoutputTree(TreeNodePtrtreePtr,intspaces)89{90intloop;/*loopcounter*/9192/*whilenottheendoftree*/93while(treePtr!=NULL){9495/*recursivecallwithrightsubtree*/96outputTree(treePtr->rightPtr,spaces+5);9798/*loopandoutputspaces*/99for(loop=1;loop<=spaces;loop++){100printf("");101}/*endfor*/102103printf("%dn",treePtr->data);104105/*setpointertoleftsubtreeandmakerecursivecall*/106outputTree(treePtr->leftPtr,spaces+5);107treePtr=NULL;108}/*endwhile*/109110}/*endfunctionoutputTree*/Thenumbersbeingplacedinthetreeare:1561411299dup14dup81411986521SPECIALSECTION:BUILDINGYOUROWNCOMPILERInExercise7.18andExercise7.19,weintroducedSimpletronMachineLanguage(SML)andcreatedtheSimpletroncomputersimulatortoexecuteprogramswritteninSML.Inthissection,webuildacompilerthatconvertsprogramswritteninahigh-levelprogramminglanguagetoSML.Thissection“ties”togethertheentireprogrammingprocess.Wewillwriteprogramsinthisnewhigh-levellanguage,compiletheprogramsonthecompilerwebuild,andruntheprogramsonthesimulatorwebuiltinExercise7.19.12.26(TheSimpleLanguage)Beforewebeginbuildingthecompiler,wediscussasimple,yetpowerful,high-levellanguagesim-ilartoearlyversionsofthepopularlanguageBASIC.WecallthelanguageSimple.EverySimplestatementconsistsofalinenumberandaSimpleinstruction.Linenumbersmustappearinascendingorder.EachinstructionbeginswithoneofthefollowingSimplecommands:rem,input,let,print,goto,if…gotoorend(seeFig.12.23).Allcommandsexceptendcanbeusedrepeatedly.Simpleevaluatesonlyintegerexpressionsusingthe+,-,*and/operators.TheseoperatorshavethesameprecedenceasinC.Parenthesescanbeusedtochangetheorderofevaluationofanexpression.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions427CommandExamplestatementDescriptionrem50remthisisaremarkAnytextfollowingthecommandremisfordocumentationpurposesonlyandisignoredbythecompiler.input30inputxDisplayaquestionmarktoprompttheusertoenteraninte-ger.Readthatintegerfromthekeyboardandstoretheinte-gerinx.let80letu=4*(j-56))Assignuthevalueof4*(j-56).Notethatanarbitrarilycomplexexpressioncanappeartotherightoftheequalsign.print10printwDisplaythevalueofw.goto70goto45Transferprogramcontroltoline45.if…goto35ifi==zgoto80Compareiandzforequalityandtransferprogramcontroltoline80iftheconditionistrue;otherwise,continueexecu-tionwiththenextstatement.end99endTerminateprogramexecution.Fig.12.1Simplecommands.OurSimplecompilerrecognizesonlylowercaseletters.AllcharactersinaSimplefileshouldbelowercase(uppercaselettersresultinasyntaxerrorunlesstheyappearinaremstatementinwhichcasetheyareignored).Avariablenameisasingleletter.Simpledoesnotallowdescriptivevariablenames,sovariablesshouldbeexplainedinremarkstoindicatetheiruseintheprogram.Simpleusesonlyintegervariables.Simpledoesnothavevariabledeclarations—merelymentioningavariablenameinaprogramcausesthevariabletobedeclaredandinitializedtozeroautomatically.ThesyntaxofSimpledoesnotallowstringmanipulation(readingastring,writingastring,comparingstrings,etc.).IfastringisencounteredinaSimpleprogram(afteracommandotherthanrem),thecompilergeneratesasyntaxerror.OurcompilerwillassumethatSimpleprogramsareenteredcorrectly.Exercise12.29asksthestudenttomodifythecompilertoperformsyntaxerrorchecking.Simpleusestheconditionalif…gotostatementandtheunconditionalgotostatementtoaltertheflowofcontrolduringpro-gramexecution.Iftheconditionintheif…gotostatementistrue,controlistransferredtoaspecificlineoftheprogram.Thefol-lowingrelationalandequalityoperatorsarevalidinanif…gotostatement:<,>,<=,>=,==or!=.TheprecedenceoftheseoperatorsisthesameasinC.LetusnowconsiderseveralSimpleprogramsthatdemonstrateSimple’sfeatures.Thefirstprogram(Fig.12.24)readstwointegersfromthekeyboard,storesthevaluesinvariablesaandb,andcomputesandprintstheirsum(storedinvariablec).110remdetermineandprintthesumoftwointegers215rem320reminputthetwointegers430inputa540inputb645rem750remaddintegersandstoreresultinc860letc=a+b965rem1070remprinttheresult1180printc1290remterminateprogramexecution1399endFigure12.25determinesandprintsthelargeroftwointegers.Theintegersareinputfromthekeyboardandstoredinsandt.Theif…gotostatementteststheconditions>=t.Iftheconditionistrue,controlistransferredtoline90andsisoutput;other-wise,tisoutputandcontrolistransferredtotheendstatementinline99wheretheprogramterminates.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com428DataStructures:SolutionsChapter12110remdeterminethelargeroftwointegers220inputs330inputt432rem535remtestifs>=t640ifs>=tgoto90745rem850remtisgreaterthans,soprintt960printt1070goto991175rem1280remsisgreaterthanorequaltot,soprints1390prints1499endSimpledoesnotprovidearepetitionstructure(suchasC’sfor,whileordo…while).However,SimplecansimulateeachofC"srepetitionstructuresusingtheif…gotoandgotostatements.Figure12.26usesasentinel-controlledlooptocalculatethesquaresofseveralintegers.Eachintegerisinputfromthekeyboardandstoredinvariablej.Ifthevalueenteredisthesentinel-9999,controlistransferredtoline99wheretheprogramterminates.Otherwise,kisassignedthesquareofj,kisoutputtothescreenandcontrolispassedtoline20wherethenextintegerisinput.110remcalculatethesquaresofseveralintegers220inputj323rem425remtestforsentinelvalue530ifj==-9999goto99633rem735remcalculatesquareofjandassignresulttok840letk=j*j950printk1053rem1155remlooptogetnextj1260goto201399endUsingthesampleprogramsofFig.12.24,Fig.12.25andFig.12.26asyourguide,writeaSimpleprogramtoaccomplisheachofthefollowing:a)Inputthreeintegers,determinetheiraverageandprinttheresult.ANS:15remExercise12.26PartASolution26rem310inputx415inputy510inputx621remcalculateaveragea725leta=(x+y+z)/3826rem930printa1099end©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter12DataStructures:Solutions429b)Useasentinel-controlledlooptoinput10integersandcomputeandprinttheirsum.ANS:15remExercise12.26PartBSolution26rem310inputn412remsetupsentinelloop515ifn==9999goto40616rem717remaddntothesumofs820lets=s+n921rem1022remlooptogetnextn1125goto101236remprintsums1340prints1499endc)Useacounter-controlledlooptoinputsevenintegers,somepositiveandsomenegative,andcomputeandprinttheiraverage.ANS:15remexercise12.26PartCSolution26rem310inputm411remincrementcounterby1512remcisautomaticallyinitiatedto0613remwhencreated715letc=c+1816rem917remcalculatesums1020lets=s+m1122remlooptogetnextm1223remifcisnotyet71325ifc<=7goto101426rem1527remcomputeaveragea1630leta=s/71731rem1835printa1999end©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com430DataStructures:SolutionsChapter12d)Inputaseriesofintegersanddetermineandprintthelargest.Thefirstintegerinputindicateshowmanynumbersshouldbeprocessed.ANS:15remExercise12.26PartDSolution26rem37remEnterthenumberofintegers48remtobeprocessed510inputn623rembeginenteringnumberst725inputt826remcheckiftislargerthan1927reml’sinitialvalueiszero1030remift<=1goto501131remtmustbelargerthan11232remsoassigntaslargest1335letl=t1449remdecrementn1550letn=n-11659remtestforloopexitcondition1760ifn==0goto801869remlooptogetnextt1970goto252079remprintlargestvalue2180printl2299ende)Input10integersandprintthesmallest.ANS:11remExercise12.26PartESolution22rem33remsetcountercequalto145letc=156reminputintegerm67remassignfirstentryto78remthesmallestvalues89inputm910lets=m1011rementermainloop1113goto201214remmainloop1315inputm1418remdetermineifmissmaller1519remthancurrents1620ifm34#definePI3.14159/*constantrepresentingPi*/56/*definepreprocessordirectivespherevolume*/7#defineSPHEREVOLUME(r)(4.0/3.0*PI*(r)*(r)*(r))89intmain()10{11inti;/*loopcounter*/1213/*printheader*/14printf("%10s%10sn","Radius","Volume");1516/*usespherevolumemacro*/17for(i=1;i<=10;i++){18printf("%10d%10.3fn",i,SPHEREVOLUME(i));19}/*endfor*/2021return0;/*indicatesuccessfultermination*/2223}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com442ThePreprocessor:SolutionsChapter13RadiusVolume14.189233.5103113.0974268.0825523.5986904.77871436.75482144.65993053.625104188.78713.5Writeaprogramthatproducesthefollowingoutput:Thesumofxandyis13TheprogramshoulddefinemacroSUMwithtwoarguments,xandy,anduseSUMtoproducetheoutput.ANS:1/*Exercise13.5Solution*/2#include34/*macrotoaddtwovalue*/5#defineSUM(x,y)((x)+(y))67intmain()8{910/*displaysumofxandyusingmacroSUM*/11printf("Thesumofxandyis%dn",SUM(6,7));1213return0;/*indicatesuccessfultermination*/1415}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter13ThePreprocessor:Solutions44313.6WriteaprogramthatdefinesandusesmacroMINIMUM2todeterminethesmallestoftwonumericvalues.Inputthevaluesfromthekeyboard.ANS:1/*Exercise13.6Solution*/2#include34/*macrotodeterminesmallestoftwovalues*/5#defineMINIMUM2(x,y)((x)<(y)?(x):(y))67intmain()8{9inta;/*firstinteger*/10intb;/*secondinteger*/11doublec;/*firstdouble*/12doubled;/*seconddouble*/1314/*promptuserandreadtwointegers*/15printf("Entertwointegers:");16scanf("%d%d",&a,&b);1718/*usemacroMINIMUMtodetermineanddisplay19smallestuserenteredinteger*/20printf("Theminimumof%dand%dis%dnn",a,b,21MINIMUM2(a,b));2223/*promptuserandreadtwodoubles*/24printf("Entertwodoubles:");25scanf("%lf%lf",&c,&d);2627/*usemacroMINIMUMtodetermineanddisplay28smallestuserentereddouble*/29printf("Theminimumof%.2fand%.2fis%.2fnn",30c,d,MINIMUM2(c,d));3132return0;/*indicatesuccessfultermination*/3334}/*endmain*/Entertwointegers:49Theminimumof4and9is4Entertwodoubles:45.713.2Theminimumof45.70and13.20is13.20©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com444ThePreprocessor:SolutionsChapter1313.7WriteaprogramthatdefinesandusesmacroMINIMUM3todeterminethesmallestofthreenumericvalues.MacroMINIMUM3shouldusemacroMINIMUM2definedinExercise13.6todeterminethesmallestnumber.Inputthevaluesfromthekey-board.ANS:1/*Exercise13.7Solution*/2#include34/*macrotodeterminesmallestoftwovalues*/5#defineMINIMUM2(x,y)((x)<(y)?(x):(y))67/*macrothatusesMINIMUM2todeterminesmallestofthreevalues*/8#defineMINIMUM3(u,v,w)(MINIMUM2(w,MINIMUM2(u,v)))910intmain()11{12inta;/*firstinteger*/13intb;/*secondinteger*/14intc;/*thirdinteger*/15doubled;/*firstdouble*/16doublee;/*seconddouble*/17doublef;/*thirddouble*/1819/*promptuserandreadthreeintegers*/20printf("Enterthreeintegers:");21scanf("%d%d%d",&a,&b,&c);2223/*usemacroMINIMUM3todeterminesmallest24ofthreeuserinputintegers*/25printf("Theminimumof%d,%d,and%dis%dnn",26a,b,c,MINIMUM3(a,b,c));2728/*promptuserandreadthreedoubles*/29printf("Enterthreedoubles:");30scanf("%lf%lf%lf",&d,&e,&f);3132/*usemacroMINIMUM3todeterminesmallest33ofthreeuserinputdoubles*/34printf("Theminimumof%.2f,%.2f,and%.2fis%.2fnn",35d,e,f,MINIMUM3(d,e,f));3637return0;/*indicatesuccessfultermination*/3839}/*endmain*/Enterthreeintegers:7210Theminimumof7,2,and10is2Enterthreedoubles:4.993.21.3Theminimumof4.90,93.20,and1.30is1.30©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter13ThePreprocessor:Solutions44513.8WriteaprogramthatdefinesandusesmacroPRINTtoprintastringvalue.ANS:1/*Exercise13.8Solution*/2#include34/*macrothatprintsitsargument*/5#definePRINT(string)printf("%s",(string))67intmain()8{9chartext[20];/*arraytoholduserinputstring*/1011/*promptuserandreadstring*/12PRINT("Enterastring:");13scanf("%s",text);1415/*usemacrotooutputstringenteredbyuser*/16PRINT("Thestringenteredwas:");17PRINT(text);18PRINT("n");1920return0;/*indicatesuccessfultermination*/2122}/*endmain*/Enterastring:HelloThestringenteredwas:Hello13.9WriteaprogramthatdefinesandusesmacroPRINTARRAYtoprintanarrayofintegers.Themacroshouldreceivethearrayandthenumberofelementsinthearrayasarguments.ANS:1/*Exercise13.9Solution*/2#include34/*macrothatprintsanarrayofvalues*/5#definePRINTARRAY(a,n)for(i=0;i<(n);i++)6printf("%d",a[i])78intmain()9{10inti;/*definesiforuseinPRINTARRAY*/1112/*initializearraytobeprinted*/13intb[10]={2,4,6,8,10,12,14,16,18,20};1415printf("Thearrayvaluesare:n");16PRINTARRAY(b,10);/*printthearray*/1718return0;/*indicatesuccessfultermination*/1920}/*endmain*/Thearrayvaluesare:2468101214161820©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com446ThePreprocessor:SolutionsChapter1313.10WriteaprogramthatdefinesandusesmacroSUMARRAYtosumthevaluesinanumericarray.Themacroshouldreceivethearrayandthenumberofelementsinthearrayasarguments.ANS:1/*Exercise13.10Solution*/2#include34/*macrothataddsvaluesofanumericarray*/5#defineSUMARRAY(a,n)for(i=0;i<(n);i++)6sum+=a[i]78intmain()9{10inti;/*loopcounter*/11intsum=0;/*sumofarrayelements*/1213/*initializearraywhosevalueswillbeadded*/14intb[10]={1,2,3,4,5,6,7,8,9,10};1516/*usemacroSUMARRAYtoaddelementsofarray*/17SUMARRAY(b,10);18printf("Thesumoftheelementsofarraybis%dn",sum);1920return0;/*indicatesuccessfultermination*/2122}/*endmain*/Thesumoftheelementsofarraybis55©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com14OtherCTopics:SolutionsSOLUTIONS14.2Writeaprogramthatcalculatestheproductofaseriesofintegersthatarepassedtofunctionproductusingavariable-lengthargumentlist.Testyourfunctionwithseveralcalls,eachwithadifferentnumberofarguments.ANS:1/*Exercise14.2Solution*/2#include3#include45/*functionwithvariablelengthargumentlist*/6intsum(inti,...);78intmain()9{10inta=1;/*valuestosum*/11intb=2;12intc=3;13intd=4;14inte=5;1516/*displayintegervalues*/17printf("%s%d,%s%d,%s%d,%s%d,%s%dn","a=",a,"b=",18b,"c=",c,"d=",d,"e=",e);1920/*callsumwithdifferentnumberofargumentsineachcall*/21printf("%s%dn%s%dn%s%dn%s%dn","Thesumofaandbis:",22sum(2,a,b),"Thesumofa,b,andcis:",sum(3,a,b,c),23"Thesumofa,b,c,anddis:",sum(4,a,b,c,d),24"Thesumofa,b,c,d,andeis:",sum(5,a,b,c,d,e));2526return0;/*indicatesuccessfultermination*/2728}/*endmain*/29©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com448OtherCTopics:SolutionsChapter1430/*sumsintegerspassedasarguments*/31intsum(inti,...)32{33inttotal=0;/*sumofintegers*/34intj;/*loopcounter*/35va_listap;/*variablelengthargumentlist*/3637va_start(ap,i);/*invokemacrotoaccessarguments*/3839/*calculatetotal*/40for(j=1;j<=i;j++){41total+=va_arg(ap,int);42}/*endfor*/4344va_end(ap);/*performterminationhousekeeping*/4546returntotal;/*returnsumofarguments*/4748}/*endfunctionsum*/a=1,b=2,c=3,d=4,e=5Thesumofaandbis:3Thesumofa,b,andcis:6Thesumofa,b,c,anddis:10Thesumofa,b,c,d,andeis:1514.3Writeaprogramthatprintsthecommand-lineargumentsoftheprogram.ANS:1/*Exercise14.3Solution*/2#include34intmain(intargc,char*argv[])5{6inti;/*loopcounter*/78printf("Thecommandlineargumentsare:n");910/*displayargumentsgiventoprogramatcommandline*/11for(i=0;i34intmain(intargc,char*argv[])5{6inta[100];/*arrayofintegersfromuser*/7intcount;/*countofintegersentered*/8inttemp;/*temporaryintegerforswapping*/9inti;/*loopcounter*/10intj;/*loopcounter*/11intorder;/*sortinascendingordescendingorder*/1213/*telluserifimproperargumentswerepassed*/14if(argc!=2){15printf("Usage:p14_4-optionn");16}/*endif*/17else{1819/*promptuserforintegerstobesorted*/20printf("Enterupto100integers(EOFtoendinput):");2122/*storeintegersuntil100elementsorEOFentered*/23for(count=0;!feof(stdin)&&count<100;count++){24scanf("%d",&a[count]);25}/*endfor*/2627/*setorderbasedoncommand-lineargument*/28order=(argv[1][1]=="d")?0:1;2930/*loopthrougharrayandswapelementsasneeded*/31for(i=1;ia[j]){48temp=a[i];49a[i]=a[j];50a[j]=temp;51}/*endif*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com450OtherCTopics:SolutionsChapter145253}/*endelse*/5455}/*endfor*/5657}/*endfor*/5859printf("nnThesortedarrayis:n");6061/*displaysortedarray*/62for(i=0;i34intmain()5{6FILE*filePtr;/*pointertofilebeingmodified*/7FILE*tempFilePtr;/*temporaryfilepointer*/8intc;/*currentcharacter*/9charfileName[30];/*nameoffiletobemodified*/1011/*promptuserandreadfilename*/12printf("Thisprograminsertsspacesbetweeneachcharactern"13"ofafile.Enterafiletobemodified:");14scanf("%s",fileName);1516/*exitprogramiffilecannotbeopened*/17if((filePtr=fopen(fileName,"r+"))!=NULL){1819/*exitprogramiftemporaryfilecannotbeopened*/20if((tempFilePtr=tmpfile())!=NULL){21printf("nThefilebeforemodificationis:n");2223/*readeachcharacterfromfile*/24while((c=getc(filePtr))!=EOF){25putchar(c);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter14OtherCTopics:Solutions45126putc(c,tempFilePtr);/*putcharacterintempfile*/2728/*writeaspacetotempfile*/29if(c!="n"){30putc("",tempFilePtr);31}/*endif*/3233}/*endwhile*/3435rewind(tempFilePtr);/*rewindbothfilepointers*/36rewind(filePtr);37printf("nnThefileaftermodificationis:n");3839/*readeachcharacterfromtempfile*/40while((c=getc(tempFilePtr))!=EOF){41putchar(c);42putc(c,filePtr);/*rewritecharactertofile*/43}/*endwhile*/4445}/*endif*/46else{47printf("Unabletoopentemporaryfilen");48}/*endelse*/4950}/*endif*/51else{52printf("Unabletoopen%sn",fileName);53}/*endelse*/5455return0;/*indicatesuccessfultermination*/5657}/*endmain*/Thisprograminsertsspacesbetweeneachcharacterofafile.Enterafiletobemodified:test.datThefilebeforemodificationis:Thisisatestfileforexercise14.5.Thefileaftermodificationis:Thisisatestfileforexercise14.5.14.6Readthemanualsforyourcompilertodeterminewhatsignalsaresupportedbythesignalhandlinglibrary(signal.h).WriteaprogramthatcontainssignalhandlersforthestandardsignalsSIGABRTandSIGINT.TheprogramshouldtestthetrappingofthesesignalsbycallingfunctionaborttogenerateasignaloftypeSIGABRTandbytypingctogenerateasignaloftypeSIGINT.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com452OtherCTopics:SolutionsChapter1414.7Writeaprogramthatdynamicallyallocatesanarrayofintegers.Thesizeofthearrayshouldbeinputfromthekeyboard.Theelementsofthearrayshouldbeassignedvaluesinputfromthekeyboard.Printthevaluesofthearray.Next,reallocatethemem-oryforthearrayto1/2ofthecurrentnumberofelements.Printthevaluesremaininginthearraytoconfirmthattheymatchthefirsthalfofthevaluesintheoriginalarray.ANS:1/*Exercise14.7Solution*/2#include3#include45intmain()6{7intcount;/*numberofelementsinarray*/8inti;/*loopcounter*/9int*array;/*pointertothearray*/1011/*promptuserandreadintegersizeofarray*/12printf("Thisprogramdynamicallyallocatesanarrayofintegers.n"13"Enterthenumberofelementsinthearray:");14scanf("%d",&count);1516/*dynamicallyallocatememory*/17array=calloc(count,sizeof(int));1819/*initializeelementsofarraywithuser-entereddata*/20for(i=0;i34/*functionprototype*/5voidreverseFile(FILE*inPtr,FILE*outPtr);67intmain(intargc,int*argv[])8{9FILE*inFilePtr;/*inputfilepointer*/10FILE*outFilePtr;/*outputfilepointer*/1112/*telluserifinvalidarguments*/13if(argc!=3){14printf("Usage:copyinfileoutfilen");15}/*endif*/16else{1718/*exitprogramifinputfilecannotbeopened*/19if((inFilePtr=fopen(argv[1],"r"))!=NULL){2021/*exitprogramifoutputfilecannotbeopened*/22if((outFilePtr=fopen(argv[2],"w"))!=NULL){23reverseFile(inFilePtr,outFilePtr);24}/*endif*/25else{26printf("File"%s"couldnotbeopenedn",argv[2]);27}/*endelse*/2829}/*endif*/30else{31printf("File"%s"couldnotbeopenedn",argv[1]);32}/*endelse*/3334}/*endelse*/3536return0;/*indicatesuccessfultermination*/3738}/*endmain*/3940/*functionthatwritescharactersinreverseorder*/41voidreverseFile(FILE*inPtr,FILE*outPtr)42{43intc;/*currentcharacter*/4445/*ifnotendoffile*/46if((c=fgetc(inPtr))!=EOF){47reverseFile(inPtr,outPtr);48}/*endif*/4950fputc(c,outPtr);/*writecharactertooutputfile*/51}/*endfunctionreverseFile*/.stnemugraenildnammocehtrofecnetnestsetasisihT©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter14OtherCTopics:Solutions45514.9Writeaprogramthatusesgotostatementstosimulateanestedloopingstructurethatprintsasquareofasterisksasfollows:****************Theprogramshoulduseonlythefollowingthreeprintfstatements:printf("*");printf("");printf("n");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com456OtherCTopics:SolutionsChapter14ANS:1/*Exercise14.9Solution*/2#include34intmain()5{6intsize;/*lengthofsquaresides*/7introw=0;/*numberofrows*/8intcol;/*numberofcolumns*/910/*obtainlengthofsideofsquarefromuser*/11printf("Enterthesidelengthofthesquare:");12scanf("%d",&size);1314start:/*label*/15++row;16printf("n");1718/*ifallrowshavebeenmadeendprogram*/19if(row>size){20gotoend;21}/*endif*/2223col=1;/*setcolumnvariabletofirstcharacterofline*/2425innerLoop:/*label*/2627/*ifallcolumnshavebeendisplayedreturntotopofloop*/28if(col>size){29gotostart;30}/*endif*/3132/*displaystarsandspacesinappropriatepositions*/33if(row==1||row==size||col==1||col==size){34printf("*");35}/*endif*/36else{37printf("");38}/*endelse*/3940++col;/*incrementcolumn*/41gotoinnerLoop;/*continuedisplayingcolumns*/4243end:/*label*/4445return0;/*indicatesuccessfultermination*/4647}/*endmain*/©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com15C++asa“BetterC”:SolutionsSOLUTIONS15.5WriteaC++programthatusesaninlinefunctioncircleAreatoprompttheuserfortheradiusofacircleandtocalcu-lateandprinttheareaofthatcircle.ANS:1//Exercise15.5Solution2#include34usingstd::cout;5usingstd::endl;6usingstd::cin;78doublepi=3.14159;//globalvariable910inlinedoublecircleArea(doubler){returnpi*r*r;}1112intmain()13{14doubleradius;1516cout<<"Entertheradiusofthecircle:";17cin>>radius;18cout<<"Theareaofthecircleis"<34usingstd::cout;5usingstd::endl;6usingstd::cin;78inttripleCallByValue(int);9voidtripleByReference(int&);1011intmain()12{13intvalue,&valueRef=value;1415cout<<"Enteraninteger:";16cin>>value;1718cout<<"nValuebeforecalltotripleCallByValue()is:"19<34usingstd::cout;5usingstd::endl;67template8voidminimum(Tvalue1,Tvalue2)//findthesmallestvalue9{10if(value1>value2)11cout<34usingstd::cout;5usingstd::endl;67template8voidmax(Tvalue1,Tvalue2,Tvalue3)//findthelargestvalue9{10if(value1>value2&&value1>value3)11cout<value1&&value2>value3)14cout<intsum(intnum1,intnum2,intnum3){returnnum1+num2+num3;}ANS:ThefunctionreturntypeandparametertypesshouldbeA.b)voidprintResults(intx,inty){cout<<"Thesumis"<Aproduct(Anum1,Anum2,Anum3){returnnum1*num2*num3;}ANS:Thekeywordclassisneededinthetemplatedeclarationtemplate.d)doublecube(int);intcube(int);ANS:Thesignaturesarenotdifferent.Overloadedfunctionsmusthavedifferentsignaturesmeaningthatthenameandparameterlistmustbedifferent.Ifonlyreturntypesdiffer,thecompilergeneratesanerrormessage.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com462C++asa“BetterC”:SolutionsChapter15©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com16C++ClassesandDataAbstraction:SolutionsSOLUTIONS16.3Whatisthepurposeofthescoperesolutionoperator?ANS:Thescoperesolutionoperatorisusedtospecifytheclasstowhichafunctionbelongs.Italsoresolvestheambiguitycausedbymultipleclasseshavingmemberfunctionsofthesamename.16.4Provideaconstructorthatiscapableofusingthecurrenttimefromthetimefunction—declaredintheCStandardLibraryheaderctime—toinitializeanobjectoftheTimeclass.ANS:1//p16_4.H2#ifndefp16_4_H3#definep16_4_H45classTime{6public:7Time();8voidsetHour(int);9voidsetMinute(int);10voidsetSecond(int);11intgetHour(void)const;12intgetMinute(void)const;13intgetSecond(void)const;14voidprintStandard(void)const;15private:16inthour;17intminute;18intsecond;19};2021#endif22//p16_4.cpp23//memberfunctiondefinitionsforp16_4.cpp24#include2526usingstd::cout;27©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com464C++ClassesandDataAbstraction:SolutionsChapter1628#include29#include"p16_4.h"3031Time::Time()32{33longinttotalTime;//timeinsecondssince197034intcurrentYear=1994-1970;//currentyear35doubletotalYear;//currenttimeinyears36doubletotalDay;//dayssincebeginningofyear37doubleday;//currenttimeindays38longdoubledivisor;//conversiondivisor39inttimeShift=7;//timereturnedbytime()is40//givenasthenumberofseconds41//elapsedsince1/1/70GMT.42//Dependingonthetimezone43//youarein,youmustshift44//thetimebyacertain45//numberofhours.Forthis46//problem,7hoursisthe47//currentshiftforEST.4849totalTime=time(NULL);50divisor=(60.0*60.0*24.0*365.0);51totalYear=totalTime/divisor-currentYear;52totalDay=365*totalYear;//leapyearsignored53day=totalDay-(int)totalDay;5455setHour(day*24+timeShift);56setMinute((day*24-(int)(day*24))*60);57setSecond((minute*60-(int)(minute*60))*60);58}5960voidTime::setHour(inth){hour=(h>=0&&h<24)?h:0;}6162voidTime::setMinute(intm){minute=(m>=0&&m<60)?m:0;}6364voidTime::setSecond(ints){second=(s>=0&&s<60)?s:0;}6566intTime::getHour()const{returnhour;}6768intTime::getMinute()const{returnminute;}6970intTime::getSecond()const{returnsecond;}7172voidTime::printStandard()const73{74cout<<((hour%12==0)?12:hour%12)<<":"75<<(minute<10?"0":"")<2122usingstd::cout;2324#include"p16_5.h"2526Complex::Complex(doublereal,doubleimaginary)27{28initialize(real,imaginary);29}3031voidComplex::addition(constComplex&a)32{33realPart+=a.realPart;34imaginaryPart+=a.imaginaryPart;35}3637voidComplex::subtraction(constComplex&s)38{39realPart-=s.realPart;40imaginaryPart-=s.imaginaryPart;41}4243voidComplex::printComplex(void)const44{45cout<<"("<5556usingstd::cout;57usingstd::endl;5859#include"p16_5.h"6061intmain(void)62{63Complexb(1,7),c(9,2);6465b.printComplex();66cout<<"+";67c.printComplex();68cout<<"=";69b.addition(c);70b.printComplex();7172cout<<"n";73b.initialize(10,1);//resetrealPartandimaginaryPart74c.initialize(11,5);75b.printComplex();76cout<<"-";77c.printComplex();78cout<<"=";79b.subtraction(c);80b.printComplex();81cout<2425usingstd::cout;2627#include"p16_6.h"2829RationalNumber::RationalNumber(intn,intd)30{31numerator=n;32denominator=d;33}3435RationalNumberRationalNumber::addition(constRationalNumber&a)36{37RationalNumbert;3839t.numerator=a.numerator*denominator+a.denominator*numerator;4041t.denominator=a.denominator*denominator;42t.reduction();4344returnt;45}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com468C++ClassesandDataAbstraction:SolutionsChapter164647RationalNumberRationalNumber::subtraction(constRationalNumber&s)48{49RationalNumbert;5051t.numerator=s.denominator*numerator-denominator*s.numerator;52t.denominator=s.denominator*denominator;53t.reduction();5455returnt;56}5758RationalNumberRationalNumber::multiplication(constRationalNumber&m)59{60RationalNumbert;6162t.numerator=m.numerator*numerator;63t.denominator=m.denominator*denominator;64t.reduction();6566returnt;67}6869RationalNumberRationalNumber::division(RationalNumber&v)70{71RationalNumbert;7273t.numerator=v.denominator*numerator;74t.denominator=denominator*v.numerator;75t.reduction();7677returnt;78}7980voidRationalNumber::printRational(void)const81{82if(denominator==0)83cout<<"nDIVIDEBYZEROERROR!!!n";84elseif(numerator==0)85cout<<0;86else87cout<denominator?numerator:denominator;9899intgcd=0;//greatestcommondivisor100for(intloop=2;loop<=largest;loop++)101if(numerator%loop==0&&denominator%loop==0)102gcd=loop;103104if(gcd!=0){105numerator/=gcd;106denominator/=gcd;107}108}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter16C++ClassesandDataAbstraction:Solutions469109//driverforP16_6.cpp110#include111112usingstd::cout;113114#include"p16_6.h"115116intmain(void)117{118RationalNumberc(1,3),d(7,8),x;119120c.printRational();121cout<<"+";122d.printRational();123x=c.addition(d);124cout<<"=";125x.printRational();126cout<<"n";127x.printRational();128cout<<"=";129x.printRationalF();130cout<<"nn";131132c.printRational();133cout<<"-";134d.printRational();135x=c.subtraction(d);136cout<<"=";137x.printRational();138cout<<"n";139x.printRational();140cout<<"=";141x.printRationalF();142cout<<"nn";143144c.printRational();145cout<<"x";146d.printRational();147x=c.multiplication(d);148cout<<"=";149x.printRational();150cout<<"n";151x.printRational();152cout<<"=";153x.printRationalF();154cout<<"nn";155156c.printRational();157cout<<"/";158d.printRational();159x=c.division(d);160cout<<"=";161x.printRational();162cout<<"n";163x.printRational();164cout<<"=";165x.printRationalF();166cout<<"n";167168return0;169}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com470C++ClassesandDataAbstraction:SolutionsChapter161/3+7/8=29/2429/24=1.208331/3-7/8=-13/24-13/24=-0.5416671/3x7/8=7/247/24=0.2916671/3/7/8=8/218/21=0.380952©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter16C++ClassesandDataAbstraction:Solutions47116.7CreateaclassRectangle.Theclasshasattributeslengthandwidth,eachofwhichdefaultsto1.Ithasmemberfunctionsthatcalculatetheperimeterandtheareaoftherectangle.Ithassetandgetfunctionsforbothlengthandwidth.Thesetfunc-tionsshouldverifythatlengthandwidthareeachfloating-pointnumberslargerthan0.0andlessthan20.0.ANS:1//P16_7.H2#ifndefP16_7_H3#defineP16_7_H45classRectangle{6public:7Rectangle(double=1.0,double=1.0);8doubleperimeter(void);9doublearea(void);10voidsetWidth(doublew);11voidsetLength(doublel);12doublegetWidth(void);13doublegetLength(void);14private:15doublelength;16doublewidth;17};1819#endif20//P16_7M.cpp21//memberfunctiondefinitionsforp16_7.cpp2223#include"p16_7.h"2425Rectangle::Rectangle(doublew,doublel)26{27setWidth(w);28setLength(l);29}3031doubleRectangle::perimeter(void)32{33return2*(width+length);34}3536doubleRectangle::area(void)37{38returnwidth*length;39}4041voidRectangle::setWidth(doublew)42{43width=w>0&&w<20.0?w:1.0;44}4546voidRectangle::setLength(doublel)47{48length=l>0&&l<20.0?l:1.0;49}5051doubleRectangle::getWidth(void){returnwidth;}5253doubleRectangle::getLength(void){returnlength;}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com472C++ClassesandDataAbstraction:SolutionsChapter1654//driverforp16_7.cpp55#include5657usingstd::cout;58usingstd::endl;59usingstd::ios;6061#include6263usingstd::setprecision;64usingstd::setiosflags;6566#include"p16_7.h"6768intmain()69{70Rectanglea,b(4.0,5.0),c(67.0,888.0);7172cout<20.0||p1[x]<0.0)?0.0:p1[x];52point1[y]=(p1[y]>20.0||p1[y]<0.0)?0.0:p1[y];53point2[x]=(p2[x]>20.0||p2[x]<0.0)?0.0:p2[x];54point2[y]=(p2[y]>20.0||p2[y]<0.0)?0.0:p2[y];55point3[x]=(p3[x]>20.0||p3[x]<0.0)?0.0:p3[x];56point3[y]=(p3[y]>20.0||p3[y]<0.0)?0.0:p3[y];57point4[x]=(p4[x]>20.0||p4[x]<0.0)?0.0:p4[x];©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com474C++ClassesandDataAbstraction:SolutionsChapter1658point4[y]=(p4[y]>20.0||p4[y]<0.0)?0.0:p4[y];5960//verifythatpointsformarectangle61if(p1[y]==p2[y]&&p1[x]==62p4[x]&&p2[x]==p3[x]&&p3[y]==p4[y])63{6465perimeter();66area();67square();68}69else70cout<<"Coordinatesdonotformarectangle!n";71}7273voidRectangle::perimeter(void)74{75doublel=fabs(point4[1]-point1[1]),76w=fabs(point2[0]-point1[0]);7778cout<w?l:w)80<<"t"<<"width="<<(l>w?w:l)81<<"nTheperimeteris:"<<2*(w+l)<<"n"82<3132usingstd::cout;33usingstd::ios;3435#include3637usingstd::setprecision;38usingstd::setiosflags;39usingstd::resetiosflags;4041#include4243#include"p16_9.h"4445Rectangle::Rectangle(double*a,double*b,double*c,double*d,46charx,chary)47{48setCoord(a,b,c,d);49setFillCharacter(x);50setPerimeterCharacter(y);51}5253voidRectangle::setCoord(double*p1,double*p2,54double*p3,double*p4)55{56//Arrangementofpoints57//p4.........p3©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter16C++ClassesandDataAbstraction:Solutions47758//..59//..60//p1.........p26162constintx=0,y=1;//addedforclarity6364//validateallpoints65point1[x]=(p1[x]>20.0||p1[x]<0.0)?0.0:p1[x];66point1[y]=(p1[y]>20.0||p1[y]<0.0)?0.0:p1[y];67point2[x]=(p2[x]>20.0||p2[x]<0.0)?0.0:p2[x];68point2[y]=(p2[y]>20.0||p2[y]<0.0)?0.0:p2[y];69point3[x]=(p3[x]>20.0||p3[x]<0.0)?0.0:p3[x];70point3[y]=(p3[y]>20.0||p3[y]<0.0)?0.0:p3[y];71point4[x]=(p4[x]>20.0||p4[x]<0.0)?0.0:p4[x];72point4[y]=(p4[y]>20.0||p4[y]<0.0)?0.0:p4[y];7374//verifythatpointsformarectangle75if(point1[y]==point2[y]&&point1[x]==point4[x]&&76point2[x]==point3[x]&&point3[y]==point4[y]){7778perimeter();79area();80square();81setValid(true);//validsetofpoints82}83else{84cout<<"Coordinatesdonotformarectangle!n";85setValid(false);//invalidsetofpoints86}87}8889voidRectangle::perimeter(void)90{91doublel=fabs(point4[1]-point1[1]),92w=fabs(point2[0]-point1[0]);9394cout<w?l:w)96<<"twidth="<<(l>w?w:l)97<<"nTheperimeteris:"<<2*(w+l)<<"n"98<=0.0;--y){124for(doublex=0.0;x<=25.0;++x){125if((point1[0]==x&&point1[1]==y)||126(point4[0]==x&&point4[1]==y)){©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com478C++ClassesandDataAbstraction:SolutionsChapter16127128//printhorizontalperimeterofrectangle129while(x<=point2[0]){130cout<=point1[0]))&&139point4[1]>=y&&point1[1]<=y){140cout<2223usingstd::cout;24usingstd::cin;2526#include2728usingstd::setw;2930#include"p16_11.h"3132TicTacToe::TicTacToe()33{34for(intj=0;j<3;++j)//initializeboard35for(intk=0;k<3;++k)36board[j][k]="";37}3839boolTicTacToe::validMove(intr,intc)40{41returnr>=0&&r<3&&c>=0&&c<3&&board[r][c]=="";42}4344//mustspecifythattypeStatusispartoftheTicTacToeclass.45//SeeChapter21foradiscussionofnamespaces.46TicTacToe::StatusTicTacToe::gameStatus(void)47{48inta;4950//checkforawinondiagonals51if(board[0][0]!=""&&board[0][0]==board[1][1]&&52board[0][0]==board[2][2])53returnWIN;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter16C++ClassesandDataAbstraction:Solutions48154elseif(board[2][0]!=""&&board[2][0]==55board[1][1]&&board[2][0]==board[0][2])56returnWIN;5758//checkforwininrows59for(a=0;a<3;++a)60if(board[a][0]!=""&&board[a][0]==61board[a][1]&&board[a][0]==board[a][2])62returnWIN;6364//checkforwinincolumns65for(a=0;a<3;++a)66if(board[0][a]!=""&&board[0][a]==67board[1][a]&&board[0][a]==board[2][a])68returnWIN;6970//checkforacompletedgame71for(intr=0;r<3;++r)72for(intc=0;c<3;++c)73if(board[r][c]=="")74returnCONTINUE;//gameisnotfinished7576returnDRAW;//gameisadraw77}7879voidTicTacToe::printBoard(void)80{81cout<<"012nn";8283for(intr=0;r<3;++r){84cout<(board[r][c]);8889if(c!=2)90cout<<"|";91}9293if(r!=2)94cout<<"n____|____|____"95<<"n||n";96}9798cout<<"nn";99}100101voidTicTacToe::makeMove(void)102{103printBoard();104105while(true){106if(xoMove("X"))107break;108elseif(xoMove("O"))109break;110}111}112113boolTicTacToe::xoMove(intsymbol)114{115intx,y;116117do{118cout<<"Player"<(symbol)119<<"entermove:";120cin>>x>>y;121cout<<"n";122}while(!validMove(x,y));©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com482C++ClassesandDataAbstraction:SolutionsChapter16123124board[x][y]=symbol;125printBoard();126StatusxoStatus=gameStatus();127128if(xoStatus==WIN){129cout<<"Player"<(symbol)<<"wins!n";130returntrue;131}132elseif(xoStatus==DRAW){133cout<<"Gameisadraw.n";134returntrue;135}136else//CONTINUE137returnfalse;138}139//driverforp16_11.cpp140#include"p16_11.h"141142intmain()143{144TicTacToeg;145g.makeMove();146147return0;148}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter16C++ClassesandDataAbstraction:Solutions4830120||____|____|____||1||____|____|____||2||PlayerXentermove:000120X||____|____|____||1||____|____|____||2||...PlayerOentermove:020120X||O____|____|____||1X|O|____|____|____||2||PlayerXentermove:200120X||O____|____|____||1X|O|____|____|____||2X||PlayerXwins!©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com484C++ClassesandDataAbstraction:SolutionsChapter16©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com17C++Classes:PartII:SolutionsSOLUTIONS17.3CompareandcontrastdynamicmemoryallocationusingtheC++’snewanddeleteoperators,withdynamicmemoryal-locationusingtheCStandardLibraryfunctionsmallocandfree.ANS:InC,dynamicmemoryallocationrequiresfunctioncallstomallocandfree.Also,mallocmustbetoldtheexactnumberofbytestoallocate(normallythisisaccomplishedwiththesizeofoperator),thenitreturnsavoidpointer.C++usesoperatorsnewanddelete.Thenewoperatorautomaticallydeterminesthenumberofbytestoallocateandreturnsapointertotheappropriatetype.Thedeleteoperatorguaranteesacalltothedestructorfortheobjects(s)begindeleted.17.4ExplainthenotionoffriendshipinC++.Explainthenegativeaspectsoffriendshipasdescribedinthetext.ANS:Functionsthataredeclaredasfriendsofaclasshaveaccesstothatclass’sprivateandprotectedmembers.Somepeopleintheobject-orientedprogrammingcommunityprefernottousefriendfunctionsbecausetheybreaktheencapsulationofaclass--i.e.,theyallowdirectaccesstoaclass’simplementationdetailsthataresupposedtobehidden.17.5CanacorrectTimeclassdefinitionincludebothofthefollowingconstructors?Ifnot,explainwhynot.Time(inth=0,intm=0,ints=0);Time();ANS:No,becausethereisambiguitybetweenthetwoconstructors.Whenacallismadetothedefaultconstructor,thecompilercannotdeterminewhichonetousebecausetheybothcanbecalledwithnoarguments.17.6Whathappenswhenareturntype,evenvoid,isspecifiedforaconstructorordestructor?ANS:Acompilersyntaxerroroccurs.Noreturntypescanbespecifiedforconstructors.17.7CreateaDateclasswiththefollowingcapabilities:a)OutputthedateinmultipleformatssuchasDDDYYYYMM/DD/YYJune14,1992b)UseoverloadedconstructorstocreateDateobjectsinitializedwithdatesoftheformatsinpart(a).c)CreateaDateconstructorthatreadsthesystemdateusingthestandardlibraryfunctionsoftheheaderandsetstheDatemembers.InChapter18,wewillbeabletocreateoperatorsfortestingtheequalityoftwodatesandforcomparingdatestodetermineifonedateispriorto,orafter,another.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com486C++Classes:PartII:SolutionsChapter17ANS:1//P17_07.H2#ifndefp17_07_H3#definep17_07_H45#include6#include78classDate{9public:10Date();11Date(int,int);12Date(int,int,int);13Date(char*,int,int);14voidsetMonth(int);15voidsetDay(int);16voidsetYear(int);17voidprintDateSlash(void)const;18voidprintDateMonth(void)const;19voidprintDateDay(void)const;20constchar*monthName(void)const;21boolleapYear(void)const;22intdaysOfMonth(void)const;23voidconvert1(int);24intconvert2(void)const;25voidconvert3(constchar*const);26constchar*monthList(int)const;27intdays(int)const;28private:29intday;30intmonth;31intyear;32};3334#endif1//P17_07M.cpp2//memberfunctiondefinitionsforp17_07.cpp3#include45usingstd::cout;67#include89#include"p17_07.h"1011//Dateconstructor12Date::Date()13{14longinttotalTime;15doubletotalYear;16longdoubledivisor;1718totalTime=time(NULL);//timeinsecondssince197019divisor=(60.0*60.0*24.0*365.25);//numberofsecondsinayear20totalYear=totalTime/divisor+1970;21year=(int)totalYear;22totalYear-=year;23day=(int)(365*totalYear);24month=1;2526while(day-days(month+1)>0)27day-=days(month++);28}29©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter17C++Classes:PartII:Solutions48730//Dateconstructorthatusesdayofyearandyear31Date::Date(intddd,intyyyy)32{33setYear(yyyy);34convert1(ddd);//converttomonthandday35}3637//Dateconstructorthatusesmonth,dayandyear38Date::Date(intmm,intdd,intyy)39{40setYear(yy+1900);41setMonth(mm);42setDay(dd);43}4445//Dateconstructorthatusesmonthname,dayandyear46Date::Date(char*mPtr,intdd,intyyyy)47{48setYear(yyyy);49convert3(mPtr);50setDay(dd);51}5253//Settheday54voidDate::setDay(intd)55{day=d>=1&&d<=daysOfMonth()?d:1;}5657//Setthemonth58voidDate::setMonth(intm){month=m>=1&&m<=12?m:1;}5960//Settheyear61voidDate::setYear(inty){year=y>=1900&&y<=1999?y:1900;}6263//PrintDateintheform:mm/dd/yyyy64voidDate::printDateSlash(void)const65{cout<366)//checkforinvalidday97ddd=1;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com488C++Classes:PartII:SolutionsChapter179899setMonth(1);100101intm=1;102103for(;m<13&&(dayTotal+daysOfMonth())159160usingstd::cout;161usingstd::endl;162163#include"p17_07.h"164165intmain()166{167Dated1(7,4,98),d2(86,1999),168d3,d4("September",1,1998);169170d1.printDateSlash();//formatm/dd/yy171d2.printDateSlash();172d3.printDateSlash();173d4.printDateSlash();174cout<<"n";175176d1.printDateDay();//formatdddyyyy177d2.printDateDay();178d3.printDateDay();179d4.printDateDay();180cout<<"n";181182d1.printDateMonth();//format"month"d,yyyy183d2.printDateMonth();184d3.printDateMonth();185d4.printDateMonth();186cout<=0?b:0;}8voidcalculateMonthlyInterest(void);9staticvoidmodifyInterestRate(double);10voidprintBalance(void)const;11private:12doublesavingsBalance;13staticdoubleannualInterestRate;14};1516#endif17//P17.08M.cpp18//Memberfunctiondefintionsforp17_08.cpp19#include"p17_08.h"20#include2122usingstd::cout;23usingstd::ios;2425#include2627usingstd::setprecision;28usingstd::setiosflags;29usingstd::resetiosflags;3031//initializestaticdatamember32doubleSavingsAccount::annualInterestRate=0.0;3334voidSavingsAccount::calculateMonthlyInterest(void)35{savingsBalance+=savingsBalance*(annualInterestRate/12.0);}3637voidSavingsAccount::modifyInterestRate(doublei)38{annualInterestRate=(i>=0&&i<=1.0)?i:0.03;}3940voidSavingsAccount::printBalance(void)const41{42cout<4849usingstd::cout;50usingstd::endl;5152#include5354usingstd::setw;5556#include"p17_08.h"5758intmain()59{60SavingsAccountsaver1(2000.0),saver2(3000.0);6162SavingsAccount::modifyInterestRate(.03);6364cout<<"nOutputmonthlybalancesforoneyearat.03"65<<"nBalances:Saver1";66saver1.printBalance();67cout<<"tSaver2";68saver2.printBalance();6970for(intmonth=1;month<=12;++month){71saver1.calculateMonthlyInterest();72saver2.calculateMonthlyInterest();7374cout<<"nMonth"<>.18.7TheC++operatorsthatcannotbeoverloadedare,,,and.ANS:sizeof,.,?:,.*,and::.18.8(Project)C++isanevolvinglanguage,andnewlanguagesarealwaysbeingdeveloped.WhatadditionaloperatorswouldyourecommendaddingtoC++ortoafuturelanguagelikeC++thatwouldsupportbothproceduralprogrammingandobject-ori-entedprogramming?Writeacarefuljustification.YoumightconsidersendingyoursuggestionstotheANSIC++Committeeorthenewsgroupcomp.std.c++.18.9Overloadthesubscriptoperatortoreturnthelargestelementofacollection,thesecondlargest,thethirdlargest,etc.18.10ConsiderclassComplexshowninFig.18.5.Theclassenablesoperationsonso-calledcomplexnumbers.Thesearenum-bersoftheformrealPart+imaginaryPart*iwhereihasthevalue:–1a)Modifytheclasstoenableinputandoutputofcomplexnumbersthroughtheoverloaded>>and<2223usingstd::cout;2425#include"complex1.h"2627//Constructor28Complex::Complex(doubler,doublei)29:real(r),imaginary(i){}3031//Overloadedadditionoperator32ComplexComplex::operator+(constComplex&operand2)const33{34returnComplex(real+operand2.real,35imaginary+operand2.imaginary);36}3738//Overloadedsubtractionoperator39ComplexComplex::operator-(constComplex&operand2)const40{41returnComplex(real-operand2.real,42imaginary-operand2.imaginary);43}4445//Overloaded=operator46constComplex&Complex::operator=(constComplex&right)47{48real=right.real;49imaginary=right.imaginary;50return*this;//enablescascading51}5253//DisplayaComplexobjectintheform:(a,b)54voidComplex::print()const55{cout<<"("<5960usingstd::cout;61usingstd::endl;6263#include"complex1.h"6465intmain()66{67Complexx,y(4.3,8.2),z(3.3,1.1);6869cout<<"x:";70x.print();71cout<<"ny:";72y.print();73cout<<"nz:";74z.print();7576x=y+z;77cout<<"nnx=y+z:n";78x.print();79cout<<"=";80y.print();81cout<<"+";82z.print();8384x=y-z;85cout<<"nnx=y-z:n";86x.print();87cout<<"=";88y.print();89cout<<"-";90z.print();91cout<56usingstd::ostream;7usingstd::istream;8©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com496C++OperatorOverloading:SolutionsChapter189classComplex{10friendostream&operator<<(ostream&,constComplex&);11friendistream&operator>>(istream&,Complex&);12public:13Complex(double=0.0,double=0.0);//constructor14Complexoperator+(constComplex&)const;//addition15Complexoperator-(constComplex&)const;//subtraction16Complexoperator*(constComplex&)const;//multiplication17Complex&operator=(constComplex&);//assignment18booloperator==(constComplex&)const;19booloperator!=(constComplex&)const;20private:21doublereal;//realpart22doubleimaginary;//imaginarypart23};2425#endif26//P18_10M.cpp27//memberfunctiondefinitionsforp18_10.cpp28#include"p18_10.h"29#include3031usingstd::ostream;32usingstd::istream;3334//Constructor35Complex::Complex(doubler,doublei)36{37real=r;38imaginary=i;39}4041//Overloadedadditionoperator42ComplexComplex::operator+(constComplex&operand2)const43{44Complexsum;4546sum.real=real+operand2.real;47sum.imaginary=imaginary+operand2.imaginary;48returnsum;49}5051//Overloadedsubtractionoperator52ComplexComplex::operator-(constComplex&operand2)const53{54Complexdiff;5556diff.real=real-operand2.real;57diff.imaginary=imaginary-operand2.imaginary;58returndiff;59}6061//Overloadedmultiplicationoperator62ComplexComplex::operator*(constComplex&operand2)const63{64Complextimes;6566times.real=real*operand2.real+imaginary*operand2.imaginary;67times.imaginary=real*operand2.imaginary+imaginary*operand2.real;68returntimes;69}7071//Overloaded=operator72Complex&Complex::operator=(constComplex&right)73{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter18C++OperatorOverloading:Solutions49774real=right.real;75imaginary=right.imaginary;76return*this;//enablesconcatenation77}7879boolComplex::operator==(constComplex&right)const80{returnright.real==real&&right.imaginary==imaginary?true:false;}8182boolComplex::operator!=(constComplex&right)const83{return!(*this==right);}8485ostream&operator<<(ostream&output,constComplex&complex)86{87output<>(istream&input,Complex&complex)92{93input>>complex.real;94input.ignore(3);//skipspacesand+95input>>complex.imaginary;96input.ignore(2);9798returninput;99}100//driverforp18_10.cpp101#include102103usingstd::cout;104usingstd::cin;105106#include"p18_10.h"107108intmain()109{110Complexx,y(4.3,8.2),z(3.3,1.1),k;111112cout<<"Enteracomplexnumberintheform:a+bin?";113cin>>k;114115cout<<"x:"<6usingstd::ostream;78classPoint{9friendostream&operator<<(ostream&,constPoint&);10public:11Point(doublea=0,doubleb=0){setPoint(a,b);}12voidsetPoint(double,double);13voidprint(void)const;14doublegetX(void)const{returnx;}15doublegetY(void)const{returny;}16private:17doublex,y;18};1920#endif21//P19_08PM.cpp22//MemberfunctionsforclassPoint23#include2425usingstd::cout;26usingstd::ostream;2728#include"p19_08.h"2930voidPoint::setPoint(doublea,doubleb)31{32x=a;33y=b;34}3536ostream&operator<<(ostream&output,constPoint&p)37{38p.print();39returnoutput;40}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter19C++Inheritance:Solutions5014142voidPoint::print(void)const43{cout<<"["<6768usingstd::cout;69usingstd::ios;7071#include7273usingstd::setprecision;74usingstd::setiosflags;75usingstd::resetiosflags;7677#include"P19_08c.h"7879Circle::Circle(doubler,doublea,doubleb):pointObject(a,b)80{setRadius(r);}8182doubleCircle::area(void)const83{return3.14159*getRadius()*getRadius();}8485ostream&operator<<(ostream&output,constCircle&c)86{87c.print();88returnoutput;89}9091voidCircle::print(void)const92{93cout<<"Center=";94pointObject.print();95cout<<";Radius="<123124usingstd::cout;125usingstd::ostream;126127#include"p19_08cy.h"128129Cylinder::Cylinder(doubleh,doubler,doublex,doubley)130:circleObject(r,x,y){height=h;}131132doubleCylinder::area(void)const133{return2*circleObject.area()+2*3.14159*134circleObject.getRadius()*getHeight();}135136ostream&operator<<(ostream&output,constCylinder&c)137{138c.print();139returnoutput;140}141142doubleCylinder::volume(void)const143{returncircleObject.area()*getHeight();}144145voidCylinder::print(void)const146{147circleObject.print();148cout<<";Height="<152153usingstd::cout;154usingstd::endl;155156#include"P19_08.h"157#include"P19_08c.h"158#include"P19_08cy.h"159160intmain()161{162Pointp(1.1,8.5);163Circlec(2.0,6.4,9.8);164Cylindercyl(5.7,2.5,1.2,2.3);165166cout<<"Point:"<6usingstd::ostream;78classPoint{9friendostream&operator<<(ostream&,constPoint&);10public:11Point(double=0,double=0);12voidsetPoint(double,double);13voidprint(void)const;14doublegetX(void)const{returnx;}15doublegetY(void)const{returny;}16private:17doublex,y;18};1920#endif21//P19_11PM.cpp22//memberfunctiondefintionsforclassPoint23#include2425usingstd::cout;26usingstd::ios;27usingstd::ostream;2829#include3031usingstd::setprecision;32usingstd::setiosflags;33usingstd::resetiosflags;3435#include"p19_11.h"3637Point::Point(doublea,doubleb){setPoint(a,b);}3839voidPoint::setPoint(doublea,doubleb)40{41x=a;42y=b;43}4445ostream&operator<<(ostream&output,constPoint&p)46{47output<<"Thepointis:";48p.print();49returnoutput;50}5152voidPoint::print(void)const53{54cout<65usingstd::ostream;6667classQuadrilateral{68friendostream&operator<<(ostream&,Quadrilateral&);69public:70Quadrilateral(double=0,double=0,double=0,double=0,double=0,71double=0,double=0,double=0);72voidprint(void)const;73protected:74Pointp1;75Pointp2;76Pointp3;77Pointp4;78};7980#endif81//P19_11QM.cpp82//memberfunctionsforclassQuadrilateral83#include"p19_11q.h"8485#include86usingstd::cout;87usingstd::ostream;8889Quadrilateral::Quadrilateral(doublex1,doubley1,doublex2,doubley2,90doublex3,doubley3,doublex4,doubley4)91:p1(x1,y1),p2(x2,y2),p3(x3,y3),p4(x4,y4){}9293ostream&operator<<(ostream&output,Quadrilateral&q)94{95output<<"CoordinatesofQuadrilateralare:n";96q.print();97output<<"n";98returnoutput;99}100101voidQuadrilateral::print(void)const102{103cout<<"("<114usingstd::ostream;115116classTrapazoid:publicQuadrilateral{117friendostream&operator<<(ostream&,Trapazoid&);118public:119Trapazoid(double=0,double=0,double=0,double=0,double=0,120double=0,double=0,double=0,double=0);121voidprint(void)const;122voidsetHeight(doubleh){height=h;}123doublegetHeight(void)const{returnheight;}124private:125doubleheight;126};127128#endif129//P19_11TM.cpp130//memberfunctiondefinitionsforclassTrapazoid131#include"p19_11t.h"132133#include134135usingstd::cout;136usingstd::ostream;137138Trapazoid::Trapazoid(doubleh,doublex1,doubley1,doublex2,doubley2,139doublex3,doubley3,doublex4,doubley4)140:Quadrilateral(x1,y1,x2,y2,x3,y3,x4,y4)141{setHeight(h);}142143ostream&operator<<(ostream&out,Trapazoid&t)144{145out<<"TheCoordinatesoftheTrapazoidare:n";146t.print();147returnout;148}149150voidTrapazoid::print(void)const151{152Quadrilateral::print();153cout<<"Heightis:"<161usingstd::ostream;162163classParallelogram:publicQuadrilateral{164friendostream&operator<<(ostream&,Parallelogram&);165public:166Parallelogram(double=0,double=0,double=0,double=0,167double=0,double=0,double=0,double=0);168voidprint(void)const;169private:170//noprivatedatamembers171};172173#endif174//P19_11PAM.cpp175#include"p19_11q.h"176#include"p19_11pa.h"177178#include179usingstd::ostream;180181Parallelogram::Parallelogram(doublex1,doubley1,doublex2,doubley2,182doublex3,doubley3,doublex4,doubley4)183:Quadrilateral(x1,y1,x2,y2,x3,y3,x4,y4){}184185ostream&operator<<(ostream&out,Parallelogram&pa)186{187out<<"ThecoordinatesoftheParallelogramare:n";188pa.print();189returnout;190}191192voidParallelogram::print(void)const193{Quadrilateral::print();}194//P19_11R.H195#ifndefP19_11R_H196#defineP19_11R_H197#include"p19_11pa.h"198199#include200usingstd::ostream;201202classRectangle:publicParallelogram{203friendostream&operator<<(ostream&,Rectangle&);204public:205Rectangle(double=0,double=0,double=0,double=0,206double=0,double=0,double=0,double=0);207voidprint(void)const;208private:209//noprivatedatamembers210};211212#endif©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com508C++Inheritance:SolutionsChapter19213//P19_11RM.cpp214#include"p19_11r.h"215#include"p19_11pa.h"216217#include218usingstd::ostream;219220Rectangle::Rectangle(doublex1,doubley1,doublex2,doubley2,221doublex3,doubley3,doublex4,doubley4)222:Parallelogram(x1,y1,x2,y2,x3,y3,x4,y4){}223224ostream&operator<<(ostream&out,Rectangle&r)225{226out<<"nThecoordinatesoftheRectangleare:n";227r.print();228returnout;229}230231voidRectangle::print(void)const232{Parallelogram::print();}233//P19_11RH.H234#ifndefP19_11RH_H235#defineP19_11RH_H236#include"p19_11pa.h"237238#include239usingstd::ostream;240241classRhombus:publicParallelogram{242friendostream&operator<<(ostream&,Rhombus&);243public:244Rhombus(double=0,double=0,double=0,double=0,double=0,245double=0,double=0,double=0);246voidprint(void)const{Parallelogram::print();}247private:248//noprivatedatamembers249};250251#endif252//P19_11HM.cpp253#include"p19_11rh.h"254#include"p19_11pa.h"255256#include257usingstd::ostream;258259Rhombus::Rhombus(doublex1,doubley1,doublex2,doubley2,260doublex3,doubley3,doublex4,doubley4)261:Parallelogram(x1,y1,x2,y2,x3,y3,x4,y4){}262263ostream&operator<<(ostream&out,Rhombus&r)264{265out<<"nThecoordinatesoftheRhombusare:n";266r.print();267returnout;268}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter19C++Inheritance:Solutions509269//P19_11S.H270#ifndefP19_11S_H271#defineP19_11S_H272#include"p19_11pa.h"273274#include275usingstd::ostream;276277classSquare:publicParallelogram{278friendostream&operator<<(ostream&,Square&);279public:280Square(double=0,double=0,double=0,double=0,281double=0,double=0,double=0,double=0);282voidprint(void)const{Parallelogram::print();}283private:284//noprivatedatamembers285};286287#endif288//P19_11SM.cpp289#include"p19_11s.h"290#include"p19_11pa.h"291292#include293usingstd::ostream;294295Square::Square(doublex1,doubley1,doublex2,doubley2,296doublex3,doubley3,doublex4,doubley4)297:Parallelogram(x1,y1,x2,y2,x3,y3,x4,y4){}298299ostream&operator<<(ostream&out,Square&s)300{301out<<"nThecoordinatesoftheSquareare:n";302s.print();303returnout;304}305//P19_11.cpp306#include"p19_11.h"307#include"p19_11q.h"308#include"p19_11t.h"309#include"p19_11pa.h"310#include"p19_11rh.h"311#include"p19_11r.h"312#include"p19_11s.h"313314#include315usingstd::cout;316usingstd::endl;317318intmain()319{320//NOTE:Allcoordinatesareassumedtoformthepropershapes321322//Aquadrilateralisafour-sidedpolygon323Quadrilateralq(1.1,1.2,6.6,2.8,6.2,9.9,2.2,7.4);324//Atrapazoidisaquadrilateralhavingtwoandonlytwoparallelsides325Trapazoidt(5.0,0.0,0.0,10.0,0.0,8.0,5.0,3.3,5.0);326//Aparallelogramisaquadrilateralwhoseoppositesidesareparallel327Parallelogramp(5.0,5.0,11.0,5.0,12.0,20.0,6.0,20.0);328//Arhombusisanequilateralparallelogram329Rhombusrh(0.0,0.0,5.0,0.0,8.5,3.5,3.5,3.5);330//Arectangleisanequiangularparallelogram©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com510C++Inheritance:SolutionsChapter19331Rectangler(17.0,14.0,30.0,14.0,30.0,28.0,17.0,28.0);332//Asquareisanequiangularandequilateralparallelogram333Squares(4.0,0.0,8.0,0.0,8.0,4.0,4.0,4.0);334335cout<7usingstd::ostream;89classShape{10friendostream&operator<<(ostream&,Shape&);11public:12Shape(double=0,double=0);13doublegetCenterX()const;14doublegetCenterY()const;15virtualvoidprint()const=0;16protected:17doublexCenter;18doubleyCenter;19};2021#endif22//SHAPE.CPP23//MemberandfrienddefinitionsforShape24#include"shape.h"2526Shape::Shape(doublex,doubley)27{28xCenter=x;29yCenter=y;30}3132doubleShape::getCenterX()const{returnxCenter;}3334doubleShape::getCenterY()const{returnyCenter;}3536ostream&operator<<(ostream&out,Shape&s)37{38s.print();39returnout;40}41//TWODIM.H42//DefnitionofclassTwoDimensionalShape43#ifndefTWODIM_H44#defineTWODIM_H4546#include"shape.h"4748classTwoDimensionalShape:publicShape{49public:50TwoDimensionalShape(doublex,doubley):Shape(x,y){}51virtualdoublearea()const=0;52};5354#endif©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com514C++VirtualFunctionsandPolymorphism:SolutionsChapter2055//THREEDIM.H56//DefnitionofclassThreeDimensionalShape57#ifndefTHREEDIM_H58#defineTHREEDIM_H5960#include"shape.h"6162classThreeDimensionalShape:publicShape{63public:64ThreeDimensionalShape(doublex,doubley):Shape(x,y){}65virtualdoublearea()const=0;66virtualdoublevolume()const=0;67};6869#endif70//CIRCLE.H71//DefinitionofclassCircle72#ifndefCIRCLE_H73#defineCIRCLE_H7475#include"twodim.h"7677classCircle:publicTwoDimensionalShape{78public:79Circle(double=0,double=0,double=0);80doublegetRadius()const;81doublearea()const;82voidprint()const;83private:84doubleradius;85};8687#endif88//CIRCLE.CPP89//MemberfunctiondefinitionsforCircle90#include"circle.h"9192#include93usingstd::cout;9495Circle::Circle(doubler,doublex,doubley)96:TwoDimensionalShape(x,y){radius=r>0?r:0;}9798doubleCircle::getRadius()const{returnradius;}99100doubleCircle::area()const{return3.14159*radius*radius;}101102voidCircle::print()const103{104cout<<"Circlewithradius"<130usingstd::cout;131132Square::Square(doubles,doublex,doubley)133:TwoDimensionalShape(x,y){sideLength=s>0?s:0;}134135doubleSquare::getSideLength()const{returnsideLength;}136137doubleSquare::area()const{returnsideLength*sideLength;}138139voidSquare::print()const140{141cout<<"Squarewithsidelength"<168usingstd::cout;169170Cube::Cube(doubles,doublex,doubley)171:ThreeDimensionalShape(x,y){sideLength=s>0?s:0;}172173doubleCube::area()const{return6*sideLength*sideLength;}174175doubleCube::volume()const176{returnsideLength*sideLength*sideLength;}177178doubleCube::getSideLength()const{returnsideLength;}179180voidCube::print()const181{182cout<<"Cubewithsidelength"<210usingstd::cout;211212Square::Square(doubles,doublex,doubley)213:TwoDimensionalShape(x,y){sideLength=s>0?s:0;}214215doubleSquare::getSideLength()const{returnsideLength;}216217doubleSquare::area()const{returnsideLength*sideLength;}218219voidSquare::print()const220{221cout<<"Squarewithsidelength"<227228usingstd::cout;229usingstd::endl;230usingstd::cin;231usingstd::ios;232233#include"circle.h"234#include"square.h"235#include"sphere.h"236#include"cube.h"237238intmain()239{240Circlecir(3.5,6,9);241Squaresqr(12,2,2);242Spheresph(5,1.5,4.5);243Cubecub(2.2);244Shape*ptr[4]={&cir,&sqr,&sph,&cub};245246for(intx=0;x<4;++x)247cout<<*(ptr[x])<<"n";248249return0;250}Circlewithradius3.5;centerat(6,9);areaof38.4845Squarewithsidelength12;centerat(2,2);areaof144Spherewithradius5;centerat(1.5,4.5);areaof314.159;volumeof523.598Cubewithsidelength2.2;centerat(0,0);areaof29.04;volumeof10.648©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com518C++VirtualFunctionsandPolymorphism:SolutionsChapter20©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com21C++StreamInput/Output:SolutionsEXERCISES21.6Writeastatementforeachofthefollowing:a)Printinteger40000left-justifiedina15-digitfield.ANS:cout<>state;c)Print200withandwithoutasign.ANS:cout<34usingstd::cout;5usingstd::endl;6usingstd::cin;7usingstd::ios;89#include1011usingstd::setiosflags;12usingstd::hex;13usingstd::oct;14usingstd::dec;1516intmain()17{18intinteger;1920cout<<"Enteraninteger:";21cin>>integer;2223cout<>setiosflags(ios::showbase)>>oct>>integer;2930cout<>setiosflags(ios::showbase)>>hex>>integer;3637cout<34usingstd::cout;56intmain()7{8char*string="test";910cout<<"Valueofstringis:"11<(string)is:"14<(string)<<"n";1516//TheFollowinggenerateerrors.17//reinterpret_castwillallowthistypeofcasting1819/*cout<<"Valueofstatic_cast(string)is:"20<(string)<<"n";2122cout<<"Valueofstatic_cast(string)is:"23<(string)<<"n";2425cout<<"Valueofstatic_cast(string)is:"26<(string)<<"n";2728cout<<"Valueofstatic_cast(string)is:"29<(string)<<"n";3031cout<<"Valueofstatic_cast(string)is:"32<(string)33*/3435return0;36}Valueofstringis:testValueofstatic_cast(string)is:0041A178©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com522C++StreamInput/Output:SolutionsChapter2121.9Writeaprogramtotesttheresultsofprintingtheintegervalue12345andthefloating-pointvalue1.2345invarious-sizefields.Whathappenswhenthevaluesareprintedinfieldscontainingfewerdigitsthanthevalues?ANS:1//Exercise21.9Solution2#include34usingstd::cout;56#include78usingstd::setw;910intmain()11{12intx=12345;13doubley=1.2345;1415for(intloop=0;loop<=10;++loop)16cout<34usingstd::cout;5usingstd::endl;6usingstd::ios;78#include910usingstd::setw;11usingstd::setprecision;12usingstd::setiosflags;1314intmain()15{16doublex=100.453627;1718cout<34usingstd::cout;5usingstd::endl;6usingstd::cin;78#include910usingstd::setw;1112#include1314constintSIZE=80;1516intmain()17{18charstring[SIZE];19intstringLength;2021cout<<"Enterastring:";22cin>>string;2324stringLength=strlen(string);2526cout<<"thelengthofthestringis"<34usingstd::cout;5usingstd::ios;67#include89usingstd::setw;10usingstd::setprecision;11usingstd::setiosflags;12usingstd::resetiosflags;1314intmain()15{16doublecelsius;1718cout<34usingstd::cout;5usingstd::cin;67constintSIZE=80;89intmain()10{11charstring[SIZE];1213for(intk=0;k<3;++k){14cout<<"Enterastring:";15cin>>string;16cout<<"Stringis"<>functionwillneedtobeentirelyrecoded.a)Inputtheentirephonenumberintoanarray.Testthatthepropernumberofcharactershasbeenentered.Thereshouldbeatotalof14charactersreadforaphonenumberoftheform(800)555-1212.Usethestreammemberfunctioncleartosetios::failbitforimproperinput.b)Theareacodeandexchangedonotbeginwith0or1.Testthefirstdigitoftheareacodeandexchangeportionsofthephonenumbertobesurethatneitherbeginswith0or1.Usestreammemberfunctioncleartosetios::failbitforimproperinput.c)Themiddledigitofanareacodeusedtoalwaysbe0or1(althoughthishaschangedrecently).Testthemiddledigitforavalueof0or1.Usethestreammemberfunctioncleartosetios::failbitforimproperinput.Ifnoneoftheaboveoperationsresultsinios::failbitbeingsetforimproperinput,copythethreepartsofthetelephonenumberintotheareaCode,exchangeandlinemembersofthePhoneNumberobject.Inthemainprogram,ifios::fail-bithasbeensetontheinput,havetheprogramprintanerrormessageandendratherthanprintthephonenumber.ANS:1//P21_14.H2#ifndefP21_14_H3#defineP21_14_H45#include67usingstd::cout;8usingstd::endl;9usingstd::cin;10usingstd::ios;11usingstd::ostream;12usingstd::istream;13usingstd::cerr;1415#include16usingstd::string;1718#include1920classPhoneNumber{21friendostream&operator<<(ostream&,PhoneNumber&);22friendistream&operator>>(istream&,PhoneNumber&);23public:24PhoneNumber();25private:26charphone[15];27charareaCode[4];28charexchange[4];29charline[5];30};3132#endif33//P21_14M.cpp34//memberfunctiondefinitiondefinitionforp21_14.cpp35#include"p21_14.h"3637PhoneNumber::PhoneNumber()38{39phone[0]="";40areaCode[0]="";41exchange[0]="";42line[0]="";43}4445ostream&operator<<(ostream&output,PhoneNumber&number)46{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com528C++StreamInput/Output:SolutionsChapter2147output<<"("<>(istream&input,PhoneNumber&number)54{55cin.getline(number.phone,15);5657if(strlen(number.phone)!=14)58cin.clear(ios::failbit);5960if(number.phone[1]=="0"||number.phone[6]=="0"||61number.phone[1]=="1"||number.phone[6]=="1")62cin.clear(ios::failbit);6364if(number.phone[2]!="0"&&number.phone[2]!="1")65cin.clear(ios::failbit);6667if(!cin.fail()){68intloop=0;69for(;loop<=2;++loop){70number.areaCode[loop]=number.phone[loop+1];71number.exchange[loop]=number.phone[loop+6];72}7374number.areaCode[loop]=number.exchange[loop]="";7576for(loop=0;loop<=3;++loop)77number.line[loop]=number.phone[loop+10];7879number.line[loop]="";80}81else{82cerr<<"Invalidphonenumberentered.n";83exit(1);84}8586returninput;87}88//driverforp21_14.cpp89#include"p21_14.h"9091intmain()92{93PhoneNumbertelephone;9495cout<<"Enteraphonenumberintheform(123)456-7890:n";96cin>>telephone;9798cout<<"Thephonenumberenteredwas:"<>telephone;102103return0;104}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter21C++StreamInput/Output:Solutions529Enteraphonenumberintheform(123)456-7890:(800)987-4567Thephonenumberenteredwas:(800)987-4567Nowenteraninvalidphonenumber:abcdefghijkInvalidphonenumberentered.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com530C++StreamInput/Output:SolutionsChapter2121.15Writeaprogramthataccomplisheseachofthefollowing:a)Createtheuser-definedclassPointthatcontainstheprivateintegerdatamembersxCoordinateandyCoordinateanddeclaresstream-insertionandstream-extractionoverloadedoperatorfunctionsasfriendsoftheclass.b)Definethestream-insertionandstream-extractionoperatorfunctions.Thestream-extractionoperatorfunctionshoulddetermineifthedataenteredarevaliddata,andifnot,itshouldsettheios::failbittoindicateimproperinput.Thestream-insertionoperatorshouldnotbeabletodisplaythepointafteraninputerroroccurred.c)Writeamainfunctionthattestsinputandoutputofuser-definedclassPointusingtheoverloadedstream-extractionandstream-insertionoperators.ANS:1//P21_15.H2#ifndefP21_15_H3#defineP21_15_H4#include56classPoint{7friendostream&operator<<(ostream&,Point&);8friendistream&operator>>(istream&,Point&);9private:10intxCoordinate;11intyCoordinate;12};1314#endif15//P21_15M.cpp16//memberfunctiondefinitionsforp21_15.cpp17#include"p21_15.h"1819ostream&operator<<(ostream&out,Point&p)20{21if(!cin.fail())22cout<<"("<>(istream&i,Point&p)30{31if(cin.peek()!="(")32cin.clear(ios::failbit);33else34i.ignore();//skip(3536cin>>p.xCoordinate;3738if(cin.peek()!=",")39cin.clear(ios::failbit);40else{41i.ignore();//skip,4243if(cin.peek()=="")44i.ignore();//skipspace45else46cin.clear(ios::failbit);47}4849cin>>p.yCoordinate;5051if(cin.peek()==")")52i.ignore();//skip)53else54cin.clear(ios::failbit);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter21C++StreamInput/Output:Solutions5315556returni;57}58//driverforp21_15.cpp59#include"p21_15.h"6061intmain()62{63Pointpt;6465cout<<"Enterapointintheform(x,y):n";66cin>>pt;6768cout<<"Pointenteredwas:"<56usingstd::ostream;7usingstd::istream;89classComplex{10friendostream&operator<<(ostream&,Complex&);11friendistream&operator>>(istream&,Complex&);12public:13Complex(void);//constructor14private:15intreal;16intimaginary;17};1819#endif©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com532C++StreamInput/Output:SolutionsChapter2120//P21_16M.cpp21//memberfunctiondefinitionsforp21_16.cpp22#include2324usingstd::cout;25usingstd::cin;26usingstd::ios;27usingstd::ostream;28usingstd::istream;2930#include3132usingstd::setiosflags;33usingstd::resetiosflags;3435#include"p21_16.h"3637Complex::Complex(void)38{39real=0;40imaginary=0;41}4243ostream&operator<<(ostream&output,Complex&c)44{45if(!cin.fail())46output<>(istream&input,Complex&c)57{58intnumber,multiplier;59chartemp;6061input>>number;6263if(cin.peek()==""){//casea+bi64c.real=number;65cin>>temp;6667multiplier=(temp=="+")?1:-1;6869if(cin.peek()!="")70cin.clear(ios::failbit);//setbadbit71else{7273if(cin.peek()==""){74input>>c.imaginary;75c.imaginary*=multiplier;7677cin>>temp;78if(cin.peek()!="n")79cin.clear(ios::failbit);//setbadbit80}81else82cin.clear(ios::failbit);//setbadbit83}84}85elseif(cin.peek()=="i"){//casebi86cin>>temp;87©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter21C++StreamInput/Output:Solutions53388if(cin.peek()=="n"){89c.real=0;90c.imaginary=number;91}92else93cin.clear(ios::failbit);//setbadbit94}9596elseif(cin.peek()=="n"){//casea97c.real=number;98c.imaginary=0;99}100else101cin.clear(ios::failbit);//setbadbit102103returninput;104}105//driverforp21_16.cpp106#include107108usingstd::cout;109usingstd::cin;110usingstd::endl;111112#include"p21_16.h"113114intmain()115{116Complexcomplex;117118cout<<"InputacomplexnumberintheformA+Bi:n";119cin>>complex;120121cout<<"Complexnumberenteredwas:n"<34usingstd::cout;5usingstd::endl;;6usingstd::ios;78#include910usingstd::setw;11usingstd::setiosflags;12usingstd::dec;13usingstd::oct;14usingstd::hex;1516intmain()17{18cout<(loop)<34usingstd::cout;5usingstd::endl;6usingstd::cin;7usingstd::ios;89#include1011constintSIZE=80;1213intmain()14{15chararray[SIZE],array2[SIZE],c;1617cout<<"Enterasentencetotestgetline()andget():n";18cin.getline(array,SIZE,"*");19cout<>c;//readnextcharacterininput22cout<<"Thenextcharacterintheinputis:"<>c;//readnextcharacterininput28cout<<"Thenextcharacterintheinputis:"<librarytotestifthecharacterisawhitespacechar-acter.Eachcharactershouldbeinputusingtheistreammemberfunctionget.Whenanon-whitespacecharacterisencountered,theskipwhitemanipulatorfinishesitsjobbyplacingthecharacterbackontheinputstreamandreturninganistreamreference.Testthemanipulatorbycreatingamainfunctioninwhichtheios::skipwsflagisunsetsothatthestream-extractionoper-atordoesnotautomaticallyskipwhitespace.Thentestthemanipulatorontheinputstreambyenteringacharacterprecededbywhitespaceasinput.Printthecharacterthatwasinputtoconfirmthatawhitespacecharacterwasnotinput.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com536C++StreamInput/Output:SolutionsChapter21©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com22C++Templates:SolutionsSOLUTIONS22.3UseanontypeparameternumberOfElementsandatypeparameterelementTypetohelpcreateatemplatefortheArrayclasswedevelopedinChapter18,“OperatorOverloading.”ThistemplatewillenableArrayobjectstobeinstantiatedwithaspec-ifiednumberofelementsofaspecifiedelementtypeatcompiletime.ANS:1#ifndefARRAY1_H2#defineARRAY1_H34#include56usingstd::cout;7usingstd::endl;8usingstd::cin;910#include11#include1213template14classArray{15public:16Array();//defaultconstructor17~Array();//destructor18intgetSize()const;//returnsize19booloperator==(constArray&)const;//compareequal20booloperator!=(constArray&)const;//compare!equal21elementType&operator[](int);//subscriptoperator22staticintgetArrayCount();//Returncountof23//arraysinstantiated.24voidinputArray();//inputthearrayelements25voidoutputArray()const;//outputthearrayelements26private:27elementTypeptr[numberOfElements];//pointertofirstelementofarray28intsize;//sizeofthearray29staticintarrayCount;//#ofArraysinstantiated30};©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com538C++Templates:SolutionsChapter223132//Initializestaticdatamemberatfilescope33template34intArray::arrayCount=0;//noobjectsyet3536//DefaultconstructorforclassArray37template38Array::Array()39{40++arrayCount;//countonemoreobject41size=numberOfElements;4243for(inti=0;i49Array::~Array(){--arrayCount;}5051//Getthesizeofthearray52template53intArray::getSize()const{returnsize;}5455//Determineiftwoarraysareequaland56//returntrueorfalse.57template58boolArray::59operator==(constArray&right)const60{61if(size!=right.size)62returnfalse;//arraysofdifferentsizes6364for(inti=0;i74boolArray::75operator!=(constArray&right)const76{77if(size!=right.size)78returntrue;//arraysofdifferentsizes7980for(inti=0;i89elementType&Array::90operator[](intsubscript)91{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter22C++Templates:Solutions53992//checkforsubscriptoutofrangeerror93assert(0<=subscript&&subscript100intArray::getArrayCount()101{returnarrayCount;}102103//Inputvaluesforentirearray.104template105voidArray::inputArray()106{107for(inti=0;i>ptr[i];109}110111//Outputthearrayvalues112template113voidArray::outputArray()const114{115inti=0;116for(;i130131usingstd::cout;132133#include"arraytmp.h"134135intmain()136{137ArrayintArray;138139cout<<"Enter"<floatArray;146147cout<<"nEnter"<).Thedrivershoulddemonstratethein-stantiationofanArrayofintthroughthetemplateandshouldshowthatanattempttoinstantiateanArrayoffloatusesthedefinitionprovidedinclassArray.22.5Whichismorelikeastencil—aclasstemplateoratemplateclass?Explainyouranswer.ANS:Aclasstemplatecanbeviewedasastencilfromwhichatemplateclasscanbecreated.Atemplateclasscanbeviewedasastencilfromwhichobjectsofthatclasscanbecreated.So,inaway,bothcanbeviewedasstencils.22.6Whatperformanceproblemcanresultfromusingclasstemplates?ANS:Therecanbeatremendousproliferationofcodeintheprogramduetomanycopiesofcodegeneratedbythecom-piler.22.7Whyisitappropriatetocallaclasstemplateaparameterizedtype?ANS:Whencreatingtemplateclassesfromaclasstemplate,itisnecessarytoprovideatype(orpossiblyseveraltypes)tocompletethedefinitionofthenewtypebeingdeclared.Forexample,whencreatingan“arrayofintegers”fromanArrayclasstemplate,thetypeintisprovidedtotheclasstemplatetocompletethedefinitionofanarrayofintegers.22.8ExplainwhyyoumightusethestatementArrayworkerList(100);inaC++program.ANS:DeclaresanArrayobjecttostoreEmployeeobjectsandpasses100totheconstructor.22.9ReviewyouranswertoExercise22.8.Now,whymightyouusethestatementArrayworkerList;inaC++program?ANS:DeclaresanArrayobjecttostoreanEmployee.Thedefaultconstructoriscalled.22.10ExplaintheuseofthefollowingnotationinaC++program:templateArray::Array(ints)ANS:ThisnotationisusedtobeginthedefinitionoftheArray(int)constructorfortheclasstemplateArray.22.11Whymightyoutypicallyuseanontypeparameterwithaclasstemplateforacontainersuchasanarrayorstack?ANS:Tospecifyatcompiletimethesizeofthecontainerclassobjectbeingdeclared.22.12Describehowtoprovideaclassforaspecifictypetooverridetheclasstemplateforthattype.22.13Describetherelationshipbetweenclasstemplatesandinheritance.22.14SupposeaclasstemplatehastheheadertemplateclassC1Describethefriendshiprelationshipsestablishedbyplacingeachofthefollowingfriendshipdeclarationsinsidethisclasstemplateheader.Identifiersbeginningwith“f”arefunctions,identifiersbeginningwith“C”areclassesandidentifiersbeginningwith“T”canrepresentanytype(i.e.,built-intypesorclasstypes).©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter22C++Templates:Solutions541a)friendvoidf1();ANS:Functionf1isafriendofalltemplateclassesinstantiatedfromclasstemplateC1.b)friendvoidf2(C1&);ANS:Functionf2foraspecifictypeofT1isafriendofthetemplateclassoftypeT1.Forexample,ifT1isoftypeintthefunctionwiththeprototypevoidf2(C1&);isafriendoftheclassC1.c)friendvoidC2::f4();ANS:Functionf4ofclassC2isafriendofalltemplateclassesinstantiatedfromclasstemplateC1.d)friendvoidC3::f5(C1&);ANS:Functionf5ofclassC3foraspecifictypeofT1isafriendofthetemplateclassoftypeT1.Forexample,ifT1isint,thefunctionwiththeprototypevoidC3::f5(C1&);isafriendoftheclassC1.e)friendclassC5;ANS:MakeseverymemberfunctionofclassC5afriendofalltemplateclassesinstantiatedfromtheclasstemplateC1.f)friendclassC6;ANS:ForaspecifictypeT1,makeseverymemberfunctionofC6afriendofclassC1.Forexample,ifT1isint,everymemberfunctionofclassC6isafriendofC1.22.15SupposeclasstemplateEmployeehasastaticdatamembercount.Supposethreetemplateclassesareinstantiatedfromtheclasstemplate.Howmanycopiesofthestaticdatamemberwillexist?Howwilltheuseofeachbeconstrained(ifatall)?ANS:Forstaticmembersofaclasstemplate,eachtemplateclassinstantiatedreceivesitsowncopyofallthestaticmembers.Thenallobjectsinstantiatedforagiventemplateclasscanaccessthatparticulartemplateclass’staticmembers©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com542C++Templates:SolutionsChapter22©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com23C++ExceptionHandling:SolutionSOLUTIONS23.20Underwhatcircumstanceswouldtheprogrammernotprovideaparameternamewhendefiningthetypeoftheobjectthatwillbecaughtbyahandler?ANS:Ifthereisnoinformationintheobjectthatisrequiredinthehandler,aparameternameisnotrequiredinthehandler.23.21Aprogramcontainsthestatementthrow;Wherewouldyounormallyexpecttofindsuchastatement?Whatifthatstatementappearedinadifferentpartoftheprogram?ANS:Thestatementwouldbefoundinanexceptionhandlertorethrowanexception.Ifanythrowexpressionoccursout-sideatryblock,thefunctionunexpectediscalled.23.22Underwhatcircumstanceswouldyouusethefollowingstatement?catch(...){throw;}ANS:Theproceedingstatementisusedtocatchanyexceptionandrethrowitforhandlingbyanexceptionhandlerinafunctionwithinthecallstack.23.23Compareandcontrastexceptionhandlingwiththevariousothererror-processingschemesdiscussedinthetext.ANS:Exceptionhandlingenablestheprogrammertobuildmorerobustclasseswithbuilt-inerrorprocessingcapabilities.Oncecreated,suchclassesallowclientsofclassestoconcentrateonusingtheclassesratherthandefiningwhatshouldhappenifanerroroccurswhileusingtheclass.Exceptionhandlingoffersthepossibilitythatanerrorcanbeprocessedandthattheprogramcancontinueexecution.Otherformsoferrorcheckingsuchasassert,exittheprogramimmediatelywithoutanyfurtherprocessing.23.24Listtheadvantagesofexceptionhandlingoverconventionalmeansoferrorprocessing.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com544C++ExceptionHandling:SolutionChapter2323.25Useinheritancetocreateabaseexceptionclassandvariousderivedexceptionclasses.Thenshowthatacatchhandlerspecifyingthebaseclasscancatchderived-classexceptions.ANS:1//Exercise23.25Solution2#include34usingstd::cout;56#include7#include89classBaseException{10public:11BaseException(char*mPtr):message(mPtr){}12voidprint()const{cout<34usingstd::cout;5usingstd::cerr;67#include8usingstd::bad_alloc;910#include1112intmain()13{14longdouble*ptr[10];1516try{17for(inti=0;i<10;++i){18ptr[i]=newlongdouble[1000000];19cout<<"Allocated1000000longdoublesinptr["20<number2)28result=number1+"islarger.";29elseif(number1number2){41largest=number1;42smallest=number2;43}44else{45largest=number2;46smallest=number1;47}4849if(number3>largest)50largest=number3;5152if(number3=1){37inttemp=number/factor;3839switch(factor){40case1000:41digit4=temp;42break;43case100:44digit3=temp*10;45break;46case10:47digit2=temp*100;48break;49case1:50digit1=temp*1000;51break;52}5354number%=factor;55factor/=10;56}5758if(digit1==0)//specialcasewhenlastdigitinitiallyis059showStatus(String.valueOf(0)+String.valueOf(digit2/100)60+String.valueOf(digit3/10)+61String.valueOf(digit4));©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter25BeyondC&C++:Operators,Methods&ArraysinJava:Solutions56962else63showStatus(String.valueOf(digit1+digit2+digit3+digit4));64}65}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com570BeyondC&C++:Operators,Methods&ArraysinJava:SolutionsChapter2525.15Thegreatestcommondivisor(GCD)oftwointegersisthelargestintegerthatevenlydivideseachofthetwonumbers.Writeamethodgcdthatreturnsthegreatestcommondivisoroftwointegers.Incorporatethemethodintoanappletthatreadstwovaluesfromtheuser.Displaytheresultofthemethodinthestatusbar.ANS:1//Exercise25.15Solution2//Divisor.java3//Programfindsthegreatest4//commondivisoroftwonumbers.5importjavax.swing.*;6importjava.awt.*;7importjava.awt.event.*;89publicclassDivisorextendsJAppletimplementsActionListener{10JTextFieldinput1,input2;11JLabellabel1,label2;1213publicvoidinit()14{15input1=newJTextField(4);16input2=newJTextField(4);17input2.addActionListener(this);18label1=newJLabel("Enterfirstnumber:");19label2=newJLabel("Entersecondnumber:");20Containerc=getContentPane();21c.setLayout(newFlowLayout());22c.add(label1);23c.add(input1);24c.add(label2);25c.add(input2);26}2728publicvoidactionPerformed(ActionEvente)29{30intnum1,num2;3132num1=Integer.parseInt(input1.getText());33num2=Integer.parseInt(input2.getText());3435showStatus("GCDis:"+gcd(num1,num2));36}3738publicintgcd(intx,inty)39{40intgreatest=1;4142for(intz=2;z<=((x=0&&number<=100)30showStatus("Pointis:"+qualityPoints(number));31else32showStatus("Invalidinput.");33}3435publicintqualityPoints(intgrade)36{37if(grade>=90)38return4;39elseif(grade>=80)40return3;41elseif(grade>=70)42return2;43elseif(grade>=60)44return1;45else46return0;47}48}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com572BeyondC&C++:Operators,Methods&ArraysinJava:SolutionsChapter2525.17Writeanappletthatsimulatescointossing.Lettheprogramtossthecoineachtimetheuserpressesthe“Toss”button.Countthenumberoftimeseachsideofthecoinappears.Displaytheresults.Theprogramshouldcallaseparatemethodflipthattakesnoargumentsandreturnsfalsefortailsandtrueforheads.[Note:Iftheprogramrealisticallysimulatesthecointossing,eachsideofthecoinshouldappearapproximatelyhalfthetime.]ANS:1//Exercise25.17Solution2//Coin.java3//Programsimulatestossingacoin.4importjavax.swing.*;5importjava.awt.event.*;67publicclassCoinextendsJApplet8implementsActionListener{9intheads,tails;10JButtonb;1112publicvoidinit()13{14b=newJButton("Toss");15b.addActionListener(this);16getContentPane().add(b);17}1819publicvoidactionPerformed(ActionEvente)20{21if(flip()==true)22++heads;23else24++tails;2526showStatus("Heads:"+heads+"Tails:"+tails);27}2829publicbooleanflip()30{31if((int)(Math.random()*2)==1)32returntrue;33else34returnfalse;35}36}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter25BeyondC&C++:Operators,Methods&ArraysinJava:Solutions57325.18Computersareplayinganincreasingroleineducation.Writeaprogramthatwillhelpanelementaryschoolstudentlearnmultiplication.UseMath.randomtoproducetwopositiveone-digitintegers.ItshouldthendisplayaquestioninthestatusbarsuchasHowmuchis6times7?ThestudentthentypestheanswerintoaJTextField.Yourprogramchecksthestudent"sanswer.Ifitiscorrect,drawthestring"Verygood!"ontheapplet,thenaskanothermultiplicationquestion.Iftheansweriswrong,drawthestring"No.Pleasetryagain."ontheapplet,thenletthestudenttrythesamequestionagainrepeatedlyuntilthestudentfinallygetsitright.Aseparatemethodshouldbeusedtogenerateeachnewquestion.Thismethodshouldbecalledoncewhentheappletbeginsexecutionandeachtimetheuseranswersthequestioncorrectly.Alldrawingontheappletshouldbeperformedbythepaintmethod.ANS:1//Exercise25.18Solution2//Multiply.java3//Programgeneratessingledigitmultiplication4//problems.5importjavax.swing.*;6importjava.awt.*;7importjava.awt.event.*;89//Note:AppletshaveaproblemrenderingPaintgraphicswhen10//SwingcomponentsareattachedtotheUI.Consequently,this11//solutiondoesnotusepaint1213publicclassMultiplyextendsJAppletimplementsActionListener{14JTextFieldquestion;15JTextFieldinput;16JTextFieldresponse;17JLabelprompt;18intanswer;19StringquestionString;2021publicvoidinit()22{23input=newJTextField(4);24input.addActionListener(this);25prompt=newJLabel("Enteryouranswer:");2627response=newJTextField(20);28response.setEditable(false);2930question=newJTextField(20);31question.setEditable(false);3233Containerc=getContentPane();34c.setLayout(newFlowLayout());35c.add(question);36c.add(prompt);37c.add(input);38c.add(response);3940createQuestion();41}4243publicvoidstart()44{45question.setText(questionString);46}4748publicvoidactionPerformed(ActionEvente)49{50intguess=Integer.parseInt(input.getText());5152input.setText("");5354if(guess!=answer)55response.setText("No.Pleasetryagain.");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com574BeyondC&C++:Operators,Methods&ArraysinJava:SolutionsChapter2556else{57response.setText("VeryGood!");58createQuestion();59}6061question.setText(questionString);62}6364//Createanewquestion,and65//thecorrespondinganswer66publicvoidcreateQuestion()67{68intdigit1=getNumber();69intdigit2=getNumber();7071answer=digit1*digit2;72questionString="Howmuchis"+digit1+"times"+digit2+"?";73}7475publicintgetNumber()76{77return((int)(Math.random()*10));78}79}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter25BeyondC&C++:Operators,Methods&ArraysinJava:Solutions57525.19Writeanappletthatplaysthe“guessthenumber”gameasfollows:Yourprogramchoosesthenumbertobeguessedbyselectingarandomintegerintherange1to1000.TheappletdisplaysthepromptGuessanumberbetween1and1000nexttoaJTextField.TheplayertypesafirstguessintotheJTextFieldandpressestheEnterkey.Iftheplayer"sguessisincorrect,yourprogramshoulddisplayToohigh.Tryagain.orToolow.Tryagain.inthestatusbartohelptheplayer“zeroin”onthecor-rectanswerandshouldcleartheJTextFieldsotheusercanenterthenextguess.Whentheuserentersthecorrectanswer,displayCongratulations.Youguessedthenumber!inthestatusbarandcleartheJTextFieldsotheusercanplayagain.[Note:Theguessingtechniqueemployedinthisproblemissimilartoabinarysearch.]ANS:1//Exercise25.19Solution2//Guess.java3//Programplaysguessthenumber.4//problems.5importjavax.swing.*;6importjava.awt.*;7importjava.awt.event.*;89publicclassGuessextendsJAppletimplementsActionListener{10JTextFieldinput;11JLabelprompt;12intanswer;1314publicvoidinit()15{16input=newJTextField(4);17input.addActionListener(this);18prompt=newJLabel("Guessanumberbetween1and1000");19Containerc=getContentPane();20c.setLayout(newFlowLayout());21c.add(prompt);22c.add(input);23answer=getNumber();24}2526publicvoidactionPerformed(ActionEvente)27{28intuserGuess=Integer.parseInt(input.getText());2930checkUserGuess(userGuess);31input.setText("");32}3334publicintgetNumber()35{36return((int)(1+Math.random()*1000));37}3839publicvoidcheckUserGuess(intuserGuess)40{41if(userGuessanswer)44showStatus(userGuess+"isTooHigh.TryAgain.");45else{46showStatus("Congratulations.Youguessedthenumber!");47input.setText("");4849//newsearch50answer=getNumber();51}52}53}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com576BeyondC&C++:Operators,Methods&ArraysinJava:SolutionsChapter25©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter25BeyondC&C++:Operators,Methods&ArraysinJava:Solutions57725.20Thegreatestcommondivisorofintegersxandyisthelargestintegerthatevenlydividesbothxandy.Writearecursivemethodgcdthatreturnsthegreatestcommondivisorofxandy.Thegcdofxandyisdefinedrecursivelyasfollows:Ifyisequalto0,thengcd(x,y)isx;otherwise,gcd(x,y)isgcd(y,x%y),where%isthemodulusoperator.UsethismethodtoreplacetheoneyouwroteintheappletofExercise25.15.ANS:1//Exercise25.20Solution2//Divisor.java3//Programrecursivelyfindsthegreatest4//commondivisoroftwonumbers.5importjavax.swing.*;6importjava.awt.*;7importjava.awt.event.*;89publicclassDivisorextendsJAppletimplementsActionListener{10JTextFieldinput1,input2;11JLabellabel1,label2;1213publicvoidinit()14{15input1=newJTextField(4);16input2=newJTextField(4);17input2.addActionListener(this);18label1=newJLabel("Enterfirstnumber:");19label2=newJLabel("Entersecondnumber:");20Containerc=getContentPane();21c.setLayout(newFlowLayout());22c.add(label1);23c.add(input1);24c.add(label2);25c.add(input2);26}2728publicvoidactionPerformed(ActionEvente)29{30intnum1,num2;3132num1=Integer.parseInt(input1.getText());33num2=Integer.parseInt(input2.getText());34showStatus("GCDis:"+gcd(num1,num2));35}3637publicintgcd(intx,inty)38{39if(y==0)40returnx;41else42returngcd(y,x%y);43}44}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com578BeyondC&C++:Operators,Methods&ArraysinJava:SolutionsChapter2525.21ModifythecrapsprogramofFig.25.13toallowwagering.InitializevariablebankBalanceto1000dollars.Prompttheplayertoenterawager.CheckthatwagerislessthanorequaltobankBalance,andifnot,havetheuserreenterwageruntilavalidwagerisentered.Afteracorrectwagerisentered,runonegameofcraps.Iftheplayerwins,increasebankBalancebywagerandprintthenewbankBalance.Iftheplayerloses,decreasebankBalancebywager,printthenewbankBalance,checkifbankBalancehasbecomezero,andifso,printthemessage"Sorry.Youbusted!"Asthegameprogresses,printvariousmes-sagestocreatesome“chatter,”suchas"Oh,you"regoingforbroke,huh?"or"Awc’mon,takeachance!"or"You"reupbig.Now"sthetimetocashinyourchips!".Implementthe“chatter”asaseparatemethodthatrandomlychoosesthestringtodisplay.ANS:1//Exercise25.21Solution2//Craps.java3//ProgramplaysCraps4importjava.awt.*;5importjavax.swing.*;6importjava.awt.event.*;78publicclassCrapsextendsJAppletimplementsActionListener{9//constantvariablesforstatusofgame10finalintWON=0,LOST=1,CONTINUE=2;1112//othervariablesusedinprogram13booleanfirstRoll=true;//trueiffirstroll14intdieSum;//sumofthedice15intmyPoint;//pointifnowin/lossonfirstroll16intgameStatus=CONTINUE;//WON,LOST,CONTINUE17intbankBalance,wager;1819//graphicaluserinterfacecomponents20JLabeldie1Label,die2Label,sumLabel,pointLabel,betLabel;21JTextFieldfirstDie,secondDie,sum,point,better,chatter;22JButtonroll;2324//setupgraphicaluserinterfacecomponents25publicvoidinit()26{27Containerc=getContentPane();28c.setLayout(newFlowLayout());2930bankBalance=1000;31betLabel=newJLabel("bet:");32better=newJTextField("100",10);33die1Label=newJLabel("Die1");34firstDie=newJTextField(10);35firstDie.setEditable(false);36die2Label=newJLabel("Die2");37secondDie=newJTextField(10);38secondDie.setEditable(false);39sumLabel=newJLabel("Sumis");40sum=newJTextField(10);41sum.setEditable(false);42roll=newJButton("RollDice");43roll.addActionListener(this);44pointLabel=newJLabel("Pointis");45point=newJTextField(10);46point.setEditable(false);4748chatter=newJTextField(25);49chatter.setEditable(false);50c.add(die1Label);51c.add(firstDie);52c.add(die2Label);53c.add(secondDie);54c.add(sumLabel);55c.add(sum);56c.add(pointLabel);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter25BeyondC&C++:Operators,Methods&ArraysinJava:Solutions57957c.add(point);58c.add(betLabel);59c.add(better);60c.add(roll);61c.add(chatter);62}6364//processonerollofthedice65publicvoidplay()66{67if(firstRoll){//firstrollofthedice68dieSum=rollDice();6970switch(dieSum){71case7:case11://winonfirstroll72gameStatus=WON;73point.setText("");//clearpointtextfield74firstRoll=true;//allownewgametostart75break;76case2:case3:case12://loseonfirstroll77gameStatus=LOST;78point.setText("");//clearpointtextfield79firstRoll=true;//allownewgametostart80break;81default://rememberpoint82gameStatus=CONTINUE;83myPoint=dieSum;84point.setText(Integer.toString(myPoint));85firstRoll=false;86break;87}88}89else{90dieSum=rollDice();9192if(dieSum==myPoint)//winbymakingpoint93gameStatus=WON;94elseif(dieSum==7)//losebyrolling795gameStatus=LOST;96}9798if(gameStatus==CONTINUE)99showStatus("($"+bankBalance+")Rollagain.");100else{101102if(gameStatus==WON){103bankBalance+=wager;104showStatus("($"+bankBalance+")Playerwins."+105"ClickRollDicetoplayagain.");106}107else{108bankBalance-=wager;109checkBalance();110showStatus("($"+bankBalance+")Playerloses."+111"ClickRollDicetoplayagain.");112}113114better.setEditable(true);115firstRoll=true;116}117}118119voidcheckBalance()120{121if(bankBalance==0){122System.out.println("Sorry.Youbusted!");123System.exit(0);124}125}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com580BeyondC&C++:Operators,Methods&ArraysinJava:SolutionsChapter25126127//callmethodplaywhenbuttonisclicked128publicvoidactionPerformed(ActionEvente)129{130intw=Integer.parseInt(better.getText());131132if(w>bankBalance||w<0)133showStatus("($"+bankBalance+")"+134"Enteravalidwager!");135else{136wager=w;137better.setEditable(false);138play();139}140141chatter.setText(chatter());142}143144//rollthedice145introllDice()146{147intdie1,die2,workSum;148149die1=1+(int)(Math.random()*6);150die2=1+(int)(Math.random()*6);151workSum=die1+die2;152153firstDie.setText(Integer.toString(die1));154secondDie.setText(Integer.toString(die2));155sum.setText(Integer.toString(workSum));156157returnworkSum;158}159160publicStringchatter()161{162Strings=null;163164switch((int)(Math.random()*5)){165case0:166s="Oh,you"regoingforbrokehuh?";167break;168case1:169s="Awcmon,takeachance!";170break;171case2:172s="You"reupbig.Now"sthe"+173"timetocashinyourchips!";174break;175case3:176s="You"rewaytoolucky!Ithinkyou"re"+177"acheat!!!";178break;179case4:180s="I"mbettingallmymoneyonyou.";181break;182}183184returns;185}186}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter25BeyondC&C++:Operators,Methods&ArraysinJava:Solutions581©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com582BeyondC&C++:Operators,Methods&ArraysinJava:SolutionsChapter2525.22Writeaprogramtosimulatetherollingoftwodice.TheprogramshoulduseMath.randomtorollthefirstdieandshoulduseMath.randomagaintorolltheseconddie.Thesumofthetwovaluesshouldthenbecalculated.[Note:Sinceeachdiecanshowanintegervaluefrom1to6,thesumofthevalueswillvaryfrom2to12,with7beingthemostfrequentsumand2and12beingtheleastfrequentsums.Figure25.24showsthe36possiblecombinationsofthetwodice.Yourprogramshouldrollthedice36,000times.Useasingle-subscriptedarraytotallythenumbersoftimeseachpossiblesumappears.Printtheresultsinatabularformat.Also,determineifthetotalsarereasonable(i.e.,therearesixwaystorolla7,soapproximatelyonesixthofalltherollsshouldbe7).123456123456723456783456789456789105678910116789101112Fig.25.24The36possibleoutcomesofrollingtwodice.ANS:1//Exercise25.22Solution2//Roll36.java3//Programsimulatesrollingtwo4//six-sideddie36,000times5//NOTE:thisprogramcouldtakea6//fewsecondsbeforedisplayingthedata7importjavax.swing.*;8importjava.awt.*;910publicclassRoll36extendsJApplet{11inttotal[];1213publicvoidinit()14{15total=newint[13];1617for(inti=0;i=0&&h<24)?h:0);}3940//settheminute41publicvoidsetMinute(intm)42{minute=((m>=0&&m<60)?m:0);}4344//setthesecond45publicvoidsetSecond(ints)46{second=((s>=0&&s<60)?s:0);}4748//GetMethods49//getthehour50publicintgetHour(){returnhour;}5152//gettheminute53publicintgetMinute(){returnminute;}5455//getthesecond56publicintgetSecond(){returnsecond;}57©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com590JavaObject-BasedProgramming:SolutionsChapter2658//ConverttoStringinmilitary-timeformat59publicStringtoMilitaryString()60{61return(hour<10?"0":"")+hour+62(minute<10?"0":"")+minute;63}6465//ConverttoStringinstandard-timeformat66publicStringtoString()67{68return((hour==12||hour==0)?12:hour%12)+69":"+(minute<10?"0":"")+minute+70":"+(second<10?"0":"")+second+71(hour<12?"AM":"PM");72}7374//Tickthetimebyonesecond75publicvoidtick()76{77setSecond(second+1);7879if(second==0)80incrementMinute();81}8283//Incrementtheminute84publicvoidincrementMinute()85{86setMinute(minute+1);8788if(minute==0)89incrementHour();90}9192//Incrementthehour93publicvoidincrementHour()94{95setHour(hour+1);96}97}98//Exercise26.3Solution99//TimeTest.java100//DemonstratingtheTimeclasssetandgetmethods101importjava.awt.*;102importjavax.swing.*;103importjava.awt.event.*;104105publicclassTimeTestextendsJAppletimplementsActionListener{106privateTime3t;107privateJLabelhrLabel,minLabel,secLabel;108privateJTextFieldhrField,minField,secField,display;109privateJButtontickButton;110111publicvoidinit()112{113t=newTime3();114115hrLabel=newJLabel("SetHour");116hrField=newJTextField(10);117hrField.addActionListener(this);118minLabel=newJLabel("SetMinute");119minField=newJTextField(10);120minField.addActionListener(this);121secLabel=newJLabel("SetSecond");122secField=newJTextField(10);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter26JavaObject-BasedProgramming:Solutions591123secField.addActionListener(this);124display=newJTextField(30);125display.setEditable(false);126tickButton=newJButton("Add1toSecond");127tickButton.addActionListener(this);128129Containerc=getContentPane();130c.setLayout(newFlowLayout());131c.add(hrLabel);132c.add(hrField);133c.add(minLabel);134c.add(minField);135c.add(secLabel);136c.add(secField);137c.add(display);138c.add(tickButton);139updateDisplay();140}141142publicvoidactionPerformed(ActionEvente)143{144if(e.getSource()==tickButton)145t.tick();146elseif(e.getSource()==hrField){147t.setHour(Integer.parseInt(e.getActionCommand().toString()));148hrField.setText("");149}150elseif(e.getSource()==minField){151t.setMinute(Integer.parseInt(e.getActionCommand().toString()));152minField.setText("");153}154elseif(e.getSource()==secField){155t.setSecond(Integer.parseInt(e.getActionCommand().toString()));156secField.setText("");157}158159updateDisplay();160}161162publicvoidupdateDisplay()163{164display.setText("Hour:"+t.getHour()+165";Minute:"+t.getMinute()+166";Second:"+t.getSecond());167showStatus("Standardtimeis:"+t.toString()+168";Militarytimeis:"+t.toMilitaryString());169}170}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com592JavaObject-BasedProgramming:SolutionsChapter2626.4CreateaclassRectangle.Theclasshasattributeslengthandwidth,eachofwhichdefaultsto1.Ithasmethodsthatcalculatetheperimeterandtheareaoftherectangle.Ithassetandgetmethodsforbothlengthandwidth.Thesetmethodsshouldverifythatlengthandwidthareeachfloating-pointnumberslargerthan0.0andlessthan20.0.ANS:1//Exercise26.4Solution2//MyRectangle.java3//DefinitionofclassMyRectangle45publicclassMyRectangle{6privatedoublelength,width;78publicMyRectangle(){this(1.0,1.0);}910publicMyRectangle(doublel,doublew)11{12setLength(l);13setWidth(w);14}1516publicvoidsetLength(doublelen)17{length=(len>=0.0&&len<=20.0?len:1.0);}1819publicvoidsetWidth(doublew)20{width=(w>=0&&w<=20.0?w:1.0);}2122publicdoublegetLength(){returnlength;}2324publicdoublegetWidth(){returnwidth;}2526publicdoubleperimeter(){return2*length+2*width;}2728publicdoublearea(){returnlength*width;}2930publicStringtoString(){31return("Length:"+length+"n"+32"Width:"+width+"n"+33"Perimeter:"+perimeter()+"n"+34"Area:"+area());35}36}37//Exercise26.4Solution38//DefinitionofclassRectangleTest39importjava.awt.*;40importjavax.swing.*;41importjava.awt.event.*;4243publicclassRectangleTestextendsJAppletimplementsActionListener{44privateJLabelprompt1,prompt2;45privateJTextFieldinput1,input2;46privateJLabeloutputLabel;47privateJTextAreaoutput;48privateMyRectangler;4950publicvoidinit()51{52prompt1=newJLabel("Length:");53prompt2=newJLabel("Width:");54input1=newJTextField(10);55input2=newJTextField(10);56input2.addActionListener(this);5758outputLabel=newJLabel("TestOutput");59output=newJTextArea(4,10);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter26JavaObject-BasedProgramming:Solutions5936061Containerc=getContentPane();62c.setLayout(newFlowLayout());63c.add(prompt1);64c.add(input1);65c.add(prompt2);66c.add(input2);67c.add(outputLabel);68c.add(output);69r=newMyRectangle();70}7172publicvoidactionPerformed(ActionEvente)73{74doubled1,d2;7576d1=Double.parseDouble(input1.getText());77d2=Double.parseDouble(input2.getText());7879r.setLength(d1);80r.setWidth(d2);8182output.setText(r.toString());83}84}26.5CreateamoresophisticatedRectangleclassthantheoneyoucreatedinExercise26.4.ThisclassstoresonlytheCartesiancoordinatesofthefourcornersoftherectangle.Theconstructorcallsasetmethodthatacceptsfoursetsofcoordinatesandverifiesthateachoftheseisinthefirstquadrantwithnosinglex-ory-coordinatelargerthan20.0.Thesetmethodalsoverifiesthatthesuppliedcoordinatesdo,infact,specifyarectangle.Providemethodstocalculatethelength,width,perimeterandarea.Thelengthisthelargerofthetwodimensions.IncludeapredicatemethodisSquarewhichdeterminesiftherectangleisasquare.26.6ModifytheRectangleclassofExercise26.5toincludeadrawmethodthatdisplaystherectangleinsidea25-by-25boxenclosingtheportionofthefirstquadrantinwhichtherectangleresides.UsethemethodsoftheGraphicsclasstohelpoutputtheRectangle.Ifyoufeelambitious,youmightincludemethodstoscalethesizeoftherectangle,rotateitandmoveitaroundwithinthedesignatedportionofthefirstquadrant.26.7CreateaclassHugeIntegerwhichusesa40-elementarrayofdigitstostoreintegersaslargeas40digitseach.ProvidemethodsinputHugeInteger,outputHugeInteger,add-HugeIntegersandsubtractHugeIntegers.ForcomparingHugeIntegerobjects,providemethodsisEqualTo,isNotEqualTo,isGreaterThan,isLessThan,IsGreaterTha-nOrEqualToandisLessThanOrEqualTo—eachoftheseisa“predicate”methodthatsimplyreturnstrueiftherelationshipholdsbetweenthetwoHugeIntegersandreturnsfalseiftherelationshipdoesnothold.ProvideapredicatemethodisZero.Ifyoufeelambitious,alsoprovidethemethodmultiplyHugeIntegers,themethoddivideHugeIntegersandthemethodmod-ulusHugeIntegers.26.8CreateclassSavingsAccount.UseastaticclassvariabletostoretheannualInterestRateforallaccountholders.EachobjectoftheclasscontainsaprivateinstancevariablesavingsBalanceindicatingtheamountthesavercurrentlyhasondeposit.ProvidemethodcalculateMonthlyInteresttocalculatethemonthlyinterestbymultiplyingthesavingsBalancebyannualInterestRatedividedby12;thisinterestshouldbeaddedtosavingsBalance.ProvideastaticmethodmodifyIn-terestRatethatsetstheannualInterestRatetoanewvalue.WriteadriverprogramtotestclassSavingsAccount.Instan-©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com594JavaObject-BasedProgramming:SolutionsChapter26tiatetwosavingsAccountobjects,saver1andsaver2,withbalancesof$2000.00and$3000.00,respectively.SetannualInterestRateto4%,thencalculatethemonthlyinterestandprintthenewbalancesforeachofthesavers.ThensettheannualInterestRateto5%andcalculatethenextmonth’sinterestandprintthenewbalancesforeachofthesavers.26.9CreateclassIntegerSet.Eachobjectoftheclasscanholdintegersintherange0through100.Asetisrepresentedinter-nallyasanarrayofbooleans.Arrayelementa[i]istrueifintegeriisintheset.Arrayelementa[j]isfalseifintegerjisnotintheset.Theno-argumentconstructorinitializesasettotheso-called“emptyset”(i.e.,asetwhosearrayrepresentationcontainsallfalsevalues).Providethefollowingmethods:MethodunionOfIntegerSetscreatesathirdsetwhichistheset-theoreticunionoftwoexistingsets(i.e.,anelementofthethirdset’sarrayissettotrueifthatelementistrueineitherorbothoftheexistingsets;oth-erwise,theelementofthethirdsetissettofalse).MethodintersectionOfIntegerSetscreatesathirdsetwhichistheset-theoreticintersectionoftwoexistingsetsi.e.,anelementofthethirdset’sarrayissettofalseifthatelementisfalseineitherorbothoftheexistingsets;otherwise,theelementofthethirdsetissettotrue).MethodinsertElementinsertsanewintegerkintoaset(bysettinga[k]totrue).MethoddeleteElementdeletesintegerm(bysettinga[m]tofalse).MethodsetPrintprintsasetasalistofnumbersseparatedbyspaces.Printonlythoseelementsthatarepresentintheset.Print---foranemptyset.MethodisEqualTodeterminesiftwosetsareequal.WriteaprogramtotestyourIntegerSetclass.InstantiateseveralInte-gerSetobjects.Testthatallyourmethodsworkproperly.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter26JavaObject-BasedProgramming:Solutions59526.10ItwouldbeperfectlyreasonablefortheTime1classofFig.26.1torepresentthetimeinternallyasthenumberofsecondssincemidnightratherthanthethreeintegervalueshour,minuteandsecond.Clientscouldusethesamepublicmethodsandgetthesameresults.ModifytheTime1classofFig.26.1toimplementtheTime1asthenumberofsecondssincemidnightandshowthatthereisnovisiblechangetotheclientsoftheclass.ANS:1//Exercise26.10Solution2//Time1classdefinition34publicclassTime1{5privateinttotalSeconds;67publicTime1(){setTime(0,0,0);}89publicvoidsetTime(inth,intm,ints)10{11inthour,minute,second;1213hour=((h>=0&&h<24)?h:0);14minute=((m>=0&&m<60)?m:0);15second=((s>=0&&s<60)?s:0);1617totalSeconds=hour*3600+minute*60+second;18}1920publicStringtoMilitaryString()21{22inthour,minute,temp;2324hour=totalSeconds/3600;25temp=totalSeconds%3600;26minute=temp/60;2728return(hour<10?"0":"")+hour+29(minute<10?"0":"")+minute;30}3132publicStringtoString()33{34inthour,minute,second,temp;3536hour=totalSeconds/3600;37temp=totalSeconds%3600;38minute=temp/60;39second=temp%60;4041return((hour==12||hour==0)?12:hour%12)+42":"+(minute<10?"0":"")+minute+43":"+(second<10?"0":"")+second+44(hour<12?"AM":"PM");45}46}47//Exercise26.10Solution48//TimeTest.java49//ClassTimeTesttoexerciseclassTime50importjavax.swing.*;5152publicclassTimeTest{53publicstaticvoidmain(Stringargs[])54{55Time1t=newTime1();56Stringresult="";57©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com596JavaObject-BasedProgramming:SolutionsChapter2658result+="Theinitialmilitarytimeis:"+59t.toMilitaryString();60result+="nTheinitialstandardtimeis:"+61t.toString();6263t.setTime(13,27,6);64result+="nMilitarytimeaftersetTimeis:"+65t.toMilitaryString();66result+="nStandardtimeaftersetTimeis:"+67t.toString();6869t.setTime(99,99,99);70result+="nAfterattemptinginvalidsettings:";71result+="nMilitarytime:"+t.toMilitaryString();72result+="nStandardtime:"+t.toString();7374JOptionPane.showMessageDialog(75null,result,"Time1Test",76JOptionPane.INFORMATION_MESSAGE);77System.exit(0);78}79}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter26JavaObject-BasedProgramming:Solutions59726.11(DrawingProgram)Createadrawingappletthatrandomlydrawslines,rectanglesandovals.Forthispurpose,createasetof“smart”shapeclasseswhereobjectsoftheseclassesknowhowtodrawthemselvesifprovidedwithaGraphicsobjectthattellsthemwheretodraw(i.e.,theapplet’sGraphicsobjectallowsashapetodrawontheapplet’sbackground).TheclassnamesshouldbeMyLine,MyRectandMyOval.ThedataforclassMyLineshouldincludex1,y1,x2andy2coordinates.MethoddrawLinemethodofclassGraphicswillconnectthetwopointssuppliedwithaline.ThedataforclassesMyRectandMyOvalshouldincludeanupper-leftx-coordinatevalue,anupper-lefty-coordinatevalue,awidth(mustbenonnegative)andaheight(mustbenonnegative).Alldataineachclassmustbeprivate.Inadditiontothedata,eachclassshoulddefineatleastthefollowingpublicmethods:a)Aconstructorwithnoargumentsthatsetsthecoordinatesto0.b)Aconstructorwithargumentsthatsetsthecoordinatestothesuppliedvalues.c)Setmethodsforeachindividualpieceofdatathatallowtheprogrammertoindependentlysetanypieceofdatainashape(e.g.,ifyouhaveaninstancevariablex1,youshouldhaveamethodsetX1).d)Getmethodsforeachindividualpieceofdatathatallowtheprogrammertoindependentlyretrieveanypieceofdatainashape(e.g.,ifyouhaveaninstancevariablex1,youshouldhaveamethodgetX1).e)Adrawmethodwiththefirstlinepublicvoiddraw(Graphicsg)willbecalledfromtheapplet’spaintmethodtodrawashapeontothescreen.Theprecedingmethodsarerequired.Ifyouwouldliketoprovidemoremethodsforflexibility,pleasedoso.BeginbydefiningclassMyLineandanapplettotestyourclasses.TheappletshouldhaveaMyLineinstancevariablelinethatcanrefertooneMyLineobject(createdintheapplet’sinitmethodwithrandomcoordinates).Theapplet’spaintmethodshoulddrawtheshapewithastatementlikeline.draw(g);wherelineistheMyLinereferenceandgistheGraphicsobjectthattheshapewillusetodrawitselfontheapplet.Next,changethesingleMyLinereferenceintoanarrayofMyLinereferencesandhardcodeseveralMyLineobjectsintotheprogramfordrawing.Theapplet’spaintmethodshouldwalkthroughthearrayofMyLineobjectsanddraweveryone.Aftertheprecedingpartisworking,youshoulddefinetheMyOvalandMyRectclassesandaddobjectsoftheseclassesintotheMyRectandMyOvalarrays.Theapplet’spaintmethodshouldwalkthrougheacharrayanddraweveryshape.Createfiveshapesofeachtype.Oncetheappletisrunning,selectReloadfromtheappletviewer’sAppletmenutoreloadtheapplet.Thiswillcausetheapplettochoosenewrandomnumbersfortheshapesanddrawtheshapesagain.InChapter27,wewillmodifythisexercisetotakeadvantageofthesimilaritiesbetweentheclassesandtoavoidreinventingthewheel.ANS:1//Exercise26.11Solution2//MyLine.java3//DefinitionofclassMyLine4importjava.awt.Graphics;56publicclassMyLine{7privateintx1,x2;8privateinty1,y2;910publicMyLine()11{12x1=0;13y1=0;14x2=0;15y2=0;16}1718publicMyLine(intx1,inty1,intx2,inty2)19{20setX1(x1);21setX2(x2);22setY1(y1);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com598JavaObject-BasedProgramming:SolutionsChapter2623setY2(y2);24}2526publicvoidsetX1(intx1)27{this.x1=(x1>=0?x1:0);}2829publicvoidsetX2(intx2)30{this.x2=(x2>=0?x2:0);}3132publicvoidsetY1(inty1)33{this.y1=(y1>=0?y1:0);}3435publicvoidsetY2(intx2)36{this.y2=(y2>=0?y2:0);}3738publicintgetX1(){returnx1;}39publicintgetX2(){returnx2;}40publicintgetY1(){returny1;}41publicintgetY2(){returny2;}4243publicvoiddraw(Graphicsg)44{45g.drawLine(x1,y1,x2,y2);46}47}48//Exercise26.11Solution49//MyOval.java50//DefinitionofclassMyRect51importjava.awt.Graphics;5253publicclassMyOval{54privateintlength,width;55privateintupperLeftX,upperLeftY;5657publicMyOval()58{59length=0;60width=0;61upperLeftX=0;62upperLeftY=0;63}6465publicMyOval(intx,inty,intl,intw)66{67setUpperLeftX(x);68setUpperLeftY(y);69setLength(l);70setWidth(w);71}7273publicvoidsetLength(intlen)74{length=(len>=0?len:0);}7576publicvoidsetUpperLeftX(intx)77{upperLeftX=(x>=0?x:0);}7879publicvoidsetUpperLeftY(inty)80{upperLeftX=(y>=0?y:0);}8182publicvoidsetWidth(intw)83{width=(w>=0?w:0);}8485publicintgetLength(){returnlength;}8687publicintgetWidth(){returnwidth;}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter26JavaObject-BasedProgramming:Solutions5998889publicintgetUpperLeftX(){returnupperLeftX;}9091publicintgetUpperLeftY(){returnupperLeftY;}9293publicvoiddraw(Graphicsg)94{95g.drawOval(upperLeftX,upperLeftY,length,width);96}97}98//Exercise26.11Solution99//MyRect.java100//DefinitionofclassMyRect101importjava.awt.Graphics;102103publicclassMyRect{104privateintlength,width;105privateintupperLeftX,upperLeftY;106107publicMyRect()108{109length=0;110width=0;111upperLeftX=0;112upperLeftY=0;113}114115publicMyRect(intx,inty,intl,intw)116{117setUpperLeftX(x);118setUpperLeftY(y);119setLength(l);120setWidth(w);121}122123publicvoidsetLength(intlen)124{length=(len>=0.0?len:1);}125126publicvoidsetUpperLeftX(intx)127{upperLeftX=(x>=0?x:0);}128129publicvoidsetUpperLeftY(inty)130{upperLeftX=(y>=0?y:0);}131132publicvoidsetWidth(intw)133{width=(w>=0?w:1);}134135publicintgetLength(){returnlength;}136137publicintgetWidth(){returnwidth;}138139publicintgetUpperLeftX(){returnupperLeftX;}140141publicintgetUpperLeftY(){returnupperLeftY;}142143publicvoiddraw(Graphicsg)144{145g.drawRect(upperLeftX,upperLeftY,length,width);146}147}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com600JavaObject-BasedProgramming:SolutionsChapter26148//Exercise26.11Solution149//DefinitionofclassRectangleTest150importjava.awt.*;151importjavax.swing.*;152153publicclassTestDrawextendsJApplet{154privateMyLineline[];155privateMyOvaloval[];156privateMyRectrect[];157158publicvoidinitDraw()159{160line=newMyLine[5];161line[0]=newMyLine(100,100,200,200);162line[1]=newMyLine(200,200,100,100);163line[2]=newMyLine(300,300,100,100);164line[3]=newMyLine(400,400,0,0);165line[4]=newMyLine(100,100,300,300);166167oval=newMyOval[5];168oval[0]=newMyOval(100,100,200,200);169oval[1]=newMyOval(200,200,100,100);170oval[2]=newMyOval(300,300,100,100);171oval[3]=newMyOval(400,400,30,200);172oval[4]=newMyOval(100,100,300,300);173174rect=newMyRect[5];175rect[0]=newMyRect(100,100,200,200);176rect[1]=newMyRect(200,200,100,100);177rect[2]=newMyRect(300,300,100,100);178rect[3]=newMyRect(400,400,30,200);179rect[4]=newMyRect(100,100,300,300);180}181182publicvoidpaint(Graphicsg)183{184initDraw();185186for(inti=0;i=0?s:0);}4344publicdoublegetSide(){returnside;}4546publicdoublearea(){returnMath.pow(side,2);}4748publicStringtoString()49{return"Corner="+p.toString()+";Side="+side;}5051publicStringgetName(){return"Square";}5253publicStringgetPointName(){returnp.getName();}5455publicStringgetPointString(){returnp.toString();}56}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com606JavaObject-OrientedProgramming:SolutionsChapter2757//Exercies27.9--Composition58//Cube.java59//DefinitionofclassCube6061publicclassCube{62privatedoubledepth;63privateSquares;//composition6465publicCube(doublem,doublea,doubleb)66{67s=newSquare(m,a,b);68depth=m;69}7071publicdoublegetDepth(){returndepth;}7273publicdoublearea(){returns.area()*6;}7475publicdoublevolume(){returns.area()*depth;}7677publicStringtoString()78{returns.toString()+";Depth="+depth;}7980publicStringgetName(){return"Cube";}8182publicdoublegetSquareArea(){returns.area();}8384publicStringgetSquareName(){returns.getName();}8586publicStringgetSquareString(){returns.toString();}8788publicStringgetSPointString(){returns.getPointString();}8990publicStringgetSPointName(){returns.getPointName();}91}92//Exercise27.9--Composition93//Test.java94//Driverforpoint,square,cubecompositionprogram95importjavax.swing.*;9697publicclassTest{98publicstaticvoidmain(Stringargs[])99{100Cubecube=newCube(3.3,10,10);101Stringresult="";102103result+=cube.getSPointName()+":"+104cube.getSPointString();105106result+="n"+cube.getSquareName()+":"+107cube.getSquareString();108109result+="n"+cube.getName()+":"+110cube.toString();111112result+="n"+cube.getSPointName()+113":"+cube.getSPointString();114115result+="n"+cube.getSquareName()+116":"+cube.getSquareString();117result+="n"+"Area="+cube.getSquareArea();118119result+="n"+cube.getName()+120":"+cube.toString();121result+="n"+"Area="+cube.area();122result+="n"+"Volume="+cube.volume();©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter27JavaObject-OrientedProgramming:Solutions607123124JOptionPane.showMessageDialog(125null,result,"Shapes",126JOptionPane.INFORMATION_MESSAGE);127System.exit(0);128}129}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com608JavaObject-OrientedProgramming:SolutionsChapter27ANS:1//Exercies27.9--Inheritance2//Point.java3//DefinitionofclassPoint45publicclassPointextendsShape{6protecteddoublex,y;78publicPoint(doublea,doubleb){setPoint(a,b);}910publicvoidsetPoint(doublea,doubleb)11{12x=a;13y=b;14}1516publicdoublegetX(){returnx;}1718publicdoublegetY(){returny;}1920publicStringtoString()21{return"["+x+","+y+"]";}2223publicStringgetName(){return"Point";}24}25//Exercies27.9--Inheritance26//Shape.java27//DefinitionofabstractbaseclassShape2829publicabstractclassShape{30publicdoublearea(){return0.0;}31publicdoublevolume(){return0.0;}32publicabstractStringgetName();33}34//Exercies27.9--Inheritance35//Square.java36//DefinitionofclassSquare3738publicclassSquareextendsPoint{39protecteddoubleside;4041publicSquare()42{this(0.0,0.0,0.0);}4344publicSquare(doubles,doublea,doubleb)45{46super(a,b);47setSide(s);48}4950publicvoidsetSide(doubles)51{side=(s>=0?s:0);}5253publicdoublegetSide(){returnside;}5455publicdoublearea(){returnMath.pow(side,2);}5657publicStringtoString()58{return"Corner="+super.toString()+59";side="+side;}60©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter27JavaObject-OrientedProgramming:Solutions60961publicStringgetName(){return"Square";}62}63//Exercies27.9--Inheritance64//Cube.java65//DefinitionofclassCylinder6667publicclassCubeextendsSquare{68privatedoubledepth;6970publicCube(doubles,doublea,doubleb)71{72super(s,a,b);73depth=s;74}7576publicdoublearea(){returnsuper.area()*6;}7778publicdoublevolume(){returnsuper.area()*depth;}7980publicStringtoString()81{returnsuper.toString()+";depth="+depth;}8283publicStringgetName(){return"Cube";}84}85//Exercies27.9--Inheritance86//Test.java87//Driverforpoint,square,cubehierarchy88importjavax.swing.*;8990publicclassTest{91publicstaticvoidmain(Stringargs[])92{93Pointpoint=newPoint(7,11);94Squaresquare=newSquare(3.5,22,8);95Cubecube=newCube(3.3,10,10);9697Shape[]arrayOfShapes=newShape[3];98Stringresult="";99100arrayOfShapes[0]=point;101arrayOfShapes[1]=square;102arrayOfShapes[2]=cube;103104result+=point.getName()+":"+105point.toString();106107result+="n"+square.getName()+":"+108square.toString();109110result+="n"+cube.getName()+":"+111cube.toString();112113for(inti=0;i<3;i++){114result+="n"+arrayOfShapes[i].getName()+115":"+arrayOfShapes[i].toString();116result+="n"+"Area="+117arrayOfShapes[i].area();118result+="n"+"Volume="+119arrayOfShapes[i].volume();120}121©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com610JavaObject-OrientedProgramming:SolutionsChapter27122JOptionPane.showMessageDialog(123null,result,"Shapes",124JOptionPane.INFORMATION_MESSAGE);125System.exit(0);126}127}27.10Inthechapter,westated,“Whenasuperclassmethodisinappropriateforasubclass,thatmethodcanbeoverriddeninthesubclasswithanappropriateimplementation.”Ifthisisdone,doesthesubclass-is-a-superclass-objectrelationshipstillhold?Ex-plainyouranswer.ANS:Yes,thesubclass-is-a-superclass-objectrelationshipstillholds.InJava,itisnotpossibletobreakthisrelationship.27.11Howisitthatpolymorphismenablesyoutoprogram“inthegeneral”ratherthan“inthespecific”?Discussthekeyadvan-tagesofprogramming“inthegeneral.”ANS:Polymorphismenablestheprogrammertoconcentrateontheprocessingofcommonoperationsthatareappliedtoalldatatypesinaclasshierarchywithouttheknowledgeofindividualdetailsofeachdatatype.Thegeneralprocessingcapabilitiesareseparatedfromtheinternaldetailsofeachtype.Programminginthegernaralenablesyoutowritemoremaintainableandmodifyablesystems.Newdatatypescanbeaddedintothesystemaslongastheybelongtotheportionoftheclasshierarchybeingpolymorphicallyprocessed.27.12Discusstheproblemsofprogrammingwithswitchlogic.Explainwhypolymorphismisaneffectivealternativetousingswitchlogic.ANS:Themainproblemwithprogrammingusingtheswitchstructureistheextensibilityandmaintainabilityofthepro-gram.Aprogramcontainingmanyswitchstructuresisdifficulttomodify.Allthestructuresmustbemodifiedtohandletheprocessingofanadditionaltypeorofonelesstype.Polymorphismdeterminesthetypeofanobjectautomatically,soitisnotnecessarytodeterminethetypeofanobjecttoprocesstheobjectinagenericmanner.27.13Distinguishbetweeninheritinginterfaceandinheritingimplementation.Howdoinheritancehierarchiesdesignedforinher-itinginterfacedifferfromthosedesignedforinheritingimplementation?ANS:Whenaclassinheritsimplementation,itinheritspreviouslydefinedfunctionalityfromanotherclass.Whenaclassinheritsinterface,itinheritsthedefinitionofwhattheinterfacetothenewclasstypeshouldbe.Theimplementationisthenprovidedbytheprogrammerdefiningthenewclasstype.Inheritancehierarchiesdesignedforinheritingimplementationareusedtoreducetheamountofnewcodethatisbeingwritten.Suchhierarchiesarecommonlyusedtofacilitatesoftwarereusability.Inheritancehierarchiesdesignedforinheritinginterfaceareusedtowriteprogramsthatperformgenericpro-cessingofmanyclasstypes.Suchhierarchiesarecommonlyusedtofacilitatesoftwareextensibility(i.e.,newtypescanbeaddedtothehierarchywithoutchangingthegenericprocessingcapabilitiesoftheprogram).27.14Distinguishbetweennon-abstractmethodsandabstractmethods.ANS:Anon-abstractmethodprovidesimplementation.Anabstractmethoddoesnotprovideanyimplementation.27.15(True/False)Allmethodsinanabstractsuperclassmustbedeclaredabstract.ANS:False.Anabstractclassmusthaveatleastoneabstractmethod.Anynumberofmethodsintheclasscanbenon-abstract.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter27JavaObject-OrientedProgramming:Solutions61127.16SuggestoneormorelevelsofabstractsuperclassesfortheShapehierarchydiscussedinthebeginningofthischapter(thefirstlevelisShapeandthesecondlevelconsistsoftheclassesTwoDimensionalShapeandThreeDimensionalShape).27.17Howdoespolymorphismpromoteextensibility?ANS:Polymorphismmakesprogramsmoreextensiblebymakingallmethodcallsgeneric.Whenanewclasstypewiththeappropriatemethodsisaddedtothehierarchy,nochangesneedtobemadetothegenericmethodcallstoenableproc-cessingofthenewdatatype.27.18Youhavebeenaskedtodevelopaflightsimulatorthatwillhaveelaborategraphicaloutputs.Explainwhypolymorphicprogrammingwouldbeespeciallyeffectiveforaproblemofthisnature.27.19(DrawingApplication)ModifythedrawingprogramofExercise26.11tocreateadrawingapplicationthatdrawsrandomlines,rectanglesandovals.[Note:Likeanapplet,aJFramehasapaintmethodthatyoucanoverridetodrawonthebackgroundoftheJFrame.]Forthisexercise,modifytheMyLine,MyOvalandMyRectclassesofExercise26.11tocreatetheclasshierarchyinFig.27.8.TheclassesoftheMyShapehierarchyshouldbe“smart”shapeclasseswhereobjectsoftheseclassesknowhowtodrawthem-selves(ifprovidedwithaGraphicsobjectthattellsthemwheretodraw).Theonlyswitchorif/elselogicinthisprogramshouldbetodeterminethetypeofshapeobjecttocreate(userandomnumberstopicktheshapetypeandthecoordinatesofeachshape).Onceanobjectfromthishierarchyiscreated,itwillbemanipulatedfortherestofitslifetimeasasuperclassMyShaperef-erence.java.lang.ObjectMyShapeMyLineMyOvalMyRectFig.27.8TheMyShapehierarchy.ClassMyShapeinFig.27.8mustbeabstract.TheonlydatarepresentingthecoordinatesoftheshapesinthehierarchyshouldbedefinedinclassMyShape.Lines,rectanglesandovalscanallbedrawnifyouknowtwopointsinspace.Linesrequirex1,y1,x2andy2coordinates.ThedrawLinemethodoftheGraphicsclasswillconnectthetwopointssuppliedwithaline.Ifyouhavethesamefourcoordinatevalues(x1,y1,x2andy2)forovalsandrectangles,youcancalculatethefourargumentsneededtodrawthem.Eachrequiresanupper-leftx-coordinatevalue(minimumofthetwox-coordinatevalues),anupper-lefty-coordinatevalue(minimumofthetwoy-coordinatevalues),awidth(differencebetweenthetwox-coordinatevalues;mustbenonnegative)andaheight(differencebetweenthetwoy-coordinatevalues;mustbenonnegative).[Note:InChapter29,eachx,ypairwillbecapturedusingmouseeventsfrommouseinteractionsbetweentheuserandtheprogram’sbackground.Thesecoordinateswillbestoredinanappropriateshapeobjectasselectedbytheuser.Asyoubegintheexercise,youwilluserandomcoordinatevaluesasargumentstotheconstructor.]Inadditiontothedataforthehierarchy,classMyShapeshoulddefineatleastthefollowingmethods:a)Aconstructorwithnoargumentsthatsetsthecoordinatesto0.b)Aconstructorwithargumentsthatsetsthecoordinatestothesuppliedvalues.c)Setmethodsforeachindividualpieceofdatathatallowtheprogrammertoindependentlysetanypieceofdataforashapeinthehierarchy(e.g.,ifyouhaveaninstancevariablex1,youshouldhaveamethodsetX1).d)Getmethodsforeachindividualpieceofdatathatallowtheprogrammertoindependentlyretrieveanypieceofdataforashapeinthehierarchy(e.g.,ifyouhaveaninstancevariablex1,youshouldhaveamethodgetX1).e)Theabstractmethodpublicabstractvoiddraw(Graphicsg);Thismethodwillbecalledfromtheprogram’spaintmethodtodrawashapeontothescreen.Theprecedingmethodsarerequired.Ifyouwouldliketoprovidemoremethodsforflexibility,pleasedoso.However,besurethatanymethodyoudefineinthisclassisamethodthatwouldbeusedbyallshapesinthehierarchy.AlldatamustbeprivatetoclassMyShapeinthisexercise(thisforcesyoutouseproperencapsulationofthedataandpro-videproperset/getmethodstomanipulatethedata).Youarenotallowedtodefinenewdatathatcanbederivedfromexistinginfor-mation.Asexplainedpreviously,theupper-leftx,upper-lefty,widthandheightneededtodrawanovalorrectanglecanbecalculatedifyoualreadyknowtwopointsinspace.AllsubclassesofMyShapeshouldprovidetwoconstructorsthatmimicthoseprovidedbyclassMyShape.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com612JavaObject-OrientedProgramming:SolutionsChapter27ObjectsoftheMyOvalandMyRectclassesshouldnotcalculatetheirupper-leftx-coordinate,upper-lefty-coordinate,widthandheightuntiltheyareabouttodraw.Nevermodifythex1,y1,x2andy2coordinatesofaMyOvalorMyRectobjecttopreparetodrawthem.Instead,usethetemporaryresultsofthecalculationsdescribedabove.ThiswillhelpusenhancetheprograminChapter29byallowingtheusertoselecteachshape’scoordinateswiththemouse.ThereshouldbenoMyLine,MyOvalorMyRectreferencesintheprogram—onlyMyShapereferencesthatrefertoMyLine,MyOvalandMyRectobjectsareallowed.TheprogramshouldkeepanarrayofMyShapereferencescontainingallshapes.Theprogram’spaintmethodshouldwalkthroughthearrayofMyShapereferencesanddraweveryshape(i.e.,calleveryshape’sdrawmethod).BeginbydefiningclassMyShape,classMyLineandanapplicationtotestyourclasses.TheapplicationshouldhaveaMyShapeinstancevariablethatcanrefertooneMyLineobject(createdintheapplication’sconstructor).Thepaintmethod(foryoursubclassofJFrame)shoulddrawtheshapewithastatementlikecurrentShape.draw(g);wherecurrentShapeistheMyShapereferenceandgistheGraphicsobjectthattheshapewillusetodrawitselfontheback-groundofthewindow.Next,changethesingleMyShapereferenceintoanarrayofMyShapereferencesandhardcodeseveralMyLineobjectsintotheprogramfordrawing.Theapplication’spaintmethodshouldwalkthroughthearrayofshapesanddraweveryshape.Aftertheprecedingpartisworking,youshoulddefinetheMyOvalandMyRectclassesandaddobjectsoftheseclassesintotheexistingarray.Fornow,alltheshapeobjectsshouldbecreatedintheconstructorforyoursubclassofJFrame.InChapter29,wewillcreatetheobjectswhentheuserchoosesashapeandbeginsdrawingitwiththemouse.ANS:1//Exercise27.19Solution2//MyShape.java34importjava.awt.Graphics;56publicabstractclassMyShapeextendsObject{7privateintx1,x2,y1,y2;89publicMyShape()10{11setX1(0);12setX2(0);13setY1(0);14setY2(0);15}1617publicMyShape(intx1,inty1,intx2,inty2)18{19setX1(x1);20setX2(x2);21setY1(y1);22setY2(y2);23}2425publicvoidsetX1(intx1){this.x1=(x1>=0?x1:0);}26publicvoidsetX2(intx2){this.x2=(x2>=0?x2:0);}27publicvoidsetY1(inty1){this.y1=(y1>=0?y1:0);}28publicvoidsetY2(intx2){this.y2=(y2>=0?y2:0);}2930publicintgetX1(){returnx1;}31publicintgetX2(){returnx2;}32publicintgetY1(){returny1;}33publicintgetY2(){returny2;}3435publicabstractvoiddraw(Graphicsg);36}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter27JavaObject-OrientedProgramming:Solutions61337//Exercise27.19Solution38//MyLine.java39//DefinitionofclassMyLine40importjava.awt.Graphics;4142publicclassMyLineextendsMyShape{4344publicMyLine()45{46super();47}4849publicMyLine(intx1,inty1,intx2,inty2)50{51super(x1,y1,x2,y2);52}5354publicvoiddraw(Graphicsg)55{56g.drawLine(getX1(),getY1(),getX2(),getY2());57}58}59//Exercise27.19Solution60//MyOval.java61importjava.awt.Graphics;6263publicclassMyOvalextendsMyShape{6465publicMyOval()66{67super();68}6970publicMyOval(intx1,inty1,intx2,inty2)71{72super(x1,y1,x2,y2);73}7475publicvoiddraw(Graphicsg)76{77g.drawOval(Math.min(getX1(),getX2()),78Math.min(getY1(),getY2()),79Math.abs(getY2()-getY1()),80Math.abs(getX2()-getX1()));81}82}83//Exercise27.19Solution84//MyRect.java85importjava.awt.Graphics;8687publicclassMyRectextendsMyShape{8889publicMyRect()90{91super();92}9394publicMyRect(intx1,inty1,intx2,inty2)95{96super(x1,y1,x2,y2);97}98©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com614JavaObject-OrientedProgramming:SolutionsChapter2799publicvoiddraw(Graphicsg)100{101g.drawRect(Math.min(getX1(),getX2()),102Math.min(getY1(),getY2()),103Math.abs(getY2()-getY1()),104Math.abs(getX2()-getX1()));105}106}107//Exercise27.19Solution108//MyShape.java109110importjava.awt.Graphics;111112publicabstractclassMyShapeextendsObject{113privateintx1,x2,y1,y2;114115publicMyShape()116{117setX1(0);118setX2(0);119setY1(0);120setY2(0);121}122123publicMyShape(intx1,inty1,intx2,inty2)124{125setX1(x1);126setX2(x2);127setY1(y1);128setY2(y2);129}130131publicvoidsetX1(intx1){this.x1=(x1>=0?x1:0);}132publicvoidsetX2(intx2){this.x2=(x2>=0?x2:0);}133publicvoidsetY1(inty1){this.y1=(y1>=0?y1:0);}134publicvoidsetY2(intx2){this.y2=(y2>=0?y2:0);}135136publicintgetX1(){returnx1;}137publicintgetX2(){returnx2;}138publicintgetY1(){returny1;}139publicintgetY2(){returny2;}140141publicabstractvoiddraw(Graphicsg);142}143//Exercise27.19Solution144//TestDrawWindow.java145146importjava.awt.*;147importjavax.swing.*;148149publicclassTestDrawWindowextendsJFrame{150privateMyShapeshape[];151152publicTestDrawWindow()153{154super("Exercise9.28Tester");155shape=newMyShape[15];156157shape[0]=newMyLine(100,100,200,200);158shape[1]=newMyLine(200,200,100,100);159shape[2]=newMyLine(300,300,100,100);160shape[3]=newMyLine(400,400,0,0);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter27JavaObject-OrientedProgramming:Solutions615161shape[4]=newMyLine(100,100,300,300);162163shape[5]=newMyOval(100,100,200,200);164shape[6]=newMyOval(200,200,100,100);165shape[7]=newMyOval(300,300,100,100);166shape[8]=newMyOval(400,400,30,200);167shape[9]=newMyOval(100,100,300,300);168169shape[10]=newMyRect(100,100,200,200);170shape[11]=newMyRect(200,200,100,100);171shape[12]=newMyRect(300,300,100,100);172shape[13]=newMyRect(400,400,30,200);173shape[14]=newMyRect(100,100,300,300);174175setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);176}177178publicstaticvoidmain(Stringargs[])179{180TestDrawWindowwindow=newTestDrawWindow();181window.setSize(500,500);182window.show();183}184185publicvoidpaint(Graphicsg)186{187for(inti=0;i=13;i--)50keyPad.add(keys[i]);//.,=,add©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions6375152//setappletlayouttoborderlayout53getContentPane().setLayout(newBorderLayout());54getContentPane().add(lcd,BorderLayout.NORTH);55getContentPane().add(keyPad,BorderLayout.CENTER);56}57}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com638JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.10CreatethefollowingGUI.Youdonothavetoprovideanyfunctionality.ANS:1//Exercise29.10Solution2//Printer.java3//ThisprogramcreatesasimpleGUI4//html:width=400height=1305importjavax.swing.*;6importjava.awt.*;78publicclassPrinterextendsJApplet{9privateJButtonb1,b2,b3,b4;10privateJCheckBoxc1,c2,c3,c4;11privateJRadioButtonrb1,rb2,rb3;12privateButtonGroupradioGroup;13privateJComboBoxq;14privateJLabellabel1,label2;15privateJPanelp1,p2,p3,p4,p5,p6,p7,p8;1617publicvoidinit()18{19//buildleftnorthpanel20label1=newJLabel("Printer:EpsonEPL-7000");21p1=newJPanel();22p1.setLayout(newFlowLayout(FlowLayout.LEFT));23p1.add(label1);2425//buildrighteastpanel26b1=newJButton("Ok");27b2=newJButton("Cancel");28b3=newJButton("Setup...");29b4=newJButton("Help");30p2=newJPanel();31p2.setLayout(newGridLayout(4,1,5,5));32p2.add(b1);33p2.add(b2);34p2.add(b3);35p2.add(b4);3637//buildleftsouthpanel38label2=newJLabel("PrintQuality:");39q=newJComboBox();40q.addItem("High");41c1=newJCheckBox("PrinttoFile");42p3=newJPanel();43p3.setLayout(newFlowLayout(FlowLayout.CENTER,10,0));44p3.add(label2);45p3.add(q);46p3.add(c1);4748//buildlefteastpanel49c2=newJCheckBox("Image");50c3=newJCheckBox("Text");51c4=newJCheckBox("Code");52p4=newJPanel();©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions63953p4.setLayout(newBorderLayout());54p4.add(c2,BorderLayout.NORTH);55p4.add(c3,BorderLayout.CENTER);56p4.add(c4,BorderLayout.SOUTH);5758//buildleftwestpanel59p5=newJPanel();60p5.setLayout(newBorderLayout());61p5.add(rb1=newJRadioButton("Selection",false),62BorderLayout.NORTH);63p5.add(rb2=newJRadioButton("All",true),64BorderLayout.CENTER);65p5.add(rb3=newJRadioButton("Applet",false),66BorderLayout.SOUTH);67//Grouptheradiobuttons68radioGroup=newButtonGroup();69radioGroup.add(rb1);70radioGroup.add(rb2);71radioGroup.add(rb3);7273//buildleftcenter74p8=newJPanel();75p8.setLayout(newFlowLayout(FlowLayout.CENTER,30,0));76p8.setBackground(Color.white);77p8.add(p4);78p8.add(p5);7980//setupleftpanel81p6=newJPanel();82p6.setLayout(newBorderLayout());83p6.add(p1,BorderLayout.NORTH);84p6.add(p8,BorderLayout.CENTER);85p6.add(p3,BorderLayout.SOUTH);8687//setupappletlayout88p7=newJPanel();89p7.setLayout(newFlowLayout(FlowLayout.CENTER,10,0));90p7.add(p6);91p7.add(p2);9293getContentPane().add(p7);94}95}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com640JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.11WriteatemperatureconversionprogramthatconvertsfromFahrenheittoCelsius.TheFahrenheittemperatureshouldbeenteredfromthekeyboard(viaaJTextField).AJLabelshouldbeusedtodisplaytheconvertedtemperature.Usethefollowingformulafortheconversion:Celsius=5¤9×(Fahrenheit–32)ANS:1//Exercise29.11Solution2//Convert.java3//Temperatureconversionprogram4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassConvertextendsJFrame{9privateJPanelp;10privateJLabellabel1,label2;11privateJTextFieldtemperatureF;12privateJTextFieldtemperatureC;1314publicConvert()15{16label1=newJLabel("EnterFahrenheittemperature:");17label2=newJLabel("TemperatureinCelciusis:");18temperatureF=newJTextField(10);19temperatureF.addActionListener(20newActionListener(){21publicvoidactionPerformed(ActionEvente)22{23intcelcius,temp;2425temp=Integer.parseInt(temperatureF.getText());26celcius=(int)(5.0f/9.0f*(temp-32));27temperatureC.setText(String.valueOf(celcius));28}29}30);3132temperatureC=newJTextField(10);33temperatureC.setEditable(false);3435p=newJPanel();36p.setLayout(newBorderLayout());37p.add(temperatureF,BorderLayout.NORTH);38p.add(label2,BorderLayout.SOUTH);3940Containerc=getContentPane();41c.setLayout(newBorderLayout());42c.add(label1,BorderLayout.NORTH);43c.add(p,BorderLayout.CENTER);44c.add(temperatureC,BorderLayout.SOUTH);45setSize(200,150);46show();47}4849publicstaticvoidmain(Stringargs[])50{51Convertapp=newConvert();5253app.addWindowListener(54newWindowAdapter(){55publicvoidwindowClosing(WindowEvente)56{57System.exit(0);58}59}60);©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions64161}62}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com642JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.12Writeanapplicationthatallowstheusertodrawarectanglebydraggingthemouseontheapplicationwindow.Theupper-leftcoordinateshouldbethelocationwheretheuserpressesthemousebutton,andthelower-rightcoordinateshouldbethelocationwheretheuserreleasesthemousebutton.AlsodisplaytheareaoftherectangleinaJLabelintheSOUTHregionofaBorderLay-out.AlldrawingshouldbedoneonasubclassofJPanel.Usethefollowingformulaforthearea:area=width×heightANS:1//Exercise29.12Solution2//Draw.java3//Programdrawsarectanglewiththemouse4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassDrawextendsJFrame{9privateinttopX,topY;10privateintwidth,height;11privateintbottomX,bottomY;12protectedJLabelstatus;1314publicDraw()15{16super("Draw");17topX=topY=0;18addMouseListener(newMouseHandler(this));1920status=newJLabel();21getContentPane().add(status,BorderLayout.SOUTH);22setSize(300,150);23show();24}2526publicintgetTopX(){returntopX;}27publicintgetTopY(){returntopY;}28publicintgetWidth(){returnwidth;}29publicintgetHeight(){returnheight;}30publicintgetBottomX(){returnbottomX;}31publicintgetBottomY(){returnbottomY;}32publicvoidsetTopX(intx){topX=x;}33publicvoidsetTopY(inty){topY=y;}34publicvoidsetBottomX(intx){bottomX=x;}35publicvoidsetBottomY(inty){bottomY=y;}36publicvoidsetWidth(intw){width=w;}37publicvoidsetHeight(inth){height=h;}3839publicvoidpaint(Graphicsg)40{41super.paint(g);4243g.drawRect(topX,topY,width,height);44}4546publicstaticvoidmain(Stringargs[])47{48Drawapp=newDraw();4950app.addWindowListener(51newWindowAdapter(){52publicvoidwindowClosing(WindowEvente)53{54System.exit(0);55}56}57);58}59}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions6436061classMouseHandlerextendsMouseAdapter{62privateDrawdraw;6364publicMouseHandler(Drawd){draw=d;}6566publicvoidmouseReleased(MouseEvente)67{68draw.setBottomX(e.getX());69draw.setBottomY(e.getY());70draw.setWidth(Math.abs(draw.getTopX()-draw.getBottomX()));71draw.setHeight(Math.abs(draw.getTopY()-draw.getBottomY()));72draw.setTopX(Math.min(draw.getTopX(),draw.getBottomX()));73draw.setTopY(Math.min(draw.getTopY(),draw.getBottomY()));74draw.status.setText("Areais"+(draw.getWidth()*draw.getHeight()));75draw.repaint();76}7778publicvoidmousePressed(MouseEvente)79{80draw.setTopX(e.getX());81draw.setTopY(e.getY());82}83}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com644JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.13Writeaprogramthatdisplaysacircleofrandomsizeandcalculatesanddisplaysthearea,radius,diameterandcircumfer-ence.Usethefollowingequations:diameter=2×radius,area=p×radius2,circumference=2×p×radius.UsetheconstantMath.PIforpi(p).AlldrawingshouldbedoneonasubclassofJPanelandtheresultsofthecalculationsshouldbedisplayedinaread-onlyJTextArea.ANS:1//Exercise29.13Solution2//Circle1.java3//Programdrawsacircleofarandom4//diameteranddisplaysthearea,diameter,5//andcircumference.6importjavax.swing.*;7importjava.awt.*;8importjava.awt.event.*;910publicclassCircle1extendsJFrame{11privateCircleCanvastheCanvas;12privateJTextAreadisplay;1314publicCircle1()15{16super("Circle1");17theCanvas=newCircleCanvas();18display=newJTextArea(5,30);1920display.setText("TheRadiusis:"+theCanvas.getRadius()+21"nTheDiameteris:"+theCanvas.getDiameter()22+"nTheAreais:"+theCanvas.getArea()+23"nTheCircumferenceis:"+24theCanvas.getCircumference());2526getContentPane().add(theCanvas,BorderLayout.CENTER);27getContentPane().add(display,BorderLayout.SOUTH);28setSize(200,200);29show();30}3132publicstaticvoidmain(Stringargs[])33{34Circle1app=newCircle1();3536app.addWindowListener(37newWindowAdapter(){38publicvoidwindowClosing(WindowEvente)39{40System.exit(0);41}42}43);44}45}4647classCircleCanvasextendsJPanel{48privateintradius;4950publicCircleCanvas()51{52radius=(int)(1+Math.random()*100);53setSize(100,100);54}5556publicvoidpaintComponent(Graphicsg)57{g.drawOval(0,0,radius,radius);}5859publicintgetDiameter(){return(2*radius);}60©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions64561publicintgetCircumference()62{return(int)(2*Math.PI*radius);}6364publicintgetArea()65{return(int)(radius*radius*Math.PI);}6667publicintgetRadius(){returnradius;}68}29.14WriteaprogramthatusesSystem.out.printlnstatementstoprintouteventsastheyoccur.ProvideaJComboBoxwithaminimumoffouritems.Theusershouldbeabletochooseaneventto“monitor”fromtheJComboBox.Whenthatparticulareventoccurs,displayinformationabouttheeventinamessagedialogbox.UsemethodtoStringontheeventobjecttoconvertittoastringrepresentation.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com646JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.15WriteaprogramusingmethodsfrominterfaceMouseListenerthatallowstheusertopressthemousebutton,dragthemouseandreleasethemousebutton.Whenthemouseisreleased,drawarectanglewiththeappropriateupper-leftcorner,widthandheight.(Hint:ThemousePressedmethodshouldcapturethesetofcoordinatesatwhichtheuserpressesandholdsthemousebuttoninitially,andthemouseReleasedmethodshouldcapturethesetofcoordinatesatwhichtheuserreleasesthemousebutton.Bothmethodsshouldstoretheappropriatecoordinatevalues.AlldrawingshouldbedoneonasubclassofJPanelandallcalcula-tionsofthewidth,heightandupper-leftcornershouldbeperformedbythepaintComponentmethodbeforetheshapeisdrawn).ANS:1//Exercise29.15Solution2//Draw.java3//Programdrawsarectanglewiththemouse4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassDrawextendsJFrame{9privateinttopX,topY;10privateintwidth,height,upperX,upperY;11privateintbottomX,bottomY;1213publicDraw()14{15super("Draw");16addMouseListener(newMouseHandler());17setSize(300,200);18show();19}2021publicvoidsetTopX(intx){topX=x;}22publicvoidsetTopY(inty){topY=y;}23publicvoidsetBottomX(intx){bottomX=x;}24publicvoidsetBottomY(inty){bottomY=y;}2526publicvoidpaint(Graphicsg)27{28super.paint(g);2930width=Math.abs(topX-bottomX);31height=Math.abs(topY-bottomY);32upperX=Math.min(topX,bottomX);33upperY=Math.min(topY,bottomY);3435g.drawRect(upperX,upperY,width,height);36}3738publicstaticvoidmain(Stringargs[])39{40Drawapp=newDraw();4142app.addWindowListener(43newWindowAdapter(){44publicvoidwindowClosing(WindowEvente)45{46System.exit(0);47}48}49);50}5152privateclassMouseHandlerextendsMouseAdapter{53publicvoidmouseReleased(MouseEvente)54{55setBottomX(e.getX());56setBottomY(e.getY());57repaint();58}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions6475960publicvoidmousePressed(MouseEvente)61{62setTopX(e.getX());63setTopY(e.getY());64}65}66}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com648JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.16ModifyExercise29.15toprovideda“rubber-banding”effect.Astheuserdragsthemouse,theusershouldbeabletoseethecurrentsizeoftherectangletoknowexactlywhattherectanglewilllooklikewhenthemousebuttonisreleased.(Hint:MethodmouseDraggedshouldperformthesametasksasmouseReleased).ANS:1//Exercise29.16Solution2//Draw3.java3//Programdrawsarectanglewiththemouse4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassDraw3extendsJFrame{9privateinttopX,topY;10privateintwidth,height,upperX,upperY;11privateintbottomX,bottomY;1213publicDraw3()14{15super("Draw3");16addMouseListener(newMouseHandler());17addMouseMotionListener(newMouseMotionHandler());18setSize(300,200);19show();20}2122publicvoidsetTopX(intx){topX=x;}23publicvoidsetTopY(inty){topY=y;}24publicvoidsetBottomX(intx){bottomX=x;}25publicvoidsetBottomY(inty){bottomY=y;}2627publicvoidpaint(Graphicsg)28{29super.paint(g);3031width=Math.abs(topX-bottomX);32height=Math.abs(topY-bottomY);33upperX=Math.min(topX,bottomX);34upperY=Math.min(topY,bottomY);3536g.drawRect(upperX,upperY,width,height);37}3839publicstaticvoidmain(Stringargs[])40{41Draw3app=newDraw3();4243app.addWindowListener(44newWindowAdapter(){45publicvoidwindowClosing(WindowEvente)46{47System.exit(0);48}49}50);51}5253privateclassMouseHandlerextendsMouseAdapter{54publicvoidmouseReleased(MouseEvente)55{56setBottomX(e.getX());57setBottomY(e.getY());58repaint();59}6061publicvoidmousePressed(MouseEvente)62{©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions64963setTopX(e.getX());64setTopY(e.getY());65}66}6768privateclassMouseMotionHandlerextendsMouseMotionAdapter{69publicvoidmouseDragged(MouseEvente)70{71setBottomX(e.getX());72setBottomY(e.getY());73repaint();74}75}76}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com650JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.17ModifyExercise29.16toallowtheusertoselectwhichshapetodraw.AJComboBoxshouldprovideoptionsincludingatleastrectangle,oval,lineandroundedrectangle.ANS:1//Exercise29.17Solution2//Draw3.java3//Programdrawsarectanglewiththemouse4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassDraw3extendsJFrame{9privateinttopX,topY;10privateintwidth,height,upperX,upperY;11privateintbottomX,bottomY;12privatefinalintCIRCLE=0;13privatefinalintSQUARE=1;14privatefinalintOVAL=2;15privatefinalintRECTANGLE=3;16privateJComboBoxchoice;17privateintshape;18privateToolWindowtools;1920publicDraw3()21{22super("Draw3");23addMouseListener(newMouseHandler());24addMouseMotionListener(newMouseMotionHandler());2526//setdefaultshapetoCircle27shape=CIRCLE;2829setSize(300,200);30show();31tools=newToolWindow();32}3334publicvoidsetTopX(intx){topX=x;}35publicvoidsetTopY(inty){topY=y;}36publicvoidsetBottomX(intx){bottomX=x;}37publicvoidsetBottomY(inty){bottomY=y;}38publicvoidsetShape(ints){shape=s;}3940publicvoidpaint(Graphicsg)41{42super.paint(g);4344width=Math.abs(topX-bottomX);45height=Math.abs(topY-bottomY);46upperX=Math.min(topX,bottomX);47upperY=Math.min(topY,bottomY);4849switch(shape){50caseCIRCLE:51g.drawOval(upperX,upperY,width,width);52break;53caseSQUARE:54g.drawRect(upperX,upperY,width,width);55break;56caseOVAL:57g.drawOval(upperX,upperY,width,height);58break;59caseRECTANGLE:60g.drawRect(upperX,upperY,width,height);61break;62}63}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions6516465publicstaticvoidmain(Stringargs[])66{67Draw3app=newDraw3();6869app.addWindowListener(70newWindowAdapter(){71publicvoidwindowClosing(WindowEvente)72{73System.exit(0);74}75}76);77}7879privateclassToolWindowextendsJFrame{80publicToolWindow()81{82choice=newJComboBox();83choice.addItem("Circle");84choice.addItem("Square");85choice.addItem("Oval");86choice.addItem("Rectangle");8788choice.addItemListener(89newItemListener(){90publicvoiditemStateChanged(ItemEvente)91{92setShape(choice.getSelectedIndex());93repaint();94}95}96);9798//setdefaultshapetoCircle99shape=CIRCLE;100101Containerc=getContentPane();102c.setLayout(newBorderLayout());103c.add(choice,BorderLayout.SOUTH);104105pack();106setLocation(300,0);107show();108}109}110111privateclassMouseHandlerextendsMouseAdapter{112publicvoidmouseReleased(MouseEvente)113{114setBottomX(e.getX());115setBottomY(e.getY());116repaint();117}118119publicvoidmousePressed(MouseEvente)120{121setTopX(e.getX());122setTopY(e.getY());123}124}125126privateclassMouseMotionHandlerextendsMouseMotionAdapter{127publicvoidmouseDragged(MouseEvente)128{129setBottomX(e.getX());130setBottomY(e.getY());131repaint();132}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com652JavaGraphicalUserInterfaceComponents:SolutionsChapter29133}134}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions65329.18ModifyExercise29.17toallowtheusertoselectthedrawingcolorfromaJColorChooserdialogbox.ANS:1//Exercise29.18Solution2//Draw3.java3//Programdrawsarectanglewiththemouse4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassDraw3extendsJFrame{9privateinttopX,topY;10privateintwidth,height,upperX,upperY;11privateintbottomX,bottomY;12privatefinalintCIRCLE=0;13privatefinalintSQUARE=1;14privatefinalintOVAL=2;15privatefinalintRECTANGLE=3;16privateJComboBoxchoice;17privateintshape;18privateToolWindowtools;19privateJButtonchooseColor;20privateColorcolor;2122publicDraw3()23{24super("Draw3");25addMouseListener(newMouseHandler());26addMouseMotionListener(newMouseMotionHandler());2728//setdefaultshapetoCircle29shape=CIRCLE;3031setSize(300,200);32show();33tools=newToolWindow();34}3536publicvoidsetTopX(intx){topX=x;}37publicvoidsetTopY(inty){topY=y;}38publicvoidsetBottomX(intx){bottomX=x;}39publicvoidsetBottomY(inty){bottomY=y;}40publicvoidsetShape(ints){shape=s;}4142publicvoidpaint(Graphicsg)43{44super.paint(g);4546g.setColor(color);4748width=Math.abs(topX-bottomX);49height=Math.abs(topY-bottomY);50upperX=Math.min(topX,bottomX);51upperY=Math.min(topY,bottomY);5253switch(shape){54caseCIRCLE:55g.drawOval(upperX,upperY,width,width);56break;57caseSQUARE:58g.drawRect(upperX,upperY,width,width);59break;60caseOVAL:61g.drawOval(upperX,upperY,width,height);62break;63caseRECTANGLE:64g.drawRect(upperX,upperY,width,height);65break;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com654JavaGraphicalUserInterfaceComponents:SolutionsChapter2966}67}6869publicstaticvoidmain(Stringargs[])70{71Draw3app=newDraw3();7273app.addWindowListener(74newWindowAdapter(){75publicvoidwindowClosing(WindowEvente)76{77System.exit(0);78}79}80);81}8283privateclassToolWindowextendsJFrame{84publicToolWindow()85{86choice=newJComboBox();87choice.addItem("Circle");88choice.addItem("Square");89choice.addItem("Oval");90choice.addItem("Rectangle");9192choice.addItemListener(93newItemListener(){94publicvoiditemStateChanged(ItemEvente)95{96setShape(choice.getSelectedIndex());97repaint();98}99}100);101102Containerc=getContentPane();103c.add(choice,BorderLayout.SOUTH);104105chooseColor=newJButton("PickColor");106chooseColor.addActionListener(107newActionListener(){108publicvoidactionPerformed(ActionEvente)109{110color=JColorChooser.showDialog(null,"PickColor",Color.black);111}112}113);114c.add(chooseColor,BorderLayout.NORTH);115116pack();117setLocation(300,0);118show();119}120}121122privateclassMouseHandlerextendsMouseAdapter{123publicvoidmouseReleased(MouseEvente)124{125setBottomX(e.getX());126setBottomY(e.getY());127repaint();128}129130publicvoidmousePressed(MouseEvente)131{132setTopX(e.getX());133setTopY(e.getY());134}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions655135}136137privateclassMouseMotionHandlerextendsMouseMotionAdapter{138publicvoidmouseDragged(MouseEvente)139{140setBottomX(e.getX());141setBottomY(e.getY());142repaint();143}144}145}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com656JavaGraphicalUserInterfaceComponents:SolutionsChapter2929.19ModifyExercise29.18toallowtheusertospecifyifashapeshouldbefilledoremptywhenitisdrawn.TheusershouldclickaJCheckBoxtoindicatefilledorempty.ANS:1//Exercise29.19Solution2//Draw3.java3//Programdrawsarectanglewiththemouse4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassDraw3extendsJFrame{9privateinttopX,topY;10privateintwidth,height,upperX,upperY;11privateintbottomX,bottomY;12privatefinalintCIRCLE=0;13privatefinalintSQUARE=1;14privatefinalintOVAL=2;15privatefinalintRECTANGLE=3;16privateJComboBoxchoice;17privateintshape;18privateToolWindowtools;19privateJButtonchooseColor;20privateColorcolor;21privateJCheckBoxfilled;2223publicDraw3()24{25super("Draw3");26addMouseListener(newMouseHandler());27addMouseMotionListener(newMouseMotionHandler());2829//setdefaultshapetoCircle30shape=CIRCLE;3132tools=newToolWindow();33setSize(300,200);34show();35}3637publicvoidsetTopX(intx){topX=x;}38publicvoidsetTopY(inty){topY=y;}39publicvoidsetBottomX(intx){bottomX=x;}40publicvoidsetBottomY(inty){bottomY=y;}41publicvoidsetShape(ints){shape=s;}4243publicvoidpaint(Graphicsg)44{45super.paint(g);4647g.setColor(color);4849width=Math.abs(topX-bottomX);50height=Math.abs(topY-bottomY);51upperX=Math.min(topX,bottomX);52upperY=Math.min(topY,bottomY);5354if(filled.isSelected())55switch(shape){56caseCIRCLE:57g.fillOval(upperX,upperY,width,width);58break;59caseSQUARE:60g.fillRect(upperX,upperY,width,width);61break;62caseOVAL:63g.fillOval(upperX,upperY,width,height);64break;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions65765caseRECTANGLE:66g.fillRect(upperX,upperY,width,height);67break;68}69else70switch(shape){71caseCIRCLE:72g.drawOval(upperX,upperY,width,width);73break;74caseSQUARE:75g.drawRect(upperX,upperY,width,width);76break;77caseOVAL:78g.drawOval(upperX,upperY,width,height);79break;80caseRECTANGLE:81g.drawRect(upperX,upperY,width,height);82break;83}84}8586publicstaticvoidmain(Stringargs[])87{88Draw3app=newDraw3();8990app.addWindowListener(91newWindowAdapter(){92publicvoidwindowClosing(WindowEvente)93{94System.exit(0);95}96}97);98}99100privateclassToolWindowextendsJFrame{101publicToolWindow()102{103choice=newJComboBox();104choice.addItem("Circle");105choice.addItem("Square");106choice.addItem("Oval");107choice.addItem("Rectangle");108109choice.addItemListener(110newItemListener(){111publicvoiditemStateChanged(ItemEvente)112{113setShape(choice.getSelectedIndex());114repaint();115}116}117);118119Containerc=getContentPane();120c.add(choice,BorderLayout.SOUTH);121122chooseColor=newJButton("PickColor");123chooseColor.addActionListener(124newActionListener(){125publicvoidactionPerformed(ActionEvente)126{127color=JColorChooser.showDialog(null,"PickColor",Color.black);128}129}130);131c.add(chooseColor,BorderLayout.NORTH);132©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com658JavaGraphicalUserInterfaceComponents:SolutionsChapter29133filled=newJCheckBox("Filled");134c.add(filled,BorderLayout.CENTER);135136pack();137setLocation(300,0);138show();139}140}141142privateclassMouseHandlerextendsMouseAdapter{143publicvoidmouseReleased(MouseEvente)144{145setBottomX(e.getX());146setBottomY(e.getY());147repaint();148}149150publicvoidmousePressed(MouseEvente)151{152setTopX(e.getX());153setTopY(e.getY());154}155}156157privateclassMouseMotionHandlerextendsMouseMotionAdapter{158publicvoidmouseDragged(MouseEvente)159{160setBottomX(e.getX());161setBottomY(e.getY());162repaint();163}164}165}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter29JavaGraphicalUserInterfaceComponents:Solutions65929.20(CompleteDrawingApplication)UsingthetechniquesdevelopedinExercises29.12through29.19,createacompletedrawingprogram.TheprogramshouldusetheGUIcomponentsofthischaptertoenabletheusertoselecttheshape,colorandfillcharacteristics.Forthisprogram,createyourownclasses(likethoseintheclasshierarchydescribedinExercise27.19)fromwhichobjectswillbecreatedtostoreeachshapetheuserdraws.Theclassesshouldstorethelocation,dimensionsandcolorofeachshapeandshouldindicateiftheshapeisfilledorunfilled.YourclassesshouldallderivefromaclasscalledMyShapethathasallthecom-monfeaturesofeveryshapetype.EverysubclassofMyShapeshouldhaveitsownmethoddraw,whichreturnsvoidandreceivesaGraphicsobjectasitsargument.CreateasubclassofJPanelcalledDrawPanelfordrawingtheshapes.WhentheDrawPanel’spaintComponentmethodiscalled,itshouldwalkthroughthearrayofshapesanddisplayeachshapebypolymorphicallycallingtheshape’sdrawmethod(passingtheGraphicsobjectasanargument).Eachshape’sdrawmethodshouldknowhowtodrawtheshape.Asaminimum,yourprogramshouldprovidethefollowingclasses:MyLine,MyOval,MyRect,MyRoundRect.Designtheclasshierarchyformaximumsoftwarereuseandplaceallyourclassesinthepackageshapes.Importthispackageintoyourpro-gram.EachshapeshouldbestoredinanarrayofMyShapeobjects,whereMyShapeisthesuperclassinyourhierarchyofshapeclasses(seeExercise27.19).29.21ModifyExercise29.20toprovideanUndobuttonthatcanbeusedrepeatedlytoundothelastpaintingoperation.Iftherearenoshapesinthearrayofshapes,theUndobuttonshouldbedisabled.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com660JavaGraphicalUserInterfaceComponents:SolutionsChapter29©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com30JavaMultimedia:Images,Animation,andAudio:SolutionsEXERCISES30.3Describehowtomakeananimation“browserfriendly.”ANS:Begintheanimationinthestartmethodandsuspend/terminatetheanimationinthestopmethod.30.4DiscussthevariousaspectsofflickereliminationinJava.ANS:Flickeringcanbereducedoreliminatedbyoverridingthepaintmethodandusinggraphicsdoublebufferingtech-niques.30.5Explainthetechniqueofgraphicsdoublebuffering.ANS:MethodcreateImageisusedtocreateanemptyimage.ThegraphicscontextoftheemptyimageisretrievedwithacalltogetGraphics.TheemptyimagecanthenbeusedtostorepixelsdrawnontheimagewiththeGraphicsobjectthatwasobtainedviagetGraphics.Whentheimageiscomplete,itcanbedisplayedusingmethoddrawImage.SwingcomponentssuchasJPanelhavebuilt-indoublebuffering.30.6DescribetheJavamethodsforplayingandmanipulatingaudioclips.ANS:Theappletplaymethod.TheAudioClipinterfacemethods:play,loopandstop.30.7(Animation)Createaageneral-purposeJavaanimationprogram.Yourprogramshouldallowtheusertospecifythese-quenceofframestobedisplayed,thespeedatwhichtheimagesaredisplayed,audiosthatshouldbeplayedwhiletheanimationisrunningandsoon.30.8(Screensaver)Useanimationofaseriesofyourfavoriteimagestocreateascreensaverprogram.Createvariousspecialeffectsthatexplodetheimages,spintheimages,fadetheminandout,movethemofftheedgeofthescreen,andthelike.©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com662JavaMultimedia:Images,Animation,andAudio:SolutionsChapter3030.9(RandomlyErasinganImage)Supposeanimageisdisplayedinarectangularscreenarea.Onewaytoerasetheimageissimplytoseteverypixeltothesamecolorimmediately,butthisisadullvisualeffect.WriteaJavaprogramthatdisplaysanimagethenerasesitbyusingrandom-numbergenerationtoselectindividualpixelstoerase.Aftermostoftheimageiserased,erasealloftheremainingpixelsatonce.Youcanrefertoindividualpixelsbyhavingalinethatstartsandendsatthesamepoint.Youmighttryseveralvariantsofthisproblem.Forexample,youmightdisplaylinesrandomlyoryoumightdisplayshapesrandomlytoeraseregionsofthescreen.ANS:1//Exercise30.9Solution2//Eraser.java3//Programrandomlycoversupanimage.4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassEraserextendsJAppletimplementsActionListener{9privateImageIconimage;10privateintimageWidth,imageHeight,count;11privateintnumberOfTimes;12privatebooleanshowImage=true;13privateTimert;1415publicvoidinit()16{17image=newImageIcon("icons2.gif");18t=newTimer(10,this);19t.start();2021imageWidth=image.getIconWidth();22imageHeight=image.getIconHeight();23numberOfTimes=imageWidth*imageHeight/8;24}2526publicvoidpaint(Graphicsg)27{28if(showImage==true){29image.paintIcon(this,getGraphics(),0,0);30showImage=false;31}3233g.setColor(getBackground());34g.fillRect((int)(Math.random()*imageWidth),35(int)(Math.random()*imageHeight),4,4);36}3738publicvoidactionPerformed(ActionEvente)39{40repaint();4142if(count==numberOfTimes){43showImage=true;44count=0;45}4647++count;48}49}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter30JavaMultimedia:Images,Animation,andAudio:Solutions663©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com664JavaMultimedia:Images,Animation,andAudio:SolutionsChapter3030.10(TextFlasher)CreateaJavaprogramthatrepeatedlyflashestextonthescreen.Dothisbyinterspersingthetextwithaplainbackgroundcolorimage.Allowtheusertocontrolthe“blinkspeed”andthebackgroundcolororpattern.ANS:1//Exercise30.10Solution2//Flash.java3//Programflashestext.4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassFlashextendsJApplet9implementsActionListener,ItemListener{10privateMyCanvastheCanvas;11privateJComboBoxcolorSelect;12privateJLabelprompt;13privateJTextFieldinput;1415publicvoidinit()16{17prompt=newJLabel("Enterrate(50-200):");18input=newJTextField(5);19input.addActionListener(this);20theCanvas=newMyCanvas();21Stringitems[]={"Black","Red","Blue","Green"};22colorSelect=newJComboBox(items);23colorSelect.addItemListener(this);24Containerc=getContentPane();25c.setLayout(newFlowLayout());26c.add(theCanvas);27c.add(colorSelect);28c.add(prompt);29c.add(input);30}3132publicvoiditemStateChanged(ItemEvente)33{34Colorc;3536if(e.getItem().equals("Black"))37c=Color.black;38elseif(e.getItem().equals("Red"))39c=Color.red;40elseif(e.getItem().equals("Blue"))41c=Color.blue;42else43c=Color.green;4445theCanvas.setBackground(c);46}4748publicvoidactionPerformed(ActionEvente)49{50theCanvas.setSleepTime(Integer.parseInt(input.getText()));51showStatus("currentblinkrate:"+theCanvas.getSleepTime());52}53}5455classMyCanvasextendsJPanelimplementsActionListener{56privateStringtext;57privateTimert;©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter30JavaMultimedia:Images,Animation,andAudio:Solutions66558privateColorc=Color.black;59booleanflash=true;6061publicMyCanvas()62{63setBackground(Color.black);64t=newTimer(150,this);65t.start();66text="Flash!";67setSize(100,100);68setOpaque(true);69}7071publicsynchronizedvoidpaintComponent(Graphicsg)72{73super.paintComponent(g);7475if(flash){76g.setColor(Color.yellow);77g.drawString(text,10,20);78}79}8081publicsynchronizedvoidactionPerformed(ActionEvente)82{83flash=!flash;84repaint();85}8687publicvoidsetSleepTime(inttime)88{t.setDelay(time>=50&&time<=200?time:150);}8990publicintgetSleepTime(){returnt.getDelay();}9192publicDimensiongetPreferredSize()93{94returnnewDimension(100,100);95}96}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com666JavaMultimedia:Images,Animation,andAudio:SolutionsChapter3030.11(ImageFlasher)CreateaJavaprogramthatrepeatedlyflashesanimageonthescreen.Dothisbyinterspersingtheimagewithaplainbackgroundcolorimage.ANS:1//Exercise30.11Solution2//Flash2.java3//Programflashestext.4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassFlash2extendsJApplet9implementsActionListener,ItemListener{10privateMyCanvastheCanvas;11privateJComboBoxcolorSelect;12privateJLabelprompt;13privateJTextFieldinput;1415publicvoidinit()16{17prompt=newJLabel("Enterrate(50-1000):");18input=newJTextField(5);19input.addActionListener(this);20theCanvas=newMyCanvas();21Stringitems[]={"Black","Red","Blue","Green"};22colorSelect=newJComboBox(items);23colorSelect.addItemListener(this);24Containerc=getContentPane();25c.setLayout(newFlowLayout());26c.add(theCanvas);27c.add(colorSelect);28c.add(prompt);29c.add(input);30}3132publicvoiditemStateChanged(ItemEvente)33{34Colorc;3536if(e.getItem().equals("Black"))37c=Color.black;38elseif(e.getItem().equals("Red"))39c=Color.red;40elseif(e.getItem().equals("Blue"))41c=Color.blue;42else43c=Color.green;4445theCanvas.setBackground(c);46}4748publicvoidactionPerformed(ActionEvente)49{50theCanvas.setSleepTime(Integer.parseInt(input.getText()));51showStatus("currentblinkrate:"+theCanvas.getSleepTime());52}53}5455classMyCanvasextendsJPanelimplementsActionListener{56privateImageIconimage;57privateTimert;58booleanflash=true;5960publicMyCanvas()61{62setBackground(Color.black);63image=newImageIcon("icons2.gif");©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter30JavaMultimedia:Images,Animation,andAudio:Solutions66764t=newTimer(500,this);65t.start();66}6768publicsynchronizedvoidpaintComponent(Graphicsg)69{70super.paintComponent(g);7172if(flash)73g.drawImage(image.getImage(),0,0,this);74}7576publicsynchronizedvoidactionPerformed(ActionEvente)77{78flash=!flash;79repaint();80}8182publicvoidsetSleepTime(inttime)83{t.setDelay(time>=50&&time<=1000?time:500);}8485publicintgetSleepTime(){returnt.getDelay();}8687publicDimensiongetPreferredSize()88{89returnnewDimension(image.getIconWidth(),90image.getIconHeight());91}92}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.com668JavaMultimedia:Images,Animation,andAudio:SolutionsChapter3030.12(DigitalClock)Implementaprogramthatdisplaysadigitalclockonthescreen.Youmightaddoptionstoscaletheclock;displayday,monthandyear;issueanalarm;playcertainaudiosatdesignatedtimesandthelike.ANS:1//Exercise30.12Solution2//DigitalClock.java3//Programcreatesadigitalclock.4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;7importjava.util.*;89publicclassDigitalClockextendsJApplet10implementsActionListener{11privateStringtheTime;12privateTimert;1314publicvoidinit()15{16theTime="";17t=newTimer(1000,this);18}1920publicvoidpaint(Graphicsg)21{22super.paint(g);//clearsthebackground2324g.drawString(theTime,20,50);25}2627publicvoidstart()28{29t.start();30}3132publicvoidstop()33{34t.stop();35}3637publicvoidactionPerformed(ActionEvente)38{39theTime=newDate().toString();40repaint();41}42}©Copyright1992–2004byDeitel&Associates,Inc.andPearsonEducationInc.AllRightsReserved. 课后答案网www.khdaw.comChapter30JavaMultimedia:Images,Animation,andAudio:Solutions66930.13(Callingattentiontoanimage)Ifyouwanttoemphasizeanimage,youmightplacearowofsimulatedlightbulbsaroundyourimage.Youcanletthelightbulbsflashinunisonoryoucanletthemfireonandoffinsequenceoneaftertheother.ANS:1//Exercise30.13Solution2//Flash3.java3//Programhighlightsanimage.4importjavax.swing.*;5importjava.awt.*;6importjava.awt.event.*;78publicclassFlash3extendsJApplet{9privateMyCanvastheCanvas;1011publicvoidinit()12{13ImageIconimage1=newImageIcon("icons2.gif");1415intwidth=image1.getIconWidth()+20;16intheight=image1.getIconHeight()+20;17Imageimage2=createImage(width,height);18Imageimage3=createImage(width,height);1920theCanvas=newMyCanvas(image1.getImage(),image2,image3,21width,height);22getContentPane().add(theCanvas,BorderLayout.CENTER);23}24}2526classMyCanvasextendsJPanelimplementsActionListener{27privateImageimg,img2,img3;28privateGraphicsgraph2,graph3;29privatebooleanflashSwitch;30privateTimert;3132publicMyCanvas(Imagei,Imagei2,Imagei3,intw,inth)33{34t=newTimer(300,this);35t.start();36flashSwitch=true;37setSize(w,h);38img=i;39img2=i2;40img3=i3;41createBuffers(w,h);42}4344publicvoidcreateBuffers(intw,inth)45{46graph2=img2.getGraphics();47graph3=img3.getGraphics();4849graph2.setColor(Color.black);50graph2.fillRect(0,0,w,h);51graph3.setColor(Color.black);52graph3.fillRect(0,0,w,h);5354intcount=0;5556for(intx=0;x