SavitchSavitch_ch_03_第1页
SavitchSavitch_ch_03_第2页
SavitchSavitch_ch_03_第3页
SavitchSavitch_ch_03_第4页
SavitchSavitch_ch_03_第5页
已阅读5页,还剩111页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter3,MoreFlowofControl,Overview,3.1UsingBooleanExpressions3.2MultiwayBranches3.3MoreaboutC+LoopStatements3.4DesigningLoops,Slide3-3,FlowOfControl,FlowofcontrolreferstotheorderinwhichprogramstatementsareperformedWehaveseenthefollowingwaystospecifyflowofcontrolif-else-statementswhile-statementsdo-while-statementsNewmethodsdescribedinthischapterincludeswitch-statementsfor-statements,Slide3-4,3.1,UsingBooleanExpressions,UsingBooleanExpressions,ABooleanExpressionisanexpressionthatiseithertrueorfalseBooleanexpressionsareevaluatedusingrelationaloperationssuchas=,=whichproduceabooleanvalueandbooleanoperationssuchas,Slide3-18,DefaultenumValues,Ifnumericvaluesarenotspecified,identifiersareassignedconsecutivevaluesstartingwith0enumDirectionNORTH=0,SOUTH=1,EAST=2,WEST=3;isequivalenttoenumDirectionNORTH,SOUTH,EAST,WEST;,Slide3-19,EnumerationValues,Unlessspecified,thevalueassignedanenumerationconstantis1morethanthepreviousconstantenumMyEnumONE=17,TWO,THREE,FOUR=-3,FIVE;resultsinthesevaluesONE=17,TWO=18,THREE=19,FOUR=-3,FIVE=-2,Slide3-20,Section3.1Conclusion,CanyouWriteafunctiondefinitionforafunctionnamedin_orderthattakesthreeargumentsoftypeint?Thefunctionreturnstrueiftheargumentsareinascendingorder;otherwise,itreturnsfalse.DeterminethevalueoftheseBooleanexpressions?Assumecount=0andlimit=10(count=0)elsecoutyislessthan)then:outputastatementsayingdontstop,Slide3-25,FirstTryNestedifs,TranslatingthepreviouspseudocodetoC+couldyield(ifwearenotcareful)if(fuel_gauge_reading0.75)if(fuel_gauge_reading0.25)coutFuelverylow.Caution!n;elsecoutnumber)coutToohigh.;elseif(guessnumber)coutToolow.);elseif(guess=number)coutnumber)coutToohigh.;elseif(guessnumber)coutToolow.);elseif(guess=number)coutnumber)coutToohigh.;elseif(guessnumber)coutToolow.);else/(guess=number)cout15000caseConstant_2:Statement_Sequence_2break;.caseConstant_n:Statement_Sequence_nbreak;default:Default_Statement_Sequence,Slide3-36,TheControllingStatement,AswitchstatementscontrollingstatementmustreturnoneofthesetypesAboolvalueAnenumconstantAnintegertypeAcharacterThevaluereturnediscomparedtotheconstantvaluesaftereachcaseWhenamatchisfound,thecodeforthatcaseisused,Slide3-37,ThebreakStatement,Thebreakstatementendstheswitch-statementOmittingthebreakstatementwillcausethecodeforthenextcasetobeexecuted!OmittingabreakstatementallowstheuseofmultiplecaselabelsforasectionofcodecaseA:casea:coutExcellent.;break;RunsthesamecodeforeitherAora,Slide3-38,ThedefaultStatement,Ifnocaselabelhasaconstantthatmatchesthecontrollingexpression,thestatementsfollowingthedefaultlabelareexecutedIfthereisnodefaultlabel,nothinghappenswhentheswitchstatementisexecutedItisagoodideatoincludeadefaultsection,Slide3-39,Switch-statementsandMenus,Nestedif-elsestatementsaremoreversatilethanaswitchstatementSwitch-statementscanmakesomecodemoreclearAmenuisanaturalapplicationforaswitch-statement,Slide3-40,Display3.7(1),Display3.7(2),FunctionCallsinBranches,Switchandif-else-statementsallowtheuseofmultiplestatementsinabranchMultiplestatementsinabranchcanmaketheswitchorif-else-statementdifficulttoreadUsingfunctioncalls(asshowninDisplay3.7)insteadofmultiplestatementscanmaketheswitchorif-else-statementmucheasiertoread,Slide3-41,Blocks,Eachbranchofaswitchorif-elsestatementisaseparatesub-taskIftheactionofabranchistoosimpletowarrantafunctioncall,usemultiplestatementsbetweenbracesAblockisasectionofcodeenclosedbybracesVariablesdeclaredwithinablock,arelocaltotheblockorhavetheblockastheirscope.Variablenamesdeclaredintheblockcanbereusedoutsidetheblock,Slide3-42,Display3.8(1),Display3.8(2),StatementBlocks,AstatementblockisablockthatisnotafunctionbodyorthebodyofthemainpartofaprogramStatementblockscanbenestedinotherstatementblocksNestingstatementblockscanmakecodedifficulttoreadItisgenerallybettertocreatefunctioncallsthantoneststatementblocks,Slide3-43,ScopeRuleforNestedBlocks,Ifasingleidentifierisdeclaredasavariableineachoftwoblocks,onewithintheother,thenthesearetwodifferentvariableswiththesamenameOneofthevariablesexistsonlywithintheinnerblockandcannotbeaccessedoutsidetheinnerblockTheothervariableexistsonlyintheouterblockandcannotbeaccessedintheinnerblock,Slide3-44,Section3.2Conclusion,CanyouGivetheoutputofthiscodefragment?intx=1;coutxendl;coutxendl;intx=2;coutxendl;coutxendl;,Slide3-45,3.3,MoreAboutC+LoopStatements,MoreAboutC+LoopStatements,AloopisaprogramconstructionthatrepeatsastatementorsequenceofstatementsanumberoftimesThebodyoftheloopisthestatement(s)repeatedEachrepetitionoftheloopisaniterationLoopdesignquestions:Whatshouldtheloopbodybe?Howmanytimesshouldthebodybeiterated?,Slide3-47,whileanddo-while,Animportantdifferencebetweenwhileanddo-whileloops:AwhileloopcheckstheBooleanexpressionatthebeginningoftheloopAwhileloopmightneverbeexecuted!Ado-whileloopcheckstheBooleanexpressionattheendoftheloopAdo-whileloopisalwaysexecutedatleastonceReviewwhileanddo-whilesyntaxin,Slide3-48,Display3.9,TheIncrementOperator,Wehaveusedtheincrementoperatorinstatementssuchasnumber+;toincreasethevalueofnumberbyoneTheincrementoperatorcanalsobeusedinexpressions:intnumber=2;intvalue_produced=2*(number+);(number+)firstreturnsthevalueofnumber(2)tobemultipliedby2,thenincrementsnumbertothree,Slide3-49,number+vs+number,(number+)returnsthecurrentvalueofnumber,thenincrementsnumberAnexpressionusing(number+)willusethevalueofnumberBEFOREitisincremented(+number)incrementsnumberfirstandreturnsthenewvalueofnumberAnexpressionusing(+number)willusethevalueofnumberAFTERitisincrementedNumberhasthesamevalueaftereitherversion!,Slide3-50,+Comparisons,intnumber=2;intvalue_produced=2*(number+);coutvalue_producednumber;displays43intnumber=2;intvalue_produced=2*(+number);coutvalue_producednumber;displays63,Slide3-51,Display3.10,TheDecrementOperator,Thedecrementoperator(-)decreasesthevalueofthevariablebyoneintnumber=8;intvalue_produced=number-;coutvalue_producednumber;displays87Replacingnumber-with-numberdisplays77,Slide3-52,Thefor-Statement,Afor-Statement(for-loop)isanotherloopmechanisminC+DesignedforcommontaskssuchasaddingnumbersinagivenrangeIssometimesmoreconvenienttousethanawhileloopDoesnotdoanythingawhileloopcannotdo,Slide3-53,for/whileLoopComparison,sum=0;n=1;while(n=10)/addthenumbers1-10sum=sum+n;n+;sum=0;for(n=1;n=10;n+)/addthenumbers1-10sum=sum+n;,Slide3-54,ForLoopDissection,Theforloopusesthesamecomponentsasthewhileloopinamorecompactformfor(n=1;n=10;n+),Slide3-55,InitializationAction,BooleanExpression,UpdateAction,forLoopAlternative,Aforloopcanalsoincludeavariabledeclarationintheinitializationactionfor(intn=1;n=0;number-)/loopbodystatementsshowsthesyntaxforafor-loopwithamulti-statementbody,Slide3-58,Display3.13,TheEmptyStatement,AsemicoloncreatesaC+statementPlacingasemicolonafterx+createsthestatementx+;PlacingasemicolonafternothingcreatesanemptystatementthatcompilesbutdoesnothingcoutHelloendl;coutGoodByeendl;,Slide3-59,ExtraSemicolon,PlacingasemicolonaftertheparenthesesofaforloopcreatesanemptystatementasthebodyoftheloopExample:for(intcount=1;count=10;count+);coutHellon;printsoneHello,butnotaspartoftheloop!TheemptystatementisthebodyoftheloopcoutHellon;isnotpartoftheloopbody!,Slide3-60,LocalVariableStandard,ANSIC+standardrequiresthatavariabledeclaredinthefor-loopinitializationsectionbelocaltotheblockofthefor-loopFindouthowyourcompilertreatsthesevariables!Ifyouwantyourcodetobeportable,donotdependonallcompilerstotreatthesevariablesaslocaltothefor-loop!,Slide3-61,WhichLoopToUse?,ChoosethetypeoflooplateinthedesignprocessFirstdesigntheloopusingpseudocodeTranslatethepseudocodeintoC+ThetranslationgenerallymakesthechoiceofanappropriateloopclearWhile-loopsareusedforallotherloopswhentheremightbeoccassionswhentheloopshouldnotrunDo-whileloopsareusedforallotherloopswhentheloopmustalwaysrunatleastonce,Slide3-62,Choosingafor-loop,for-loopsaretypicallyselectedwhendoingnumericcalculations,especiallywhenusingavariablechangedbyequalamountseachtimetheloopiterates,Slide3-63,Choosingawhile-loop,Awhile-loopistypicallyusedWhenafor-loopisnotappropriateWhentherearecircumstancesforwhichtheloopbodyshouldnotbeexecutedatall,Slide3-64,Choosingado-whileLoop,Ado-while-loopistypicallyusedWhenafor-loopisnotappropriateWhentheloopbodymustbeexecutedatleastonce,Slide3-65,Thebreak-Statement,TherearetimestoexitaloopbeforeitendsIftheloopchecksforinvalidinputthatwouldruinacalculation,itisoftenbesttoendtheloopThebreak-statementcanbeusedtoexitaloopbeforenormalterminationBecarefulwithnestedloops!Usingbreakonlyexitstheloopinwhichthebreak-statementoccurs,Slide3-66,Display3.14,Section3.3Conclusion,CanyouDeterminetheoutputofthefollowing?for(intcount=1;count5;count+)cout(2*count)next;sum=sum+next;endofloopThispseudocodecanbeimplementedwithafor-loopasshownonthenextslide,Slide3-70,for-loopforasum,Thepseudocodefromthepreviousslideisimplementedasintsum=0;for(intcount=1;countnext;sum=sum+next;summustbeinitializedpriortotheloopbody!,Slide3-71,Repeatthismanytimes,Pseudocodecontainingthelinerepeatthefollowingthismanytimesisoftenimplementedwithafor-loopAfor-loopisgenerallythechoicewhenthereisapredeterminednumberofiterationsExample:for(intcount=1;countnext;product=product*next;productmustbeinitializedpriortotheloopbodyNoticethatproductisinitializedto1,not0!,Slide3-73,EndingaLoop,ThearefourcommonmethodstoterminateaninputloopListheadedbysizeWhenwecandeterminethesizeofthelistbeforehandAskbeforeiteratingAskiftheuserwantstocontinuebeforeeachiterationListendedwithasentinelvalueUsingaparticularvaluetosignaltheendofthelistRunningoutofinputUsingtheeoffunctiontoindicatetheendofafile,Slide3-74,ListHeadedBySize,Thefor-loopswehaveseenprovideanaturalimplementationofthelistheadedbysizemethodofendingaloopExample:intitems;coutitems;for(intcount=1;countnumber;coutans;,Slide3-76,ListEndedWithaSentinelValue,Awhileloopistypicallyusedtoendaloopusingthelistendedwithasentinelvaluemethodcoutnumber;while(number0)/statementstoprocessthenumbercinnumber;Noticethatthesentinelvalueisread,butnotprocessed,Slide3-77,RunningOutofInput,Thewhileloopistypicallyusedtoimplementtherunningoutofinputmethodofendingaloopifstreaminfile;infile.open(data.dat);while(!infile.eof()/readandprocessitemsfromthefile/FileI/OcoveredinChapter6infile.close();,Slide3-78,GeneralMethodsToControlLoops,ThreegeneralmethodstocontrolanyloopCountcontrolledloopsAskbeforeiteratingExitonflagcondition,Slide3-79,CountControlledLoops,CountcontrolledloopsareloopsthatdeterminethenumberofiterationsbeforetheloopbeginsThelistheadedbysizeisanexampleofacountcontrolledloopforinput,Slide3-80,ExitonFlagCondition,LoopscanbeendedwhenaparticularflagconditionexistsAvariablethatchangesvaluetoindicatethatsomeeventhastakenplaceisaflagExamplesofexitonaflagconditionforinputListendedwithasentinelvalueRunningoutofinput,Slide3-81,ExitonFlagCaution,Considerthislooptoidentifyastudentwithagradeof90orbetterintn=1;grade=compute_grade(n);while(grade90)n+;grade=compute_grade(n);coutStudentnumbernhasascoreofgradeendl;,Slide3-82,TheProblem,Thelooponthepreviousslidemightnotstopattheendofthelistofstudentsifnostudenthasagradeof90orhigherItisagoodideatouseasecondflagtoensurethattherearestillstudentstoconsiderThecodeonthefollowingslideshowsabettersolution,Slide3-83,TheExitOnFlagSolution,Thiscodesolvestheproblemofhavingnostudentgradeat90orhigherintn=1;grade=compute_grade(n);while(grade90)/sameoutputasbeforeelsecoutNostudenthasahighscore.;,Slide3-84,NestedLoops,Thebodyofaloopmaycontainanykindofstatement,includinganotherloopWhenloopsarenested,alliterationsoftheinnerloopareexecutedforeachiterationoftheouterloopGiveseriousconsiderationtomakingtheinnerloopafunctioncalltomakeiteasiertoreadyourprogramDisplay3.15showtwoversionsofaprogramwithnestedloops,Slide3-85,Display3.15,DebuggingLoops,CommonerrorsinvolvingloopsincludeOff-by-oneerrorsinwhichtheloopexecutesonetoomanyoronetoofewtimesInfiniteloopsusuallyresultfromamistakeintheBooleanexpressionthatcontrolstheloop,Slide3-86,FixingOffByOneErrors,Checkyourcomparison:shoulditbeor=?CheckthattheinitializationusesthecorrectvalueDoestheloophandlethezeroiterationscase?,Slide3-87,FixingInfiniteLoops,Checkthedirectionofinequalities:?Testforratherthanequality(=)Rememberthatdoublesarereallyonlyapproximations,Slide3-88,MoreLoopDebuggingTips,BesurethatthemistakeisreallyintheloopTracethevariabletoobservehowthevariablechangesTracingavariableiswatchingitsvaluechangeduringexecutionManysystemsincludeutilitiestohelpwiththiscoutstatementscanbeusedtotraceavalue,Slide3-89,DebuggingExample,Thefollowingcodeissupposedtoconcludewiththevariableproductcontainingtheproductofthenumbers2through5intnext=2,product=1;while(next5)next+;product=product*next;,Slide3-90,TracingVariables,Addtemporarycoutstatementstotracevariablesintnext=2,product=1;while(next5)next+;product=product*next;coutnext=nextproduct=productendl;,Slide3-91,FirstFix,Thecoutstatementsaddedtotheloopshowusthattheloopnevermultipliedby2Solvetheproblembymovingthestatementnext+intnext=2,product=1;while(next5)product=product*next;next+;coutnext=nextproduct=productendl;Thereisstillaproblem!,Slide3-92,SecondFix,Re-testingtheloopshowsusthatnowtheloopnevermultipliesby5Thefixistouse=insteadofinourcomparisonintnext=2,product=1;while(ne

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论