Tải bản đầy đủ - 0 (trang)
Chapter 5. Control Statements: Part 2

Chapter 5. Control Statements: Part 2

Tải bản đầy đủ - 0trang

Chapter5.ControlStatements:Part2

Noteverythingthatcanbecountedcounts,andnot

everythingthatcountscanbecounted.

AlbertEinstein

Whocancontrolhisfate?

WilliamShakespeare

Theusedkeyisalwaysbright.

BenjaminFranklin

Intelligence...isthefacultyofmakingartificial

objects,especiallytoolstomaketools.

HenriBergson

Everyadvantageinthepastisjudgedinthelightof

thefinalissue.

Demosthenes

OBJECTIVES

Inthischapteryouwilllearn:

Theessentialsofcounter-controlledrepetition.

Tousetheforanddo...whilerepetitionstatementsto

executestatementsinaprogramrepeatedly.



Tounderstandmultipleselectionusingtheswitchselection

statement.

Tousethebreakandcontinueprogramcontrolstatementsto

altertheflowofcontrol.

Tousethelogicaloperatorstoformcomplexconditional

expressionsincontrolstatements.

Toavoidtheconsequencesofconfusingtheequalityand

assignmentoperators.



[Page186]

Outline

5.1Introduction

5.2EssentialsofCounter-ControlledRepetition

5.3forRepetitionStatement

5.4ExamplesUsingtheforStatement

5.5do...whileRepetitionStatement

5.6switchMultiple-SelectionStatement

5.7breakandcontinueStatements

5.8LogicalOperators

5.9ConfusingEquality(==)andAssignment(=)Operators

5.10StructuredProgrammingSummary

5.11(Optional)SoftwareEngineeringCaseStudy:Identifying



Objects'StatesandActivitiesintheATMSystem

5.12Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises



[Page186(continued)]



5.1.Introduction

Chapter4beganourintroductiontothetypesofbuildingblocks

thatareavailableforproblemsolving.Weusedthosebuilding

blockstoemployprovenprogramconstructiontechniques.In

thischapter,wecontinueourpresentationofthetheoryand

principlesofstructuredprogrammingbyintroducingC++'s

remainingcontrolstatements.Thecontrolstatementswestudy

hereandinChapter4willhelpusinbuildingandmanipulating

objects.Wecontinueourearlyemphasisonobject-oriented

programmingthatbeganwithadiscussionofbasicconceptsin

Chapter1andextensiveobject-orientedcodeexamplesand

exercisesinChapters34.

Inthischapter,wedemonstratethefor,do...whileandswitch

statements.Throughaseriesofshortexamplesusingwhileand

for,weexploretheessentialsofcounter-controlledrepetition.

WedevoteaportionofthechaptertoexpandingtheGradeBook

classpresentedinChapters34.Inparticular,wecreatea

versionofclassGradeBookthatusesaswitchstatementtocount

thenumberofA,B,C,DandFgradesinasetoflettergrades

enteredbytheuser.Weintroducethebreakandcontinueprogram

controlstatements.Wediscussthelogicaloperators,which

enableprogrammerstousemorepowerfulconditional

expressionsincontrolstatements.Wealsoexaminethe

commonerrorofconfusingtheequality(==)andassignment(=)

operators,andhowtoavoidit.Finally,wesummarizeC++'s

controlstatementsandtheprovenproblem-solvingtechniques

presentedinthischapterandChapter4.



[Page186(continued)]



5.2.EssentialsofCounter-ControlledRepetition

Thissectionusesthewhilerepetitionstatementintroducedin

Chapter4toformalizetheelementsrequiredtoperform

counter-controlledrepetition.Counter-controlledrepetition

requires

1. thenameofacontrolvariable(orloopcounter)

2. theinitialvalueofthecontrolvariable



[Page187]

3. theloop-continuationconditionthattestsforthefinal

valueofthecontrolvariable(i.e.,whetherloopingshould

continue)

4. theincrement(ordecrement)bywhichthecontrol

variableismodifiedeachtimethroughtheloop.

ConsiderthesimpleprograminFig.5.1,whichprintsthe

numbersfrom1to10.Thedeclarationatline9namesthe

controlvariable(counter),declaresittobeaninteger,reserves

spaceforitinmemoryandsetsittoaninitialvalueof1.

Declarationsthatrequireinitializationare,ineffect,executable

statements.InC++,itismoreprecisetocalladeclarationthat

alsoreservesmemoryastheprecedingdeclarationdoesa

definition.Becausedefinitionsaredeclarations,too,wewill

usetheterm"declaration"exceptwhenthedistinctionis

important.



Figure5.1.Counter-controlledrepetition.



1//Fig.5.1:fig05_01.cpp

2//Counter-controlledrepetition.

3#include

4usingstd::cout;

5usingstd::endl;

6

7intmain()

8{

9intcounter=1;//declareandinitializecontrolvariable

10

11while(counter<=10)//loop-continuationcondition

12{

13cout<
14counter++;//incrementcontrolvariableby1

15}//endwhile

16

17cout<
18return0;//successfultermination

19}//endmain



12345678910



Thedeclarationandinitializationofcounter(line9)alsocould

havebeenaccomplishedwiththestatements

intcounter;//declarecontrolvariable

counter=1;//initializecontrolvariableto1



Weusebothmethodsofinitializingvariables.

Line14incrementstheloopcounterby1eachtimetheloop's

bodyisperformed.Theloop-continuationcondition(line11)in

thewhilestatementdetermineswhetherthevalueofthecontrol

variableislessthanorequalto10(thefinalvalueforwhichthe

conditionisTRue).Notethatthebodyofthiswhileexecuteseven



whenthecontrolvariableis10.Theloopterminateswhenthe

controlvariableisgreaterthan10(i.e.,whencounterbecomes

11).



[Page188]

Figure5.1canbemademoreconcisebyinitializingcounterto0

andbyreplacingthewhilestatementwith

while(++counter<=10)//loop-continuationcondition

cout<


Thiscodesavesastatement,becausetheincrementingisdone

directlyinthewhileconditionbeforetheconditionistested.

Also,thecodeeliminatesthebracesaroundthebodyofthe

while,becausethewhilenowcontainsonlyonestatement.

Codinginsuchacondensedfashiontakessomepracticeand

canleadtoprogramsthataremoredifficulttoread,debug,

modifyandmaintain.



CommonProgrammingError5.1

Floating-pointvaluesareapproximate,socontrolling

countingloopswithfloating-pointvariablescanresultin

imprecisecountervaluesandinaccuratetestsfor

termination.



Error-PreventionTip5.1

Controlcountingloopswithintegervalues.



GoodProgrammingPractice5.1

Putablanklinebeforeandaftereachcontrolstatement

tomakeitstandoutintheprogram.



GoodProgrammingPractice5.2

Toomanylevelsofnestingcanmakeaprogramdifficult

tounderstand.Asarule,trytoavoidusingmorethan

threelevelsofindentation.



GoodProgrammingPractice5.3

Verticalspacingaboveandbelowcontrolstatementsand

indentationofthebodiesofcontrolstatementswithinthe

controlstatementheadersgiveprogramsatwodimensionalappearancethatgreatlyimproves

readability.



[Page188(continued)]



5.3.forRepetitionStatement

Section5.2presentedtheessentialsofcounter-controlled

repetition.Thewhilestatementcanbeusedtoimplementany

counter-controlledloop.C++alsoprovidestheforrepetition

statement,whichspecifiesthecounter-controlledrepetition

detailsinasinglelineofcode.Toillustratethepoweroffor,let

usrewritetheprogramofFig.5.1.TheresultisshowninFig.

5.2.



Figure5.2.Counter-controlledrepetitionwiththe

forstatement.

(Thisitemisdisplayedonpage189intheprintversion)



1//Fig.5.2:fig05_02.cpp

2//Counter-controlledrepetitionwiththeforstatement.

3#include

4usingstd::cout;

5usingstd::endl;

6

7intmain()

8{

9//forstatementheaderincludesinitialization,

10//loop-continuationconditionandincrement.

11for(intcounter=1;counter<=10;counter++)

12cout<
13

14cout<
15return0;//indicatesuccessfultermination

16}//endmain



12345678910



Whentheforstatement(lines1112)beginsexecuting,the

controlvariablecounterisdeclaredandinitializedto1.Then,the

loop-continuationconditioncounter<=10ischecked.Theinitial

valueofcounteris1,sotheconditionissatisfiedandthebody

statement(line12)printsthevalueofcounter,namely1.Then,

theexpressioncounter++incrementscontrolvariablecounterand

theloopbeginsagainwiththeloop-continuationtest.The

controlvariableisnowequalto2,sothefinalvalueisnot

exceededandtheprogramperformsthebodystatementagain.

Thisprocesscontinuesuntiltheloopbodyhasexecuted10

timesandthecontrolvariablecounterisincrementedto11this

causestheloop-continuationtest(line11betweenthe

semicolons)tofailandrepetitiontoterminate.Theprogram

continuesbyperformingthefirststatementafterthefor

statement(inthiscase,theoutputstatementatline14).



[Page189]



forStatementHeaderComponents

Figure5.3takesacloserlookattheforstatementheader(line

11)ofFig.5.2.Noticethattheforstatementheader"doesit

all"itspecifieseachoftheitemsneededforcounter-controlled

repetitionwithacontrolvariable.Ifthereismorethanone

statementinthebodyofthefor,bracesarerequiredtoenclose

thebodyoftheloop.



Figure5.3.forstatementheadercomponents.



[Viewfullsizeimage]



NoticethatFig.5.2usestheloop-continuationconditioncounter

<=10.Iftheprogrammerincorrectlywrotecounter<10,thenthe

loopwouldexecuteonly9times.Thisisacommonoff-by-one

error.



CommonProgrammingError5.2

Usinganincorrectrelationaloperatororusingan

incorrectfinalvalueofaloopcounterintheconditionof

awhileorforstatementcancauseoff-by-oneerrors.



[Page190]

GoodProgrammingPractice5.4

Usingthefinalvalueintheconditionofawhileorfor

statementandusingthe<=relationaloperatorwillhelp

avoidoff-by-oneerrors.Foraloopusedtoprintthe

values1to10,forexample,theloop-continuation

conditionshouldbecounter<=10ratherthancounter<10

(whichisanoff-by-oneerror)orcounter<11(whichis

neverthelesscorrect).Manyprogrammersprefersocalledzero-basedcounting,inwhich,tocount10

timesthroughtheloop,counterwouldbeinitializedto



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 5. Control Statements: Part 2

Tải bản đầy đủ ngay(0 tr)

×