




已阅读5页,还剩113页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Copyright2008PearsonAddison-Wesley.Allrightsreserved.,Chapter3,MoreFlowofControl,Slide3-3,Overview,3.1UsingBooleanExpressions3.2MultiwayBranches3.3MoreaboutC+LoopStatements3.4DesigningLoops,Slide3-4,FlowOfControl,FlowofcontrolreferstotheorderinwhichprogramstatementsareperformedWehaveseenthefollowingwaystospecifyflowofcontrolif-else-statementswhile-statementsdo-while-statementsNewmethodsdescribedinthischapterincludeswitch-statementsfor-statements,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,3.1,UsingBooleanExpressions,Slide3-6,UsingBooleanExpressions,ABooleanExpressionisanexpressionthatiseithertrueorfalseBooleanexpressionsareevaluatedusingrelationaloperationssuchas=,=whichproduceabooleanvalueandbooleanoperationssuchas,Slide3-21,DefaultenumValues,Ifnumericvaluesarenotspecified,identifiersareassignedconsecutivevaluesstartingwith0enumDirectionNORTH=0,SOUTH=1,EAST=2,WEST=3;isequivalenttoenumDirectionNORTH,SOUTH,EAST,WEST;,Slide3-22,EnumerationValues,Unlessspecified,thevalueassignedanenumerationconstantis1morethanthepreviousconstantEnumMyEnumONE=17,TWO,THREE,FOUR=-3,FIVE;resultsinthesevaluesONE=17,TWO=18,THREE=19,FOUR=-3,FIVE=-2,Slide3-23,Section7.1Conclusion,CanyouWriteafunctiondefinitionforafunctionnamedin_orderthattakesthreeargumentsoftypeint?Thefunctionreturnstrueiftheargumentsareinascendingorder;otherwise,itreturnsfalse.DeterminethevalueoftheseBooleanexpressions?Assumecount=0andlimit=10(count=0)elsecoutyislessthan)then:outputastatementsayingdontstop,Slide3-28,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-39,TheControllingStatement,AswitchstatementscontrollingstatementmustreturnoneofthesetypesAboolvalueAnenumconstantAnintegertypeAcharacterThevaluereturnediscomparedtotheconstantvaluesaftereachcaseWhenamatchisfound,thecodeforthatcaseisused,Slide3-40,ThebreakStatement,Thebreakstatementendstheswitch-statementOmittingthebreakstatementwillcausethecodeforthenextcasetobeexecuted!OmittingabreakstatementallowstheuseofmultiplecaselabelsforasectionofcodecaseA:casea:coutExcellent.;break;RunsthesamecodeforeitherAora,Slide3-41,ThedefaultStatement,Ifnocaselabelhasaconstantthatmatchesthecontrollingexpression,thestatementsfollowingthedefaultlabelareexecutedIfthereisnodefaultlabel,nothinghappenswhentheswitchstatementisexecutedItisagoodideatoincludeadefaultsection,Nestedif-elsestatementsaremoreversatilethanaswitchstatementSwitch-statementscanmakesomecodemoreclearAmenuisanaturalapplicationforaswitch-statement,Slide3-42,Display3.7(1),Display3.7(2),Switch-statementsandMenus,Slide3-43,FunctionCallsinBranches,Switchandif-else-statementsallowtheuseofmultiplestatementsinabranchMultiplestatementsinabranchcanmaketheswitchorif-else-statementdifficulttoreadUsingfunctioncalls(asshowninDisplay3.7)insteadofmultiplestatementscanmaketheswitchorif-else-statementmucheasiertoread,Eachbranchofaswitchorif-elsestatementisaseparatesub-taskIftheactionofabranchistoosimpletowarrantafunctioncall,usemultiplestatementsbetweenbracesAblockisasectionofcodeenclosedbybracesVariablesdeclaredwithinablock,arelocaltotheblockorhavetheblockastheirscope.Variablenamesdeclaredintheblockcanbereusedoutsidetheblock,Slide3-44,Display3.8(1),Display3.8(2),Blocks,Slide3-45,StatementBlocks,AstatementblockisablockthatisnotafunctionbodyorthebodyofthemainpartofaprogramStatementblockscanbenestedinotherstatementblocksNestingstatementblockscanmakecodedifficulttoreadItisgenerallybettertocreatefunctioncallsthantoneststatementblocks,Slide3-46,ScopeRuleforNestedBlocks,Ifasingleidentifierisdeclaredasavariableineachoftwoblocks,onewithintheother,thenthesearetwodifferentvariableswiththesamenameOneofthevariablesexistsonlywithintheinnerblockandcannotbeaccessedoutsidetheinnerblockTheothervariableexistsonlyintheouterblockandcannotbeaccessedintheinnerblock,Slide3-47,Section3.2Conclusion,CanyouGivetheoutputofthiscodefragment?intx=1;coutxendl;coutxendl;intx=2;coutxendl;coutxendl;,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,3.3,MoreAboutC+LoopStatements,Slide3-49,MoreAboutC+LoopStatements,AloopisaprogramconstructionthatrepeatsastatementorsequenceofstatementsanumberoftimesThebodyoftheloopisthestatement(s)repeatedEachrepetitionoftheloopisaniterationLoopdesignquestions:Whatshouldtheloopbodybe?Howmanytimesshouldthebodybeiterated?,Animportantdifferencebetweenwhileanddo-whileloops:AwhileloopcheckstheBooleanexpressionatthebeginningoftheloopAwhileloopmightneverbeexecuted!Ado-whileloopcheckstheBooleanexpressionattheendoftheloopAdo-whileloopisalwaysexecutedatleastonceReviewwhileanddo-whilesyntaxin,Slide3-50,Display3.9,whileanddo-while,Slide3-51,TheIncrementOperator,Wehaveusedtheincrementoperatorinstatementssuchasnumber+;toincreasethevalueofnumberbyoneTheincrementoperatorcanalsobeusedinexpressions:intnumber=2;intvalue_produced=2*(number+);(number+)firstreturnsthevalueofnumber(2)tobemultipliedby2,thenincrementsnumbertothree,Slide3-52,number+vs+number,(number+)returnsthecurrentvalueofnumber,thenincrementsnumberAnexpressionusing(number+)willusethevalueofnumberBEFOREitisincremented(+number)incrementsnumberfirstandreturnsthenewvalueofnumberAnexpressionusing(+number)willusethevalueofnumberAFTERitisincrementedNumberhasthesamevalueaftereitherversion!,intnumber=2;intvalue_produced=2*(number+);coutvalue_producednumber;displays43intnumber=2;intvalue_produced=2*(+number);coutvalue_producednumber;displays63,Slide3-53,Display3.10,+Comparisons,Slide3-54,TheDecrementOperator,Thedecrementoperator(-)decreasesthevalueofthevariablebyoneintnumber=8;intvalue_produced=number-;coutvalue_producednumber;displays87Replacingnumber-with-numberdisplays77,Slide3-55,Thefor-Statement,Afor-Statement(for-loop)isanotherloopmechanisminC+DesignedforcommontaskssuchasaddingnumbersinagivenrangeIssometimesmoreconvenienttousethanawhileloopDoesnotdoanythingawhileloopcannotdo,Slide3-56,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-57,Theforloopusesthesamecomponentsasthewhileloopinamorecompactformfor(n=1;n=10;n+),InitializationAction,BooleanExpression,UpdateAction,ForLoopDissection,Aforloopcanalsoincludeavariabledeclarationintheinitializationactionfor(intn=1;n=0;number-)/loopbodystatementsshowsthesyntaxforafor-loopwithamulti-statementbody,Slide3-60,Display3.13,Thefor-loopBody,Slide3-61,TheEmptyStatement,AsemicoloncreatesaC+statementPlacingasemicolonafterx+createsthestatementx+;PlacingasemicolonafternothingcreatesanemptystatementthatcompilesbutdoesnothingcoutHelloendl;coutGoodByeendl;,Slide3-62,ExtraSemicolon,PlacingasemicolonaftertheparenthesesofaforloopcreatesanemptystatementasthebodyoftheloopExample:for(intcount=1;count=10;count+);coutHellon;printsoneHello,butnotaspartoftheloop!TheemptystatementisthebodyoftheloopcoutHellon;isnotpartoftheloopbody!,Slide3-63,LocalVariableStandard,ANSIC+standardrequiresthatavariabledeclaredinthefor-loopinitializationsectionbelocaltotheblockofthefor-loopFindouthowyourcompilertreatsthesevariables!Ifyouwantyourcodetobeportable,donotdependonallcompilerstotreatthesevariablesaslocaltothefor-loop!,Slide3-64,WhichLoopToUse?,ChoosethetypeoflooplateinthedesignprocessFirstdesigntheloopusingpseudocodeTranslatethepseudocodeintoC+ThetranslationgenerallymakesthechoiceofanappropriateloopclearWhile-loopsareusedforallotherloopswhentheremightbeoccassionswhentheloopshouldnotrunDo-whileloopsareusedforallotherloopswhentheloopmustalwaysrunatleastonce,Slide3-65,Choosingafor-loop,for-loopsaretypicallyselectedwhendoingnumericcalculations,especiallywhenusingavariablechangedbyequalamountseachtimetheloopiterates,Slide3-66,Choosingawhile-loop,Awhile-loopistypicallyusedWhenafor-loopisnotappropriateWhentherearecircumstancesforwhichtheloopbodyshouldnotbeexecutedatall,Slide3-67,Choosingado-whileLoop,Ado-while-loopistypicallyusedWhenafor-loopisnotappropriateWhentheloopbodymustbeexecutedatleastonce,TherearetimestoexitaloopbeforeitendsIftheloopchecksforinvalidinputthatwouldruinacalculation,itisoftenbesttoendtheloopThebreak-statementcanbeusedtoexitaloopbeforenormalterminationBecarefulwithnestedloops!Usingbreakonlyexitstheloopinwhichthebreak-statementoccurs,Slide3-68,Display3.14,Thebreak-Statement,Slide3-69,Section3.3Conclusion,CanyouDeterminetheoutputofthefollowing?for(intcount=1;count5;count+)cout(2*count)next;sum=sum+next;endofloopThispseudocodecanbeimplementedwithafor-loopasshownonthenextslide,Slide3-73,for-loopforasum,Thepseudocodefromthepreviousslideisimplementedasintsum=0;for(intcount=1;countnext;sum=sum+next;summustbeinitializedpriortotheloopbody!,Slide3-74,Repeatthismanytimes,Pseudocodecontainingthelinerepeatthefollowingthismanytimesisoftenimplementedwithafor-loopAfor-loopisgenerallythechoicewhenthereisapredeterminednumberofiterationsExample:for(intcount=1;countnext;product=product*next;productmustbeinitializedpriortotheloopbodyNoticethatproductisinitializedto1,not0!,Slide3-76,EndingaLoop,ThearefourcommonmethodstoterminateaninputloopListheadedbysizeWhenwecandeterminethesizeofthelistbeforehandAskbeforeiteratingAskiftheuserwantstocontinuebeforeeachiterationListendedwithasentinelvalueUsingaparticularvaluetosignaltheendofthelistRunningoutofinputUsingtheeoffunctiontoindicatetheendofafile,Slide3-77,ListHeadedBySize,Thefor-loopswehaveseenprovideanaturalimplementationofthelistheadedbysizemethodofendingaloopExample:intitems;coutitems;for(intcount=1;countnumber;coutans;,Slide3-79,ListEndedWithaSentinelValue,Awhileloopistypicallyusedtoendaloopusingthelistendedwithasentinelvaluemethodcoutnumber;while(number0)/statementstoprocessthenumbercinnumber;Noticethatthesentinelvalueisread,butnotprocessed,Slide3-80,RunningOutofInput,Thewhileloopistypicallyusedtoimplementtherunningoutofinputmethodofendingaloopifstreaminfile;infile.open(data.dat);while(!infile.eof()/readandprocessitemsfromthefile/FileI/OcoveredinChapter6infile.close();,Slide3-81,GeneralMethodsToControlLoops,ThreegeneralmethodstocontrolanyloopCountcontrolledloopsAskbeforeiteratingExitonflagcondition,Slide3-82,CountControlledLoops,CountcontrolledloopsareloopsthatdeterminethenumberofiterationsbeforetheloopbeginsThelistheadedbysizeisanexampleofacountcontrolledloopforinput,Slide3-83,ExitonFlagCondition,LoopscanbeendedwhenaparticularflagconditionexistsAvariablethatchangesvaluetoindicatethatsomeeventhastakenplaceisaflagExamplesofexitonaflagconditionforinputListendedwithasentinelvalueRunningoutofinput,Slide3-84,ExitonFlagCaution,Considerthislooptoidentifyastudentwithagradeof90orbetterintn=1;grade=compute_grade(n);while(grade90)n+;grade=compute_grade(n);coutStudentnumbernhasascoreofgradeendl;,Slide3-85,TheProblem,Thelooponthepreviousslidemightnotstopattheendofthelistofstudentsifnostudenthasagradeof90orhigherItisagoodideatouseasecondflagtoensurethattherearestillstudentstoconsiderThecodeonthefollowingslideshowsabettersolution,Slide3-86,TheExitOnFlagSolution,Thiscodesolvestheproblemofhavingnostudentgradeat90orhigherintn=1;grade=compute_grade(n);while(grade90)/sameoutputasbeforeelsecoutNostudenthasahighscore.;,Thebodyofaloopmaycontainanykindofstatement,includinganotherloopWhenloopsarenested,alliterationsoftheinnerloopareexecutedforeachiterationoftheouterloopGiveseriousconsiderationtomakingtheinnerloopafunctioncalltomakeiteasiertoreadyourprogramDisplay3.15showtwoversionsofaprogramwithnestedloops,Slide3-87,Display3.15,NestedLoops,Slide3-88,DebuggingLoops,CommonerrorsinvolvingloopsincludeOff-by-oneerrorsinwhichtheloopexecutesonetoomanyoronetoofewtimesInfiniteloopsusuallyresultfromamistakeintheBooleanexpressionthatcontrolstheloop,Slide3-89,FixingOffByOneErrors,Checkyourcomparison:shoulditbeor=?CheckthattheinitializationusesthecorrectvalueDoestheloophandlethezeroiterationscase?,Slide3-90,FixingInfiniteLoops,Checkthedirectionofinequalities:?Testforratherthanequality(=)Rememberthatdoublesarereallyonlyapproximations,Slide3-91,MoreLoopDebuggingTips,BesurethatthemistakeisreallyintheloopTracethevariabletoobservehowthevariablechangesTracingavariableiswatchingitsvaluechangeduringexecutionManysystemsincludeutilitiestohelpwiththiscoutstatementscanbeusedtotraceavalue,Slide3-92,DebuggingExample,Thefollowingcodeissupposedtoconcludewiththevariableproductcontainingtheproductofthenumbers2through5intnext=2,product=1;while(next5)next+;product=product*next;,Slide3-93,TracingVariables,Addtemporarycoutstatementstotracevariablesintnext=2,product=1;while(next5)next+;product=product*next;coutnext=nextproduct=productendl;,Slide3-94,FirstFix,Thecoutstatementsaddedtotheloopshowusthattheloopnevermultipliedby2Solvetheproblembymovingthestatementnext+intnext=2,product=1;while(next5)product=product*next;next+;coutnext=nextproduct=productendl;Thereisstillaproblem!,Slide3-95,SecondFix,Re-testingtheloopshowsusthatnowtheloopnevermultipliesby5Thefixistouse=insteadofinourcomparisonintn
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年三基三严考试题题库(含答案)
- 2025年公共营养师之三级营养师通关考试题库带答案解析
- 2024年特种设备安全技术考试试题和答案
- 摄影基础知识培训课件讲座
- 施工技术期末试题及答案
- 2025关于共同合作合同范本
- 2025装载机租赁合同书范本
- 2025租赁合同纠纷范文
- 知识题库-人社练兵比武劳动竞赛试题及答案(二十四)
- 搬运车安全知识培训内容课件
- 轧钢厂安全检查表
- 艺术课程标准(2022年版)
- 卫生部手术分级目录(2023年1月份修订)
- YC/T 199-2006卷烟企业清洁生产评价准则
- YY 0666-2008针尖锋利度和强度试验方法
- GB/T 6663.1-2007直热式负温度系数热敏电阻器第1部分:总规范
- GB/T 5184-1996叉车挂钩型货叉和货叉架安装尺寸
- GB/T 19355.2-2016锌覆盖层钢铁结构防腐蚀的指南和建议第2部分:热浸镀锌
- 小沈阳《四大才子》欢乐喜剧人台词
- 机械制造技术基础(课程精完整版)课件
- 护士注册健康体检表下载【可直接打印版本】
评论
0/150
提交评论