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

Chapter 5. Control Statements: Part 1

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

Chapter5.ControlStatements:Part1

Let'sallmoveoneplaceon.

LewisCarroll

Thewheeliscomefullcircle.

WilliamShakespeare

HowmanyapplesfellonNewton'sheadbeforehe

tookthehint!

RobertFrost

Alltheevolutionweknowofproceedsfromthe

vaguetothedefinite.

CharlesSandersPeirce

OBJECTIVES

Inthischapteryouwilllearn:

Tousebasicproblem-solvingtechniques.

Todevelopalgorithmsthroughtheprocessoftop-down,

stepwiserefinement.

Tousetheifandif...elseselectionstatementstochoose

betweenalternativeactions.

Tousethewhilerepetitionstatementtoexecutestatements

inanapplicationrepeatedly.



Tousecounter-controlledrepetitionandsentinel-controlled

repetition.

Tousetheincrement,decrementandcompound

assignmentoperators.



[Page172]



Outline

5.1 Introduction

5.2 Algorithms

5.3 Pseudocode

5.4 ControlStructures

5.5 ifSingle-SelectionStatement

5.6 if...elseDouble-SelectionStatement

5.7 whileRepetitionStatement

5.8 FormulatingAlgorithms:Counter-ControlledRepetition

5.9 FormulatingAlgorithms:Sentinel-ControlledRepetition

5.10 FormulatingAlgorithms:NestedControlStatements

5.11 CompoundAssignmentOperators

5.12 IncrementandDecrementOperators

5.13 SimpleTypes

5.14 (Optional)SoftwareEngineeringCaseStudy:IdentifyingClass

AttributesintheATMSystem

5.15 Wrap-Up

Summary



Terminology



Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page172(continued)]



5.1.Introduction

Beforewritinganapplicationtosolveaproblem,itisessential

tohaveathoroughunderstandingoftheproblemanda

carefullyplannedapproachtosolvingit.Whenwritingan

application,itisalsoessentialtounderstandthetypesof

buildingblocksthatareavailableandtoemployproven

application-constructiontechniques.Inthischapterandin

Chapter6,ControlStatements:Part2,wediscusstheseissues

inourpresentationofthetheoryandprinciplesofstructured

programming.Theconceptspresentedherearecrucialto

buildingclassesandmanipulatingobjects.

Inthischapter,weintroduceC#'sif,if...elseandwhilecontrol

statements,threeofthebuildingblocksthatallowyouto

specifythelogicrequiredformethodstoperformtheirtasks.

Wedevoteaportionofthechapter(andChapters6and8)to

furtherdevelopingtheGradeBookclassintroducedinChapter4.In

particular,weaddamethodtotheGradeBookclassthatuses

controlstatementstocalculatetheaverageofasetofstudent

grades.Anotherexampledemonstratesadditionalwaysto

combinecontrolstatementstosolveasimilarproblem.We

introduceC#'scompoundassignmentoperatorsandexploreits

incrementanddecrementoperators.Theseadditionaloperators

abbreviateandsimplifymanystatements.Finally,wepresent

anoverviewofC#'ssimpletypes.







[Page172(continued)]



5.2.Algorithms

Anycomputingproblemcanbesolvedbyexecutingaseriesof

actionsinaspecificorder.Aprocedureforsolvingaproblemin

termsof

1. theactionstoexecuteand

2. theorderinwhichtheseactionsexecute



[Page173]

iscalledanalgorithm.Thefollowingexampledemonstrates

thatcorrectlyspecifyingtheorderinwhichtheactionsexecute

isimportant.

Considerthe"rise-and-shinealgorithm"followedbyone

executiveforgettingoutofbedandgoingtowork:(1)Getout

ofbed;(2)takeoffpajamas;(3)takeashower;(4)get

dressed;(5)eatbreakfast;(6)carpooltowork.Thisroutine

getstheexecutivetoworkwellpreparedtomakecritical

decisions.Supposethatthesamestepsareperformedina

slightlydifferentorder:(1)Getoutofbed;(2)takeoff

pajamas;(3)getdressed;(4)takeashower;(5)eatbreakfast;

(6)carpooltowork.Inthiscase,ourexecutiveshowsupfor

worksoakingwet.

Specifyingtheorderinwhichstatements(actions)executein

anapplicationiscalledprogramcontrol.Thischapter

investigatesprogramcontrolusingC#'scontrolstatements.







[Page173(continued)]



5.3.Pseudocode

Pseudocodeisaninformallanguagethathelpsprogrammers

developalgorithmswithouthavingtoworryaboutthestrict

detailsofC#languagesyntax.Thepseudocodewepresentis

particularlyusefulfordevelopingalgorithmsthatwillbe

convertedtostructuredportionsofC#applications.Pseudocode

issimilartoeverydayEnglishitisconvenientanduserfriendly,

butitisnotanactualcomputerprogramminglanguage.

Pseudocodedoesnotexecuteoncomputers.Rather,ithelps

you"thinkout"anapplicationbeforeattemptingtowriteitina

programminglanguage,suchasC#.Thischapterprovides

severalexamplesofhowtousepseudocodetodevelopC#

applications.

Thestyleofpseudocodewepresentconsistspurelyof

characters,soyoucancreatepseudocodeusinganytext-editor

application.Acarefullypreparedpseudocodeapplicationcan

easilybeconvertedtoacorrespondingC#application.Inmany

cases,thissimplyrequiresreplacingpseudocodestatements

withC#equivalents.

Pseudocodenormallydescribesonlystatementsrepresenting

theactionsthatoccurafteryouconvertanapplicationfrom

pseudocodetoC#andtheapplicationisrunonacomputer.

Suchactionsmightincludeinput,outputandcalculations.We

typicallydonotincludevariabledeclarationsinourpseudocode,

butsomeprogrammersdolistvariablesandmentiontheir

purposesatthebeginningofpseudocodeprograms.







[Page173(continued)]



5.4.ControlStructures

Normally,statementsinanapplicationareexecutedoneafter

theotherintheorderinwhichtheyarewritten.Thisprocessis

calledsequentialexecution.VariousC#statements,which

wewillsoondiscuss,enableyoutospecifythatthenext

statementtoexecuteisnotnecessarilythenextonein

sequence.Thisiscalledtransferofcontrol.

Duringthe1960s,itbecameclearthattheindiscriminateuseof

transfersofcontrolwastherootofmuchdifficultyexperienced

bysoftwaredevelopmentgroups.Theblamewaspointedatthe

gotostatement(usedinmostprogramminglanguagesofthe

time),whichallowsprogrammerstospecifyatransferofcontrol

tooneofaverywiderangeofpossibledestinationsinan

application(creatingwhatisoftencalled"spaghetticode").The

notionofso-calledstructuredprogrammingbecamealmost

synonymouswith"gotoelimination."Werecommendthatyou

avoidC#'sgotostatement.

TheresearchofBohmandJacopini[1]haddemonstratedthat

applicationscouldbewrittenwithoutgotostatements.The

challengeoftheeraforprogrammerswastoshifttheirstylesto

"goto-lessprogramming."Notuntilthe1970sdidprogrammers

starttakingstructuredprogrammingseriously.Theresultswere

impressive.Softwaredevelopmentgroupsreportedshorter

developmenttimes,morefrequenton-timedeliveryofsystems

andmorefrequentwithin-budgetcompletionofsoftware

projects.Thekeytothesesuccesseswasthatstructured

applicationswereclearer,easiertodebugandmodify,andmore

likelytobebugfreeinthefirstplace.

[1]Bohm,C.,andG.Jacopini,"FlowDiagrams,TuringMachines,andLanguageswithOnlyTwoFormation

Rules,"CommunicationsoftheACM,Vol.9,No.5,May1966,pp.336371.



[Page174]

BohmandJacopini'sworkdemonstratedthatallapplications

couldbewrittenintermsofonlythreecontrolstructuresthe

sequencestructure,theselectionstructureandthe

repetitionstructure.Theterm"controlstructures"comes

fromthefieldofcomputerscience.WhenweintroduceC#'s

implementationsofcontrolstructures,wewillrefertothemin

theterminologyoftheC#LanguageSpecificationas"control

statements."



SequenceStructureinC#

ThesequencestructureisbuiltintoC#.Unlessdirected

otherwise,thecomputerexecutesC#statementsoneafterthe

otherintheorderinwhichtheyarewrittenthatis,insequence.

TheUMLactivitydiagraminFig.5.1illustratesatypical

sequencestructureinwhichtwocalculationsareperformedin

order.C#letsyouhaveasmanyactionsasyouwantina

sequencestructure.Asyouwillsoonsee,anywhereasingle

actionmaybeplaced,youmayplaceseveralactionsin

sequence.



Figure5.1.Sequencestructureactivitydiagram.



[Viewfullsizeimage]



Anactivitydiagrammodelstheworkflow(alsocalledthe

activity)ofaportionofasoftwaresystem.Suchworkflows

mayincludeaportionofanalgorithm,suchasthesequence

structureinFig.5.1.Activitydiagramsarecomposedofspecialpurposesymbols,suchasaction-statesymbols(rectangles

withtheirleftandrightsidesreplacedwitharcscurving

outward),diamondsandsmallcircles.Thesesymbolsare

connectedbytransitionarrows,whichrepresenttheflowof

theactivitythatis,theorderinwhichtheactionsshouldoccur.

Likepseudocode,activitydiagramshelpyoudevelopand

representalgorithms,althoughmanyprogrammersprefer

pseudocode.Activitydiagramsclearlyshowhowcontrol

structuresoperate.

ConsidertheactivitydiagramforthesequencestructureinFig.

5.1.Itcontainstwoactionstatesthatrepresentactionsto

perform.Eachactionstatecontainsanactionexpressionfor

example,"addgradetototal"or"add1tocounter"that

specifiesaparticularactiontoperform.Otheractionsmight

includecalculationsorinput/outputoperations.Thearrowsin

theactivitydiagramrepresenttransitions,whichindicatethe

orderinwhichtheactionsrepresentedbytheactionstates

occur.Theportionoftheapplicationthatimplementsthe

activitiesillustratedbythediagraminFig.5.1firstaddsgradeto

total,thenadds1tocounter.



[Page175]

Thesolidcirclelocatedatthetopoftheactivitydiagram

representstheactivity'sinitialstatethebeginningofthe

workflowbeforetheapplicationperformsthemodeledactions.

Thesolidcirclesurroundedbyahollowcirclethatappears

atthebottomofthediagramrepresentsthefinalstatetheend

oftheworkflowaftertheapplicationperformsitsactions.



Figure5.1alsoincludesrectangleswiththeupper-rightcorners

foldedover.TheseareUMLnotes(likecommentsin

C#)explanatoryremarksthatdescribethepurposeofsymbols

inthediagram.Figure5.1usesUMLnotestoshowtheC#code

associatedwitheachactionstateintheactivitydiagram.A

dottedlineconnectseachnotewiththeelementthatthenote

describes.ActivitydiagramsnormallydonotshowtheC#code

thatimplementstheactivity.Weusenotesforthispurposehere

toillustratehowthediagramrelatestoC#code.Formore

informationontheUML,seeouroptionalcasestudy,which

appearsintheSoftwareEngineeringCaseStudysectionsatthe

endsofChapters1,39and11,andvisitwww.uml.org.



SelectionStructuresinC#

C#hasthreetypesofselectionstructures,whichfromthis

pointforward,weshallrefertoasselectionstatements.

ThesearediscussedinthischapterandChapter6.Theif

statementeitherperforms(selects)anactionifaconditionis

trueorskipstheactioniftheconditionisfalse.Theif...else

statementperformsanactionifaconditionistrueorperforms

adifferentactioniftheconditionisfalse.Theswitchstatement

(Chapter6)performsoneofmanydifferentactions,depending

onthevalueofanexpression.

Theifstatementiscalledasingle-selectionstatement

becauseitselectsorignoresasingleaction(or,aswewillsoon

see,asinglegroupofactions).Theif...elsestatementiscalled

adouble-selectionstatementbecauseitselectsbetweentwo

differentactions(orgroupsofactions).Theswitchstatementis

calledamultiple-selectionstatementbecauseitselects

amongmanydifferentactions(orgroupsofactions).



RepetitionStructuresinC#



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

Chapter 5. Control Statements: Part 1

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

×