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

Chapter 6. Control Statements: Part 2

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

Chapter6.ControlStatements:Part2

Noteverythingthatcanbecountedcounts,andnot

everythingthatcountscanbecounted.

AlbertEinstein

Whocancontrolhisfate?

WilliamShakespeare

Theusedkeyisalwaysbright.

BenjaminFranklin

Intelligence...isthefacultyofmakingartificial

objects,especiallytoolstomaketools.

HenriBergson

Everyadvantageinthepastisjudgedinthelightof

thefinalissue.

Demosthenes

OBJECTIVES

Inthischapteryouwilllearn:

Theessentialsofcounter-controlledrepetition.

Tousetheforanddo...whilerepetitionstatementsto

executestatementsinanapplicationrepeatedly.



Tounderstandmultipleselectionusingtheswitchselection

statement.

Tousethebreakandcontinueprogramcontrolstatementsto

altertheflowofcontrol.

Tousethelogicaloperatorstoformcomplexconditional

expressionsincontrolstatements.



[Page224]



Outline

6.1 Introduction

6.2 EssentialsofCounter-ControlledRepetition

6.3 forRepetitionStatement

6.4 ExamplesUsingtheforStatement

6.5 do...whileRepetitionStatement

6.6 switchMultiple-SelectionStatement

6.7 breakandcontinueStatements

6.8 LogicalOperators

6.9 StructuredProgrammingSummary

6.10 (Optional)SoftwareEngineeringCaseStudy:IdentifyingObjects'

StatesandActivitiesintheATMSystem

6.11 Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page224(continued)]



6.1.Introduction

Chapter5beganourintroductiontothetypesofbuildingblocks

thatareavailableforproblemsolving.Weusedthosebuilding

blockstoemployprovenapplicationconstructiontechniques.In

thischapter,wecontinueourpresentationofthetheoryand

principlesofstructuredprogrammingbyintroducingallbutone

ofC#'sremainingcontrolstatements.Thecontrolstatements

westudyhereandinChapter5arehelpfulinbuildingand

manipulatingobjects.

Inthischapter,wedemonstrateC#'sfor,do...whileandswitch

statements.Throughaseriesofshortexamplesusingwhileand

for,weexploretheessentialsofcounter-controlledrepetition.

Wedevoteaportionofthechapter(andChapter8)to

expandingtheGradeBookclasspresentedinChapters4and5.In

particular,wecreateaversionofclassGradeBookthatusesa

switchstatementtocountthenumberofA,B,C,DandFgrade

equivalentsinasetofnumericgradesenteredbytheuser.We

introducethebreakandcontinueprogramcontrolstatements.We

discussC#'slogicaloperators,whichenableyoutousemore

complexconditionalexpressionsincontrolstatements.Finally,

wesummarizeC#'scontrolstatementsandtheproven

problem-solvingtechniquespresentedinthischapterand

Chapter5.



[Page224(continued)]



6.2.EssentialsofCounter-ControlledRepetition

Thissectionusesthewhilerepetitionstatementintroducedin

Chapter5toformalizetheelementsrequiredtoperform

counter-controlledrepetition.Counter-controlledrepetition

requires

1. acontrolvariable(orloopcounter)

2. theinitialvalueofthecontrolvariable

3. theincrement(ordecrement)bywhichthecontrol

variableismodifiedeachtimethroughtheloop(alsoknown

aseachiterationoftheloop)

4. theloop-continuationconditionthatdetermineswhether

loopingshouldcontinue.



[Page225]

Toseetheseelementsofcounter-controlledrepetition,consider

theapplicationofFig.6.1,whichusesalooptodisplaythe

numbersfrom1through10.NotethatFig.6.1containsonly

onemethod,Main,whichdoesalloftheclass'swork.Formost

applicationsinChapters4and5,wehaveencouragedtheuse

oftwoseparatefilesonethatdeclaresareusableclass(e.g.,

Account)andonethatinstantiatesoneormoreobjectsofthat

class(e.g.,AccountTest)anddemonstratestheirfunctionality.

Occasionally,however,itismoreappropriatesimplytocreate

oneclasswhoseMainmethodconciselyillustratesabasic

concept.Throughoutthischapter,weuseseveralone-class

exampleslikeFig.6.1todemonstratethemechanicsofvarious

C#controlstatements.



Figure6.1.Counter-controlledrepetitionwiththe

whilerepetitionstatement.



1//Fig.6.1:WhileCounter.cs

2//Counter-controlledrepetitionwiththewhilerepetitionstatement.

3usingSystem;

4

5publicclassWhileCounter

6{

7publicstaticvoidMain(string[]args)

8{

9intcounter=1;//declareandinitializecontrolvariable

10

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

12{

13Console.Write("{0}",counter);

14counter++;//incrementcontrolvariable

15}//endwhile

16

17Console.WriteLine();//outputanewline

18}//endMain

19}//endclassWhileCounter



12345678910



InmethodMainofFig.6.1(lines718),theelementsofcountercontrolledrepetitionaredefinedinlines9,11and14.Line9

declaresthecontrolvariable(counter)asanint,reservesspace

foritinmemoryandsetsitsinitialvalueto1.

Line13inthewhilestatementdisplayscontrolvariablecounter's

valueduringeachiterationoftheloop.Line14incrementsthe

controlvariableby1foreachiterationoftheloop.Theloopcontinuationconditioninthewhile(line11)testswhetherthe

valueofthecontrolvariableislessthanorequalto10(thefinal

valueforwhichtheconditionistrue).Notethattheapplication

performsthebodyofthiswhileevenwhenthecontrolvariableis



10.Theloopterminateswhenthecontrolvariableexceeds10



(i.e.,counterbecomes11).



CommonProgrammingError6.1

Becausefloating-pointvaluesmaybeapproximate,controllingloops

withfloating-pointvariablesmayresultinimprecisecountervaluesand

inaccurateterminationtests.



Error-PreventionTip6.1

Controlcountingloopswithintegers.



[Page226]



GoodProgrammingPractice6.1

Placeblanklinesaboveandbelowrepetitionandselectioncontrol

statements,andindentthestatementbodiestoenhancereadability.



TheapplicationinFig.6.1canbemademoreconciseby

initializingcounterto0inline9andincrementingcounterinthe

whileconditionwiththeprefixincrementoperatorasfollows:

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

Console.Write("{0}",counter);



Thiscodesavesastatement(andeliminatestheneedfor

bracesaroundtheloop'sbody),becausethewhilecondition

performstheincrementbeforetestingthecondition.(Recall

fromSection5.12thattheprecedenceof++ishigherthanthat

of<=.)Codinginsuchacondensedfashionmightmakecode

moredifficulttoread,debug,modifyandmaintain.



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

Chapter 6. Control Statements: Part 2

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

×