- 3.97 MB
- 2022-04-22 11:48:16 发布
- 1、本文档共5页,可阅读全部内容。
- 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
- 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
- 文档侵权举报电话: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"&&count