SOWGG AnswersToCheckpoints
SOWGG AnswersToCheckpoints
Chapter1
1.1 1.2 1.3 Whatisaprogram? Answer:Aprogramisasetofinstructionsthatacomputerfollowstoperformatask. Whatishardware? Answer:Hardwareisallofthephysicaldevices,orcomponents,thatacomputerismadeof. Listthefivemajorcomponentsofacomputersystem. Answer:Thecentralprocessingunit(CPU),mainmemory,secondarystoragedevices,input devices,andoutputdevices. Whatpartofthecomputeractuallyrunsprograms? Answer:TheCPU Whatpartofthecomputerservesasaworkareatostoreaprogramanditsdatawhilethe programisrunning? Answer:Mainmemory Whatpartofthecomputerholdsdataforlongperiodsoftime,evenwhenthereisnopowerto thecomputer? Answer:Secondarystorage Whatpartofthecomputercollectsdatafrompeopleandfromotherdevices? Answer:Inputdevice Whatpartofthecomputerformatsandpresentsdataforpeopleorotherdevices? Answer:Outputdevice Whatamountofmemoryisenoughtostorealetterofthealphabetorasmallnumber? Answer:Onebyte Whatdoyoucallatiny"switch"thatcanbesettoeitheronoroff? Answer:Abit Inwhatnumberingsystemareallnumericvalueswrittenassequencesof0sand1s? Answer:Thebinarynumberingsystem. WhatisthepurposeofASCII? Answer:Itisanencodingschemethatusesasetof128numericcodestorepresenttheEnglish letters,variouspunctuationmarks,andothercharacters.Thesenumericcodesareusedtostore charactersinacomputer'smemory.(ASCIIstandsfortheAmericanStandardCodefor InformationInterchange.) Whatencodingschemeisextensivetorepresentallthecharactersofmostofthelanguagesin theworld? Answer:Unicode Whatdotheterms"digitaldata"and"digitaldevice"mean? Answer:Digitaldataisdatathatisstoredinbinary,andadigitaldeviceisanydevicethatworks withbinarydata.
1.4 1.5
1.6
1.13
1.14
1.19
1.20
1.21
1.22
1.23
ACPUunderstandsinstructionsthatarewrittenonlyinwhatlanguage? Answer:machinelanguage AprogramhastobecopiedintowhattypeofmemoryeachtimetheCPUexecutesit? Answer:Mainmemory,orRAM WhenaCPUexecutestheinstructionsinaprogram,itisengagedinwhatprocess? Answer:Thefetchdecodeexecutecycle. Whatisassemblylanguage? Answer:Itisanalternativetomachinelanguage.Insteadofusingbinarynumbersfor instructions,assemblylanguageusesshortwordsthatareknownasmnemonics. Whattypeofprogramminglanguageallowsyoutocreatepowerfulandcomplexprograms withoutknowinghowtheCPUworks? Answer:Ahighlevellanguage Eachlanguagehasasetofrulesthatmustbestrictlyfollowedwhenwritingaprogram.Whatis thissetofrulescalled? Answer:Syntax Whatdoyoucallaprogramthattranslatesahighlevellanguageprogramintoaseparate machinelanguageprogram? Answer:Acompiler Whatdoyoucallaprogramthatbothtranslatesandexecutestheinstructionsinahighlevel languageprogram? Answer:Aninterpreter Whattypeofmistakeisusuallycausedbyamisspelledkeyword,amissingpunctuation character,ortheincorrectuseofanoperator? Answer:Asyntaxerror
Chapter2
2.1 Thefollowingprogramwillnotcompilebecausethestatementsaremixedup. { void DarkGDK() } // This is a mixed up program. dbWaitKey(); #include "DarkGDK.h" Whenthelinesareproperlyarrangedtheprogramshoulddisplayanemptywindowandwaitfor theusertopressakey.Rearrangethelinesinthecorrectorder.Testtheprogrambyenteringit onthecomputer,compilingit,andrunningit.
Answer: // This is a mixed up program. #include "DarkGDK.h" void DarkGDK() { dbWaitKey(); } Whatdoesthedirective#include "DarkGDK.h"do? Answer:ItcausesthecontentsofafilenamedDarkGDK.htobeincludedintheprogram. Whatisafunction?WhatfunctionisrequiredinanyC++programthatusestheDarkGDK library? Answer:Afunctionisagroupofprogrammingstatementsthatcollectivelyhasaname. InC++isthenameDarkGDKconsideredthesameasthenamedarkGDK? Answer:No,theyarenot. InC++,howdoyouwritealinecomment? Answer:Youbeginalinecommentwithtwoforwardslashes(//).Everythingwrittenafterthe slashes,totheendoftheline,isignoredbythecompiler. InC++,howdoyouwriteablockcomment? Answer:Ablockcommentstartswith/*(aforwardslashfollowedbyanasterisk)andendwith */(anasteriskfollowedbyaforwardslash).Everythingbetweenthesemarkersisignored. WhatistheresolutionofthedefaultwindowcreatedbyaDarkGDKprogram? Answer:640pixelswideby480pixelshigh Whatarethecoordinatesofthepixelintheupperleftcornerofthewindow? Answer:(0,0) Inawindowthatis640pixelswideby480pixelshigh,whatarethecoordinatesofthepixelin thelowerrightcorner? Answer:(639,479) HowisthescreencoordinatesystemdifferentfromtheCartesiancoordinatesystem? Answer:IntheCartesiancoordinatesystemtheYcoordinatesdecreaseasyoumovedownward. Inthescreencoordinatesystem,theYcoordinatesincreaseasyoumovedownward,towardthe bottomofthescreen Writeastatementthatdisplaysadotatthecoordinates(150,210). Answer:dbDot(150, 210); Writeastatementthatcausestheprogramtowaitfor5secondsbeforecontinuing. Answer:dbWait(5000); Writeastatementthatwilldrawalinefrom(100,75)to(150,200). Answer:dbLine(100, 75, 150, 200); Whatispseudcode? Answer:Itisaninformallanguagethathasnosyntaxrules,andisnotmeanttobecompiledor executed.Instead,programmersusepseudocodetocreatemodels,ormockupsofprograms. Becauseyoudonthavetoworryaboutsyntaxerrorswhilewritingpseudocode,youcanfocus
2.2 2.3
2.4 2.5
2.6
2.10
2.15
2.16
2.17
2.18 2.19
2.20
2.21 2.22
2.23
allofyourattentionontheprogramsdesign.Onceasatisfactorydesignhasbeencreatedwith pseudocode,thepseudocodecanbetranslateddirectlytoactualcode. Writeastatementthatwilldrawarectangle.Therectanglesupperleftcornershouldbeat(0,0) anditslowerrightcornershouldbeat(100,80). Answer:dbBox(0, 0, 100, 80); Writeastatementthatwilldrawacircle.Thecirclescenterpointshouldbeat(300,200)andits radiusshouldbe50pixels. Answer:dbCircle(300, 200, 50); Writeastatementthatwilldrawanellipse.Theellipsescenterpointshouldbeat(120,100).Its xradiusshouldbe100pixels,anditsyradiusshouldbe60pixels. Answer:dbEllipse(120, 100, 100, 60); Whathappenswhenanellipsesxradiusisthesameasitsyradius? Answer:Itisacircle. WriteastatementthatdisplaysthetextFourscoreandsevenyearsago.Theupperleftcorner ofthefirstcharactershouldbelocatedat(100,50). Answer:dbText(100, 50, "Four score and seven years ago"); WriteastatementthatdisplaysthetextTobe,ornottobe.Thetextshouldbecenteredjust below(100,50). Answer:dbCenterText(100, 50, "To be or not to be"); Whatisasyntaxerror? Answer:Aprogramstatementthatviolatestherulesoftheprogramminglanguagesyntax. Whatisalogicerror? Answer:Alogicerrorisamistakethatdoesnotpreventtheprogramfrombeingcompiledor running,butcausesittoproduceincorrectresults.(Mathematicalmistakesarecommoncauses oflogicerrors.) Whatdoesthetermdebugmean? Answer:Findingandcorrectinglogicerrorsinaprogram.
Chapter3
3.1 Whatarethenumericliteralsinthefollowingprogram?
#include "DarkGDK.h" void DarkGDK() { dbCenterText(300, 200, "Demo"); dbLine(50, 75, 100, 120); }
3.2 Answer:300,200,50,75,100,and120. WhatarethestringliteralsintheprogramshowninCheckpoint3.1? Answer:"DarkGDK.h"and"Demo"
3.6 3.7
3.11
3.12
3.13 3.14
Whatisavariable? Answer:Astoragelocationinmemorythatisrepresentedbyaname. Whattwoitemsdoyouspecifywithavariabledeclaration? Answer:Thevariable'sdatatypeandname. SummarizetherulesfornamingvariablesinC++. Answer: Variablenamesmustbeoneword.Theycannotcontainspaces. Thefirstcharactermustbeoneofthelettersathroughz,AthroughZ,oranunderscore character(_). AfterthefirstcharacteryoumayusethelettersathroughzorAthroughZ,thedigits0 through9,orunderscores. Uppercaseandlowercasecharactersaredistinct.ThismeansLineLengthisnotthesameas linelength. Whatvariablenamingconventiondowefollowinthisbook? Answer:camelCase Doesitmatterwhereyouwritethevariabledeclarationsinsideafunction? Answer:Yes,youmustwriteavariabledeclarationaboveanyotherstatementthatusesthe variable. Whatisvariableinitialization? Answer:Theassignmentofavaluetoavariableatthetimethevariableisdeclared. Whatisanuninitializedvariable? Answer:Avariablethathasbeendeclared,buthasnotbeeninitializedorassignedavalue. Douninitializedvariablesposeanydangerinaprogram? Answer:Yes,theyareacommoncauseoferrors.Ifanuninitializedvariableisusedinan operationsuchasacalculation,alogicerrorwilloccur. Whathappenswhenyouassignafloatingpointnumbertoanintegervariable? Answer:Thefloatingpointvalueistruncated,whichmeansthepartthatappearsafterthe decimalpointiscutoff. Summarizethemathematicalorderofoperations. Answer: 1. Performanyoperationsthatareenclosedinparentheses. 2. Performanymultiplications,divisions,ormodulusoperationsastheyappearfromleft toright. 3. Performanyadditionsorsubtractionsastheyappearfromlefttoright. Whenthefollowingstatementexecutes,whatvaluewillbestoredinresult? result = 4 + 10 / 2; Answer:9 Whenthefollowingstatementexecutes,whatvaluewillbestoredinresult? result = (2 + 5) * 10; Answer:70
3.15
3.16
3.17
3.18
3.19 3.20
3.21 3.22
3.23 3.24
Whenthefollowingstatementexecutes,whatvaluewillbestoredinresult? result = 5 / 2; Answer:2(Theresultwillnotbe2.5becauseofintegerdivision.) Rewritethefollowingstatementsusingcombinedassignmentoperators: a) x = x + 1; b) lowerY = lowerY 5; c) radius = radius * 10; d) length = length / 2; Answer: a) x+= 1; b) lowerY -= 5; c) radius *= 10; d) length /= 2; WhatvaluedoesthedbScreenWidthfunctionreturn?Whatvaluedoesthe dbScreenHeightfunctionreturn? Answer:ThedbScreenWidthfunctionreturnstheDarkGDKwindow'swidth,inpixels.The dbScreenHeightfunctionreturnsthewindow'sheight,inpixels. Writecodethatdoesthefollowing: Declarestwointvariablesnamedwidthandheight CallstheappropriatefunctionstoassigntheDarkGDKwindow'swidthandheightinthetwo variables Answer: int width, height; width = dbScreenWidth(); height = dbScreenHeight(); WhatisthepurposeofthedbRNDfunction? Answer:Itreturnsarandomnumber. Describethevaluethatwillbestoredinthenumbervariableafterthefollowingstatement executes: number = dbRND(25); Answer:Thevariablewillholdarandomintegernumberintherangeof0through25. WhatdoesthedbRandomizefunctiondo? Answer:Itreseedstherandomnumbergenerator. WhatdoesthedbTimerfunctionreturn?Howisthisvalueusedinthegenerationofrandom numbers? Answer:Thesystem'sinternaltime,inmilliseconds.Thisvalueiscommonlyusedasaseedfor therandomnumbergenerator. ThedbInputfunctionalwaysreturnstheuser'sinputaswhattypeofdata? Answer:Astring. WhatC++functiondoyouusetoconvertastringtoaninteger? Answer:atoi
3.25 3.26
3.27 3.28
3.32
WhatC++functiondoyouusetoconvertastringtoafloatingpointvalue? Answer:atof Writeastatementthatreadsdatafromthekeyboard,convertsittoaninteger,andassignsthe integertoavariablenamedx. Answer:x = atoi( dbInput() ); WhatthreecolorchannelsdoestheRGBsystemusetogeneratecolors? Answer:Red,green,andBlue WhatcolordoeachofthefollowingstatementscleartheDarkGDKwindowto? dbClear(0, 0, 255); dbClear(255, 0, 0); dbClear(0, 255, 0); dbClear(255, 255, 255); dbClear(0, 0, 0); Answer: blue red green white black WhattypeofvariabledoyouusetostoreanRGBcolor? Answer:DWORD ShowanexampleofhowyouwouldstoretheRGBvaluesforthecolorgreeninavariable. Answer:DWORD green = dbRGB(0, 255, 0); Whatisthepurposeofthekeywordconstinavariabledeclaration? Answer:Ittellsthecompilerthatthevariableisanamedconstant.Ifthecompilerencounters anystatementintheprogramthatattemptstochangethenamedconstant'svalue(suchasan assignmentstatement),anerrorwilloccur. Isitpossibletoexecuteaprogramevenifithasastatementthattriestochangethevalueofa namedconstant? Answer:No,theprogramwillnotbecompiledifitcontainsastatementthattriestochangethe valueofanamedconstant.
Chapter4
4.1 4.2 Whatismeantbythephrase"divideandconquer?" Answer:Alargetaskisdividedintoseveralsmallertasksthatareeasilyperformed. Howdofunctionshelpyoureusecodeinaprogram? Answer:Ifaspecificoperationisperformedinseveralplacesinaprogram,afunctioncanbe writtenoncetoperformthatoperation,andthenbeexecutedanytimeitisneeded. Howcanfunctionsmakethedevelopmentofmultipleprogramsfaster? Answer:Functionscanbewrittenforthecommontasksthatareneededbythedifferent programs.Thosefunctionscanthenbeincorporatedintoeachprogramthatneedsthem.
4.3
4.4
4.8
4.9
4.10
4.11
4.12
Howcanfunctionsmakeiteasierforprogramstobedevelopedbyteamsofprogrammers? Answer:Whenaprogramisdevelopedasasetoffunctionsthateachperformsanindividual task,thendifferentprogrammerscanbeassignedthejobofwritingdifferentfunctions. Whatisthefirstlineofafunctiondefinition? Answer:Thefunctionheader Whatisthebodyofafunction? Answer:Thestatementsthatexecutewhenthefunctioniscalled. Whydoprogrammersusuallyindentthelinesinthebodyofafunction? Answer:Itmakesthecodeeasierforushumanstoread.Byindentingthestatementsina function,youvisuallysetthemapart.Asaresult,youcantellataglancewhichstatementsare insidethefunction. YouarereadingthecodeforaprogramthathasavoidfunctionnameddrawMap,andyousee thefollowingstatement.Isthisstatementafunctionheaderorafunctioncall?Howcanyou tell? drawMap(); Answer:Itisafunctioncall.Youcantellbecausethewordvoiddoesnotappear,andthe statementendswithasemicolon. YouarereadingthecodeforaprogramthathasavoidfunctionnamedclearScreen,and youseethefollowingstatement.Isthisstatementafunctionheaderorafunctioncall?Howcan youtell? void clearScreen() Answer:Itisafunctionheader.Youcantellbecauseitstartswiththewordvoid,andthe statementdoesnotendwithasemicolon. Whenafunctionisexecuting,whathappenswhentheendofthefunctionisreached? Answer:Thecontroloftheprogramreturnstothestatementthatcalledthefunction.Program executionresumesatthatpoint. Whatisafunctionprototype? Answer:Astatementthatdeclarestheexistenceofafunction,butdoesnotdefinethefunction. Itismerelyawayoftellingthecompilerthataparticularfunctionexistsintheprogram,andits definitionappearsatalaterpoint. Whatisalocalvariable?Howisaccesstoalocalvariablerestricted? Answer:Alocalvariableisavariablethatisdeclaredinsideafunction.Alocalvariablebelongs tothefunctioninwhichitisdeclared,andonlystatementsinsidethatfunctioncanaccessthe variable. Whatdoestheterm"scope"mean? Answer:Theterm"scope"describesthepartofaprograminwhichavariablemaybeaccessed. Isitpermissibletohavemorethanonevariablewiththesamenameinthesamescope? Answer:No Isitpermissibleforalocalvariableinonefunctiontohavethesamenameasalocalvariablein anotherfunction? Answer:Yes
4.20 4.21
4.22
Whatarethepiecesofdatathatarepassedintoafunctioncalled? Answer:Arguments Whatarethevariablesthatreceivepiecesofdatainafunctioncalled? Answer:Parameters Whatisaparametervariable'sscope? Answer:Aparametervariablesscopeistheentirefunctioninwhichtheparameterisdeclared. Explainthedifferencebetweenpassingbyvalueandpassingbyreference. Answer:Passinganargumentbyvaluemeansthatonlyacopyoftheargumentsvalueispassed intotheparametervariable.Ifthecontentsoftheparametervariablearechangedinsidethe function,ithasnoeffectontheargumentinthecallingpartoftheprogram.Passingan argumentbyreferencemeansthattheargumentispassedintoaspecialtypeofparameter knownasareferencevariable.Whenareferencevariableisusedasaparameterinamodule,it allowsthefunctiontomodifytheargumentinthecallingpartoftheprogram. Whatisthescopeofaglobalvariable? Answer:Theentireprogram Giveonegoodreasonthatyoushouldrestricttheuseglobalvariablesinaprogram. Answer:Herearethree: Globalvariablesmakedebuggingdifficult.Anystatementinaprogramcanchangethevalue ofaglobalvariable.Ifyoufindthatthewrongvalueisbeingstoredinaglobalvariable,you havetotrackdowneverystatementthataccessesittodeterminewherethebadvalueis comingfrom.Inaprogramwiththousandsoflinesofcode,thiscanbedifficult. Functionsthatuseglobalvariablesareusuallydependentonthosevariables.Ifyouwantto usesuchafunctioninadifferentprogram,mostlikelyyouwillhavetoredesignitsoitdoes notrelyontheglobalvariable. Globalvariablesmakeaprogramhardtounderstand.Aglobalvariablecanbemodifiedby anystatementintheprogram.Ifyouaretounderstandanypartoftheprogramthatusesa globalvariable,youhavetobeawareofalltheotherpartsoftheprogramthataccessthe globalvariable. Whatisaglobalconstant?Isitpermissibletouseglobalconstantsinaprogram? Answer:Aglobalconstantisanamedconstantthatisavailabletoeveryfunctioninthe program,fromtheconstant'sdeclarationtotheendofthefile.Itispermissibletouseglobal constants.Becauseaglobalconstantsvaluecannotbechangedduringtheprogramsexecution, youdonothavetoworryaboutmanyofthepotentialhazardsthatareassociatedwiththeuse ofglobalvariables.
Chapter5
5.1 5.2 HowmanybitmapscanaDarkGDKprogramloadintomemory? Answer:32 Whatarethevalidbitmapnumbers? Answer:0through31
5.8
5.9
5.10
5.11
5.12 5.13
5.14 5.15
5.16
Whichbitmapisalwaystheonethatisdisplayed? Answer:Bitmap0. Howdoyoudisplayabitmapthatisnotcurrentlydisplayed? Answer:Youcopyittobitmap0withthedbCopyBitmapfunction. Howdoyougetabitmap'ssize? Answer:YouusethedbBitmapWidthanddbBitmapHeightfunctions. Howdoyougetthemaximumnumberofcolorsthatcanbedisplayedinaparticularbitmap? Answer:YouusethedbBitmapDepthfunction. Whyisitagoodideaforaprogramtodeleteabitmapfrommemoryoncethebitmapisno longerneeded? Answer:Removingthemaftertheyarenolongerneededfreesmemoryandcanimprovethe program'sperformance. ThedbFadeBitmapfunctionacceptsanargumentasthefadevalue.Describehowthefade valuedeterminesthewaythebitmapisfaded. Answer:Thisvaluemustbeintherangeof0through100.Avalueof0fadesthebitmap completelytoblack,whileavalueof100performsnofading. ThedbBlurBitmapfunctionacceptsanargumentastheblurvalue.Describehowthefade valuedeterminesthewaythebitmapisfaded. Answer:Thisvaluemustbeintherangeof1through9.Avalueof1onlyslightlyblursthe bitmap,whileavalueof9greatlyblursit. Describehowcolorkey,orchromakey,isusedtomakeaTVweatherpersonappearasifheor sheisstandinginfrontofagiantweathermap. Answer:Inthestudiotheweatherpersonisactuallystandinginfrontofakeycolored background,suchasablueorgreenscreen.Beforetheimageoftheweatherpersonis transmitted,acomputerremovesthepixelscontainingthekeycolorandplacesitontopofthe weathermapimage. Whatarethevalidimagenumbersthatcanbeusedwhenanimageisloadedwiththe dbLoadImagefunction? Answer:Theimagenumbermustbeanintegerintherangeof1through65,535. HowdoyoudisplayanimagethathasbeenloadedwiththedbLoadImagefunction? Answer:YouusethedbPasteImagefunction. Whenyoudisplayanimage,howdoyoumakeitskeycolorpixelstransparent? Answer:ThelastargumentpassedtothedbPasteImagefunctionmustbe1.Ifthelast argumentis0,nopixelswillbetransparent. Whatisthedefaultkeycolor? Answer:black(RGB=0,0,0) Howdoyouchangethekeycolor? Answer:YouusethedbSetImageColorKeyfunction.Thefunctionmustbecalledbefore loadinganimagewithdbLoadeImage. Whatfileformatshouldyouusewhensavinganimagethatcontainsakeycolor?Whycan'tyou useanygraphicformat?
Chapter6
6.1 6.2 6.3 6.4 Whatdoesacontrolstructuredetermine? Answer:Theorderinwhichstatementsareexecuted. Namethreetypesofcontrolstructures. Answer:Sequence,decision,andrepetition Whattypeofcontrolstructurehaveyouusedsofarasworkingthroughthisbook? Answer:Sequence Whatisasinglealternativedecisionstructure? Answer:Adecisionstructurethatprovidesasinglealternativepathofexecution.Ifthe conditionthatisbeingtestedistrue,theprogramtakesthealternativepath. WhatisaBooleanexpression? Answer:Anexpressionthatcanbeevaluatedaseithertrueorfalse. Whattypesofrelationshipsbetweenvaluescanyoutestwithrelationaloperators? Answer:Youcandeterminewhetheronevalueisgreaterthan,lessthan,greaterthanorequal to,lessthanorequalto,equalto,ornotequaltoanothervalue. Writeanifstatementthatassigns0toxifyisequalto20. Answer: if (y == 20) { x = 0; } Writeanifstatementthatdisplaysthemessage"Thelineistoolong"ifthevariablelength isgreaterthan640. Answer: if (length > 640) { dbPrint("The line is too long"); } Describehowadualalternativedecisionstructureworks. Answer:Adualalternativedecisionstructurehastwopossiblepathsofexecutiononepathis takenifaconditionistrue,andtheotherpathistakeniftheconditionisfalse. Inanifelsestatement,underwhatcircumstancesdothestatementsthatappearafterthe elseclause? Answer:WhentheBooleanexpressionisfalse.
6.5 6.6
6.7
6.8
6.9
6.10
6.11
6.12
Writeanifelsestatementthatdetermineswhetheryislessthan0.Ifthisistrue,setxto0. Otherwise,setxto320. Answer: if (y < 0) { x = 0; } else { x = 320; } Convertthefollowingsetofnestedifelsestatementstoanifelseifstatement: if (number == 1) { dbPrint("One"); } else { if (number == 2) { dbPrint("Two"); } else { if (number == 3) { dbPrint("Three"); } else { dbPrint("Unknown"); } } } Answer: if (number == 1) { dbPrint("One"); } else if (number == 2) { dbPrint("Two"); }
6.13 6.14
6.15 6.16
6.24
else if (number == 3) { dbPrint("Three"); } else { dbPrint("Unknown"); } Whatisarepetitionstructure? Answer:Astructurethatcausesasectionofcodetorepeat. Whatisaconditioncontrolledloop?Whatisacountcontrolledloop? Answer:Aconditioncontrolledloopusesatrue/falseconditiontocontrolthenumberoftimes thatitrepeats.Acountcontrolledlooprepeatsaspecificnumberoftimes. Whatisaloopiteration? Answer:Anexecutionofthestatementsinthebodyoftheloop. Whatisthedifferencebetweenapretestloopandaposttestloop? Answer:Apretestlooptestsitsconditionbeforeitperformsaniteration.Aposttestlooptests itsconditionafteritperformsaniteration. Doesthewhilelooptestitsconditionbeforeorafteritperformsaniteration? Answer:Before Doesthedowhilelooptestitsconditionbeforeorafteritperformsaniteration? Answer:After Whatisaninfiniteloop? Answer:Aloopthathasnowayofstopping,andrepeatsuntiltheprogramisinterrupted. Whenyouincrementordecrementavariable,whatareyoudoing? Answer:Incrementingavariablemeansincreasingitsvalue.Decrementingavariablemeans decreasingitsvalue. Whatisacountervariable? Answer:Avariablethatisusedtokeepcountofthenumberofiterationsthatithasperformed. Whatthreeactionsdocountcontrolledloopstypicallyperformusingthecountervariable? Answer:Initialization,test,andincrement Afterthefollowingcodeexecutes,whatvaluewillbestoredinthenumbervariable? int number = 5; number++; Answer:6 Whatwouldthefollowingcodedisplay? for (int counter = 1; count <= 5; count++) { dbPrint( dbStr(counter) ); }
Answer: 1 2 3 4 5 6.25 Whatwouldthefollowingcodedisplay? for (int counter = 0; count <= 500; count += 100) { dbPrint( dbStr(counter) ); } Answer: 0 100 200 300 400 500 WhatisacompoundBooleanexpression? Answer:ItisanexpressionthatiscreatedbyusingalogicaloperatortocombinetwoBoolean subexpressions. Thefollowingtruthtableshowsvariouscombinationsofthevaluestrueandfalseconnectedby alogicaloperator.CompletethetablebycirclingTorFtoindicatewhethertheresultofsucha combinationistrueorfalse. LogicalExpression true&&false true&&true false&&true false&&false true||false true||true false||true false||false !true !false Result(circletrueorfalse) F T T F T F T F T F T F T F T F T F T F
6.26
6.27
Answer: F T F F T T T F F T 6.28 a == 4 || b >2 6 <= c && a > 3 1 != b && c != 3 a >= -1 || a <= b !(a > 2) Answer: T F T T 6.29 T T T T T F F F F F Assumethevariablesa=2, b =4,andc=6.CircletheTorFforeachofthefollowing conditionstoindicateifitistrueorfalse.
Explainhowshortcircuitevaluationworkswiththe&&and||operators. Answer: The&&operator:Iftheexpressionontheleftsideofthe&&operatorisfalse,theexpressionon therightsidewillnotbechecked. The||operator:Iftheexpressionontheleftsideofthe||operatoristrue,theexpressionon therightsidewillnotbechecked. Writeanifstatementthatdisplaysthemessage"Thenumberisvalid"ifthevariablespeedis withintherange0through200. Answer: if (speed >= 0 && speed <= 200) { dbPrint"The number is valid"); }
6.30
6.31
Writeanifstatementthatdisplaysthemessage"Thenumberisnotvalid"ifthevariable speedisoutsidetherange0through200. Answer: if (speed < 0 || speed > 200) { dbPrint("The number is not valid"); } Convertthefollowingifelseifcodetoaswitchstatement. if (choice == 1) { dbPrint("You chose 1."); } else if (choice == 2) { dbPrint("You chose 2."); } else if (choice == 3) { dbPrint("You chose 3."); } else { dbPrint("Make another choice."); } Answer: switch(choice) { case 1: dbPrint("You chose 1."); break; case 2: dbPrint("You chose 2."); break; case 3: dbPrint("You chose 3."); break; default: dbPrint("Make another choice."); }
6.32
Chapter7
7.1 BrieflydescribethefollowingDarkGDKfunctions: dbSyncOn dbSyncRate LoopGDK dbSync Answer: dbSyncOnThisfunctiontellstheDarkGDKthatwewantourprogramtohandlethe updatingofthescreen.AsaresulttheDarkGDKwillnotattempttoupdatethescreen untilwetellitto. dbSyncRateThisfunctionacceptsanargumentthatspecifiesthemaximumtimes persecondthatthescreenshouldbeupdated. LoopGDKThisfunctionisusedtocontrolthenumberoftimesthataloopexecutes persecond.Italsotellsus,viaitsreturnvalue,whethertheuserhasattemptedtoend theprogram.Itreturnszeroiftheuserhasclosedtheprogram'swindow,orpressedthe escapekey.Otherwiseitreturnsanonzerovalue. dbSyncThisfunctionforcesascreenupdate. WhatistheconnectionbetweentheLoopGDKfunctionandthescreenrefreshratethatyou specifywiththedbSyncRatefunction? Answer:TheLoopGDKfunctionsynchronizestheloop'sexecutionspeedwiththescreen refreshratethatyouspecifiedwiththedbSyncRatefunction.Forexample,ifyouspecifya refreshrateof60timespersecond,theLoopGDKfunctionwilllettheloopiterateamaximum of60timespersecond. WhyisitimportanttocalldbSyncattheendofthegameloop? Answer:BecausedbSyncupdatesthescreen.Ifyouleavethefunctioncallout,thescreenwill notberefreshed. Whatfunctionsdoyoucalltoseeifthefollowingkeysarebeingpressed? uparrow downarrow rightarrow leftarrow Ctrl
7.2
7.3
7.4
Answer: o o o o o o o o 7.5 uparrow downarrow rightarrow leftarrow Ctrl Shift Enter Escape dbUpKey() dbDownKey() dbRightKey() dbLeftKey() dbControlKey() dbShiftKey() dbReturnKey() dbEscapeKey()
7.6
Whattwoactionsdoyouperformtocreateasprite? Answer:Tocreateasprite,youperformtwoactions:(1)youusethedbLoadImagefunction toloadanimageintomemorythatyouwanttouseasthesprite,and(2)youusethe dbSpritefunctiontodesignatethatimageasaspriteanddisplayit. Howdoyoumoveanexistingsprite? Answer:OnceyouhavecreatedanddisplayedaspritewiththedbSpritefunction,youcan moveittoanewlocationonthescreenbycallingthedbSpritefunctionagain,usingthe samespritenumberandimagenumber,butpassingdifferentvaluesfortheXandYcoordinates. Whatfunctionsdoyoucalltogetanexistingsprite'scurrentcoordinates? Answer:YoucallthedbSpriteXanddbSpriteYfunctions. Whatfunctionsdoyoucalltogetasprite'swidthandheight? Answer:YoucallthedbSpriteWidthanddbSpriteHeightfunctions. Giveanexampleofhowyouwouldrotatespritenumber1atanangleof47.5degrees. Answer:dbRotateSprite(1, 47.5); Giveanexampleofhowyouwouldoffsetspritenumber1'sinsertionpointtothecenterofthe sprite. Answer: // Calculate the X and Y offset amounts. int offsetX = spriteWidth(1) / 2; int offsetY = spriteHeight(1) / 2; // Offset the insertion point. dbOffsetSprite(1, offsetX, offsetY);
7.11
Giveexamplesofhowyouwoulddothefollowing:
a) Hidespritenumber1 b) Showspritenumber1
c) Hidealloftheexistingsprites d) Showalloftheexistingsprites e) Changethesizeofspritenumber1soitis64pixelsintheXdirectionand128pixelsintheY direction f) Scalespritenumber2soitis50percentitscurrentsizeinboththeXandYdirections g) Setspritenumber3'spriorityto1 h) Flipspritenumber2 i) Mirrorspritenumber2 j) Setspritenumber1'salphalevelto10 k) Makeaclonedcopyofspritenumber1.Thecloneshouldbespritenumber2. Answer: a) b) c) d) e) f) g) h)
i) j) 7.12 7.13 7.14 7.15 7.16 7.17
dbHideSprite(1); dbShowSprite(1); dbHideAllSprites(); dbShowAllSprites(); dbSizeSprite(1, 64, 128); dbStretchSprite(2, 50, 50); dbSetSpritePriority(3, 1); dbFlipSprite(2); dbMirrorSprite(2); dbSetSpriteAlpha(1, 10);
7.18
Whatisaspritesheet? Answer:Animagefilethatcontainsalloftheframesforananimationsequence. WhatDarkGDKfunctiondoyoucalltocreateananimatedsprite? Answer:dbCreateAnimatedSprite WhatDarkGDKfunctiondoyoucalltoextractanimagefromananimatedsprite? Answer:dbPlaySprite Whatisasprite'sboundingrectangle? Answer:Aninvisiblerectanglethatenclosesasprite'simage. Whatconstitutesaspritecollision? Answer:Whentwosprites'boundingrectanglescomeintocontact. Howdoyoudetectacollisionbetweentwosprites? Answer:YoucallthedbSpriteCollisionfunction,passingthetwospritenumbersasarguments.If thespriteshavecollided,thefunctionreturns1(true).Otherwise,itreturns0(false). Howwoulddeterminewhetherspritenumber1hascollidedwithanyothersprite? Answer:YouwouldcallthedbSpriteCollisionfunction,passing1asthefirstargumentand0as thesecondargument.Ifsprite1hascollidedwithanyothersprite,thefunctionreturns1(true). Otherwise,itreturns0(false)
Chapter8 8.1 IntheDarkGDK,whatisthedifferencebetweenasoundfileandamusicfile? Answer:AsoundfileisstoredintheWAVformat.AmusicfileisstoredineithertheMIDIorMP3formats. 8.2 TheDarkGDKprovidesfunctionstoperformmanyoperationswithsoundandmusicfiles.Completethe followingtable,listingthenamesoftheDarkGDKfunctionsthatperformthespecifiedoperation.Ifthe DarkGDKdoesnotperformoneofthelistedoperations,write"None." Answer: Operation SoundFunction MusicFunction dbLoadSound dbLoadMusic Loadsoundormusicintomemory dbPlaySound dbPlayMusic Play dbLoopSound dbLoopMusic Loop dbDeleteSound dbDeleteMusic Deletesoundormusicfrom memory dbPauseSound dbPauseMusic Pause dbResumeSound dbResumeMusic Resume dbSetSoundPan None Pan dbSetSoundVolume dbSetMusicVolume Setthevolume dbSetSoundSpeed dbSetMusicSpeed Settheplayingspeed dbCloneSound Clone None dbLoadCDMusic LoadatrackfromaCD None dbSoundExist dbMusicExist Determinewhetherasoundor musicexistsinmemory dbSoundPlaying dbMusicPlaying Determinewhetherasoundor musicisplaying dbSoundLooping dbMusicLooping Determinewhetherasoundor musicislooping dbSoundPaused dbMusicPaused Determinewhetherasoundor musicispaused dbSoundPan None Determinethepanvalue dbSoundSpeed dbMusicSpeed Determinetheplayingspeed dbSoundVolume dbMusicVolume Determinethevolumesetting
8.3
WhengravitycausesanobjecttofallinavacuumtowardtheEarth,doestheobjectfallata steadyspeed,ordoesitsspeedincreaseasitfalls? Answer:Afallingobject'sspeedincreasesatarateof9.8meterspersecondeachsecond. IfgravityiscausinganobjecttofallinavacuumtowardtheEarth,howfarwilltheobjecthave fallenat10seconds? Answer:490meters Whatfunctiondoyoucalltochangethecurrentfont? Answer: dbSetTextFont Whatfunctiondoyoucalltochangethecurrenttextsize? Answer: dbSetTextSize
Whatfunctiondoyoucalltosetthecurrenttextstyletobold? Answer: dbSetTextToBold Whatfunctiondoyoucalltosetthecurrenttextstyletoitalic? Answer: dbSetTextToItalic Whatfunctiondoyoucallifyouwanttexttobenonboldandnonitalic? Answer: dbSetTextToNormal Whatfunctiondoyoucallifyouwanttexttobetransparent? Answer: dbSetTextTransparent Whatfunctiondoyoucallifyoudonotwanttexttobetransparent? Answer: dbSetTextOpaque Whatfunctiondoyoucalltosetthetextcursorposition? Answer: dbSetCursor Whatvaluereturningfunctionsdoyoucalltogetthefollowingdata: Thecurrenttextsize Thecurrentfont Thecurrenttextwidth Thecurrenttextheight Thecurrenttextstyle Thecurrenttextbackgroundtransparencysetting Answer: dbTextSize dbTextFont dbTextWidth dbTextHeight dbTextStyle dbTextBackgroundType
Chapter9 9.1 Howdoesavaluereturningfunctiondifferfromavoidfunction? Answer:Whenavoidfunctionfinishes,theprogrammerelyreturnsbacktothepartofthe programthatcalledthefunction,andexecutionresumesatthatpoint.Whenavaluereturning functionfinishes,itreturnsavaluebacktothepartoftheprogramthatcalledit. 9.2 Whatisthepurposeofthereturnstatementinafunction? Answer:Thereturnstatementspecifiesthevaluethatthefunctionreturnstothepartofthe programthatcalledthefunction.Whenthereturnstatementexecutes,itcausesthefunctionto terminateandreturnthespecifiedvalue.
9.3
9.4 9.5
9.6 9.7
9.8
9.9
9.10
a. Whatisthenameofthefunction? Answer:doSomething b. Whattypeofdatadoesthefunctionreturn? Answer:int c. Giventhefunctiondefinition,whatwillthefollowingstatementdisplay? dbPrint( dbStr( doSomething(10) ) ); Answer:20 WhatisaBooleanfunction? Answer:Afunctionthatreturnseithertrueorfalse. Howdoyougetthemousepointer'scurrentlocationonthescreen? Answer:BycallingthedbMouseXanddbMouseYfunctions.Thesefunctionsreturnthemouse pointer'sXandYcoordinates,respectively. Howdoyoumovethemousepointertoaspecificlocationonthescreen? Answer:BycallingthedbPositionfunction,passingtheXYcoordinatesasarguments. Howdoyoumakethemouseinvisible?Onceyou'vemadeitinvisible,howdoyoumakeitvisible again? Answer:YoumakeitinvisiblebycallingthedbHideMousefunction.Tomakeitvisibleagain youcallthedbShowMousefunction. Howdoyoutelliftheuserispressingaparticularmousebutton,suchastheleftbutton? Answer:YoucallthedbMouseClickfunction.Itreturnsthefollowingvalues: 0isnomousebuttonisbeingpressed 1iftheleftmousebuttonisbeingpressed 2iftherightmousebuttonisbeingpressed 4ifthethirdmousebuttonisbeingpressed 8ifthefourthmousebuttonisbeingpressed Howdoyoutelliftheuserispressingmorethanonemousebuttonsimultaneously? Answer:Iftheuserpressesmorethanonemousebuttonatthesametime,the dbMouseClickfunctionreturnsthesumofthosebuttons'individualreturnvalues.For example,iftheuserispressingboththeleftandrightbutton,thedbMouseClickfunction returnsthevalue3.Onafourbuttonmouse,iftheuserispressingboththethirdandfourth buttons,thedbMouseClickfunctionreturnsthevalue12. Howdoyouchangethemousepointertothehourglasspointer?Howdoyouchangeitbackto theregularsystempointer?
Answer:TochangethepointertothehourglassyoucalldbChangeMouse,passing1asan argument.TochangethepointerbacktotheregularsystempointeryoucalldbChangeMouse, passing0asanargument. Chapter10 10.1 Canyoustoreamixtureofdatatypesinanarray? Answer:No,youcannot.Alloftheitemsinanarraymustbeofthesamedatatype. 10.2 Whatisanarraysizedeclarator? Answer:Anonnegativeintegerthatspecifiesthesizeofanarray. 10.3 Canthesizeofanarraybechangedwhiletheprogramisrunning? Answer:No 10.4 Whatisanarrayelement? Answer:Anindividualstoragelocationinanarray. 10.5 Whatisasubscript? Answer:Anumberthatidentifiesaspecificelementinanarray. 10.6 Whatisthefirstsubscriptinanarray? Answer:0 10.7 Lookatthefollowingcodeandanswerquestionsathrough const int SIZE = 7; float numbers[SIZE]; a) Whatisthenameofthearraythatisbeingdeclared? Answer:numbers b) Howmanyelementswillthearrayhave? Answer:7 c) Whatdatatypearethearrayelements? Answer:float d) Whatisthesubscriptofthelastelementinthearray? Answer:6 10.8 Lookatthefollowingcodeandanswerquestionsathrough int numbers[] = { 10, 20, 30 }; a) Isthisalegaldeclarationofanarray? Answer:Yes b) Howmanyelementswillthearrayhave? Answer:3 c) Whatisthesubscriptofthelastelementinthearray? Answer:2
10.9
10.10
10.11 10.12
10.13
10.14
DoesC++performarrayboundschecking?Whatdoesthismean? Answer:TheC++languagedoesnotperformarrayboundschecking,whichmeanstheC++ compilerdoesnotcheckthevaluesthatyouuseasarraysubscriptstomakesuretheyarevalid. Howdoyoucopythecontentsofonearraytoanotherarray? Answer:Youassigntheindividualelementsofthearraythatyouarecopyingtotheelementsof theotherarray.Thisisusuallybestdonewithaloop Whatisasortingalgorithm? Answer:Atechniqueforsteppingthroughanarrayandrearrangingitscontentsinsomeorder. Whatisthedifferencebetweenanascendingordersortandadescendingordersort? Answer:Ascendingordermeansthevaluesaresortedfromlowesttohighest.Descendingorder meansthevaluesaresortedfromhighesttolowest. Brieflydescribetheprocessusedbytheselectionsortalgorithmtosortthecontentsofanarray. Answer:Thesmallestvalueinthearrayislocatedandmovedtoelement0.Thenthenext smallestvalueislocatedandmovedtoelement1.Thisprocesscontinuesuntilallofthe elementshavebeenplacedintheirproperorder. Howmanyrowsandhowmanycolumnsareinthefollowingarray? int points[88][100]; Answer:88rowsand100columns
10.15 Writeastatementthatassignsthevalue100toverylastelementinthepointsarraydeclaredin Checkpoint10.14. Answer:points[87][99] = 100; 10.16 Writeadeclarationforatwodimensionalarrayinitializedwiththefollowingtableofdata: 12 24 32 21 42 14 67 87 65 90 19 1 24 12 8 Answer: const int ROWS = 3; const int COLS = 5; int table[ROWS][COLS] = { {12, 24, 32, 21, 42}, {14, 67, 87, 65, 90}, {19, 1, 24, 12, 8} }; 10.17 Assumeaprogramhasthefollowingdeclarations: const int ROWS = 100; const int COLS = 50; int info[ROWS][COLS];
Writeasetofnestedloopsthatstorethevalue99ineachelementoftheinfoarray. Answer: for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { info[row][col] = 99; } }
10.18 Assumeaprogramhasthefollowingglobalconstants: const int ROWS = 10; const int COLS = 5; Assumethesameprogramhasthefollowingarraydeclaration: int data[ROWS][COLS]; WritethefunctionheaderforavoidfunctionnamedprocessArray.Weshouldbeableto passthedataarrayasanargumenttotheprocessArrayfunction. Answer:void processArray(int numbers[][COLS], int rows) 10.19 Whataretiles? Answer:Tilesaresmallrectangularimagesthatcanbeputtogethertoformalargerimage. 10.20 Whatisatilemap? Answer:Atilemapisatwodimensionalarraythatmapsthelocationofeachtileonthescreen. 10.21 Supposeyouarewritingatilebasedgamethatusesascreenthatis500pixelswideby400 pixelshigh.Thetilesthatyouwanttouseforthebackgroundare25pixelswideby20pixels high.Howmanyrowsandcolumnswouldthetilemaphave? Answer:20rowsand20columns
Chapter11
11.1 Whatisacharvariable?Cancharvariablesholdstrings? Answer:Acharvariableoccupiesonebyteofmemory,andisusedtoholdasinglecharacter. Youcannotstoreastringinacharvariable,becauseofthewaythatstringsarestoredin memory. Whatdoyouenclosecharacterliteralsin? Answer:Singlequotationmarks. Howmanybytesofmemorywouldthestring"Maxwell"occupy? Answer:Thestring"Maxwell"wouldoccupy8bytesofmemory.Theeighthbytewouldcontain thenullcharacter.
11.2 11.3
11.4
11.9
11.10
11.11
11.12
11.17
TousethestandardC++functionsdiscussedinthissection,what#includedirectivedoyou use? Answer:#include <string.h> WhatstandardC++functioncanyouusetocopyastringtoachararray? Answer:strcpy WhatstandardC++functioncanyouusetoappendonestringtoanotherstring? Answer:strcat WhatstandardC++functioncanyouusetogetthelengthofastring? Answer:strlen Describethemeaningofthevaluesthatarereturnedfromthestrcmpfunction. Answer:AssumestrcmpiscalledwithString1andString2passedasarguments.Thefunction returnsavalueaccordingtothefollowingrules: Ifbothstringsareidentical,strcmpreturns0. IfString1islessthanString2,strcmpreturnsanegativenumber. IfString1isgreaterthanString2,strcmpreturnsapositive Whatisthepurposeofthestrstrfunction,andhowdoyouuseit? Answer:Thestrstrfunctionsearchesforastringinsideofastring.Thefunctionsfirst argumentisthestringtobesearched,andthesecondargumentisthestringtolookfor.Ifthe functionfindsthesecondstringinsidethefirst,itreturnsanonzerovaluetoindicatetrue. Otherwiseitreturns0toindicatefalse. Sincestringsarestoredinonedimensionalchararrays,howwouldyoucreateanarrayof strings? Answer:Withatwodimensionalchararray. Whatisanoutputfile? Answer:Afilethataprogramwritesdatato.Itiscalledanoutputfilebecausetheprogram sendsoutputtoit. Whatisaninputfile? Answer:Afilethataprogramreadsdatafrom.Itiscalledaninputfilebecausetheprogram receivesinputfromit. Whatthreestepsmustbetakenbyaprogramwhenitusesafile? Answer:(1)Openthefile(2)Processthefile(3)Closethefile Whatisthepurposeofopeningafile? Answer:Openingafilecreatesaconnectionbetweenthefileandtheprogram. Whatisthepurposeofclosingafile? Answer:Closingafiledisconnectstheprogramfromthefile. Whatisafile'sreadposition?Initially,whereisthereadpositionwhenaninputfileisopened? Answer:Afilesreadpositionmarksthelocationofthenextitemthatwillbereadfromthefile. Whenaninputfileisopened,itsreadpositionisinitiallysettothefirstiteminthefile. WhatisthepurposeofthedbFileEndfunction? Answer:Itdetermineswhethertheendofafilehasbeenreached.
11.18 WhatwoulditmeaniftheexpressiondbFileEnd(FILE_NUM)returnstrue? Answer:Itwouldmeanthattheprogramhasreachedtheendofthefileassociatedwith FILE_NUM. Chapter12 12.1 Whatisanobject? Answer:Anobjectisasoftwareentitythatcontainsbothdataandprocedures. 12.2 Whatisencapsulation? Answer:Encapsulationisthecombiningofdataandcodeintoasingleobject. 12.3 Whyisanobject'sinternaldatausuallyhiddenfromoutsidecode? Answer:Whenanobjectsinternaldataishiddenfromoutsidecodeandaccesstothatdatais restrictedtotheobjectsmethods,thedataisprotectedfromaccidentalcorruption.Inaddition, theprogrammingcodeoutsidetheobjectdoesnotneedtoknowabouttheformatorinternal structureoftheobjectsdata. 12.4 Whatarepublicmethods? Answer:Publicmethodscanbeaccessedbyentitiesoutsidetheobject.Privatemethodscannot beaccessedbyentitiesoutsidetheobject.Theyaredesignedtobeaccessedinternally. 12.5 Youhearsomeonemakethefollowingcomment:Ablueprintisadesignforahouse.A carpentercanusetheblueprinttobuildthehouse.Ifthecarpenterwishes,heorshecanbuild severalidenticalhousesfromthesameblueprint.Thinkofthisasametaphorforclassesand objects.Doestheblueprintrepresentaclass,ordoesitrepresentanobject? Answer:Themetaphorofablueprintrepresentsaclass. 12.6 Inthischapterweusethemetaphorofacookiecutterandcookiesthataremadefromthe cookiecuttertodescribeclassesandobjects.Inthismetaphor,areobjectsthecookiecutter,or thecookies? Answer:Objectsarethecookies. 12.7 Anobject'sprivatemembersareaccessiblebywhatcode? Answer:Codeintheclass'smemberfunctions. 12.8 Areaclass'smembervariablestypicallydeclaredintheclass'spublicsectionortheclass's privatesection? Answer:Membervariablesaretypicallydeclaredintheclass'sprivatesection. 12.9 Areaclass'smemberfunction'stypicallydeclaredintheclass'spublicsectionortheclass's privatesection? Answer:Memberfunctionsaretypicallydeclaredintheclass'spublicsection. 12.10 Whatisanaccessor?Whatisamutator? Answer:Anaccessorisamemberfunctionthatgetsavaluefromaclasssmembervariablebut doesnotchangeit.Amutatorisamemberfunctionthatstoresavalueinamembervariableor changesthevalueofamembervariableinsomeotherway. 12.11 Whatisaconstructor? Answer:Aconstructorisaspecialmemberfunctionthatisautomaticallyexecutedwhenan objectiscreated.Itiscalledaconstructorbecauseithelpsconstructtheobject.
12.12 Whatisaparameterizedconstructor?Whatisadefaultconstructor? Answer:Aparameterizedconstructorhasparameters,soitacceptsarguments.Adefault constructorhasnoparameters,soitacceptsnoarguments. 12.13 Whatareoverloadedmemberfunctions? Answer:Whenamemberfunctionisoverloaded,itmeansthattwoormorefunctionsinthe sameclasshavethesamename,butusedifferentparameterlists. 12.14 Whatisadestructor? Answer:Adestructorisaspecialmemberfunctionthatisautomaticallyexecutedwhenan objectisdestroyedfrommemory. 12.15 Inthissectionwediscussedbaseclassesandderivedclasses.Whichisthegeneralclassand whichisthespecializedclass? Answer:Thebaseclassisthegeneralclassandthederivedclassisthespecializedclass. 12.16 Whatdoesitmeantosaythereisanisarelationshipbetweentwoobjects? Answer:Whenoneobjectisaspecializedversionofanotherobject,thereisanisa relationshipbetweenthem.Whenanisarelationshipexistsbetweenobjects,itmeansthat thespecializedobjecthasallofthecharacteristicsofthegeneralobject,plusadditional characteristicsthatmakeitspecial.Inobjectorientedprogramming,inheritanceisusedto createanisarelationshipamongclasses.Thisallowsyoutoextendthecapabilitiesofaclass bycreatinganotherclassthatisaspecializedversionofit. 12.17 Whatdoesaderivedclassinheritfromitsbaseclassclass? Answer:Thederivedclassinheritsthemembersofthebaseclass. 12.18 Lookatthefollowingcodewhichisthefirstlineofaclassdeclaration.Whatisthenameofthe baseclass?Whatisthenameofthederivedclass? class Canary : public Bird Answer:ThebaseclassisBirdandthederivedclassisCanary. 12.19 Canaderivedclasshaveamemberfunctionwiththesamenameasbaseclassmember function? Answer:Yes.