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

Chapter 4. Control Statements: Part 1

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

Chapter4.ControlStatements:Part1

Let'sallmoveoneplaceon.

LewisCarroll

Thewheeliscomefullcircle.

WilliamShakespeare

HowmanyapplesfellonNewton'sheadbeforehe

tookthehint!

RobertFrost

Alltheevolutionweknowofproceedsfromthe

vaguetothedefinite.

CharlesSandersPeirce

OBJECTIVES

Inthischapteryouwilllearn:

Basicproblem-solvingtechniques.

Todevelopalgorithmsthroughtheprocessoftop-down,

stepwiserefinement.

Tousetheifandif...elseselectionstatementstochoose

amongalternativeactions.

Tousethewhilerepetitionstatementtoexecutestatements

inaprogramrepeatedly.



Counter-controlledrepetitionandsentinel-controlled

repetition.

Tousetheincrement,decrementandassignmentoperators.



[Page125]

Outline

4.1Introduction

4.2Algorithms

4.3Pseudocode

4.4ControlStructures

4.5ifSelectionStatement

4.6if...elseDouble-SelectionStatement

4.7whileRepetitionStatement

4.8FormulatingAlgorithms:Counter-ControlledRepetition

4.9FormulatingAlgorithms:Sentinel-ControlledRepetition

4.10FormulatingAlgorithms:NestedControlStatements

4.11AssignmentOperators

4.12IncrementandDecrementOperators

4.13(Optional)SoftwareEngineeringCaseStudy:Identifying

ClassAttributesintheATMSystem

4.14Wrap-Up



Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page125(continued)]



4.1.Introduction

Beforewritingaprogramtosolveaproblem,wemusthavea

thoroughunderstandingoftheproblemandacarefullyplanned

approachtosolvingit.Whenwritingaprogram,wemustalso

understandthetypesofbuildingblocksthatareavailableand

employprovenprogramconstructiontechniques.Inthischapter

andinChapter5,ControlStatements:Part2,wediscussthese

issuesinpresentingofthetheoryandprinciplesofstructured

programming.Theconceptspresentedherearecrucialto

buildingeffectiveclassesandmanipulatingobjects.

Inthischapter,weintroduceC++'sif,if...elseandwhile

statements,threeofthebuildingblocksthatallowprogrammers

tospecifythelogicrequiredformemberfunctionstoperform

theirtasks.Wedevoteaportionofthischapter(andChapters5

and7)tofurtherdevelopingtheGradeBookclassintroducedin

Chapter3.Inparticular,weaddamemberfunctiontothe

GradeBookclassthatusescontrolstatementstocalculatethe

averageofasetofstudentgrades.Anotherexample

demonstratesadditionalwaystocombinecontrolstatementsto

solveasimilarproblem.WeintroduceC++'sassignment

operatorsandexploreC++'sincrementanddecrement

operators.Theseadditionaloperatorsabbreviateandsimplify

manyprogramstatements.



[Page125(continued)]



4.2.Algorithms

Anysolvablecomputingproblemcanbesolvedbytheexecution

ofaseriesofactionsinaspecificorder.Aprocedurefor

solvingaproblemintermsof

1. theactionstoexecuteand

2. theorderinwhichtheseactionsexecute

iscalledanalgorithm.Thefollowingexampledemonstrates

thatcorrectlyspecifyingtheorderinwhichtheactionsexecute

isimportant.



[Page126]

Considerthe"rise-and-shinealgorithm"followedbyonejunior

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,ourjuniorexecutiveshowsup

forworksoakingwet.Specifyingtheorderinwhichstatements

(actions)executeinacomputerprogramiscalledprogram

control.ThischapterinvestigatesprogramcontrolusingC++'s

controlstatements.



[Page126(continued)]



4.3.Pseudocode

Pseudocode(or"fake"code)isanartificialandinformal

languagethathelpsprogrammersdevelopalgorithmswithout

havingtoworryaboutthestrictdetailsofC++language

syntax.Thepseudocodewepresenthereisparticularlyuseful

fordevelopingalgorithmsthatwillbeconvertedtostructured

portionsofC++programs.Pseudocodeissimilartoeveryday

English;itisconvenientanduserfriendly,althoughitisnotan

actualcomputerprogramminglanguage.

Pseudocodedoesnotexecuteoncomputers.Rather,ithelpsthe

programmer"thinkout"aprogrambeforeattemptingtowriteit

inaprogramminglanguage,suchasC++.Thischapter

providesseveralexamplesofhowtousepseudocodetodevelop

C++programs.

Thestyleofpseudocodewepresentconsistspurelyof

characters,soprogrammerscantypepseudocodeconveniently,

usinganyeditorprogram.Thecomputercanproduceafreshly

printedcopyofapseudocodeprogramondemand.Acarefully

preparedpseudocodeprogramcaneasilybeconvertedtoa

correspondingC++program.Inmanycases,thissimply

requiresreplacingpseudocodestatementswithC++

equivalents.

Pseudocodenormallydescribesonlyexecutablestatements,

whichcausespecificactionstooccurafteraprogrammer

convertsaprogramfrompseudocodetoC++andtheprogram

isrunonacomputer.Declarations(thatdonothaveinitializers

ordonotinvolveconstructorcalls)arenotexecutable

statements.Forexample,thedeclaration

inti;



tellsthecompilervariablei'stypeandinstructsthecompilerto

reservespaceinmemoryforthevariable.Thisdeclarationdoes

notcauseanyactionsuchasinput,outputoracalculationto

occurwhentheprogramexecutes.Wetypicallydonotinclude

variabledeclarationsinourpseudocode.However,some

programmerschoosetolistvariablesandmentiontheir

purposesatthebeginningofpseudocodeprograms.

Wenowlookatanexampleofpseudocodethatmaybewritten

tohelpaprogrammercreatetheadditionprogramofFig.2.5.

Thispseudocode(Fig.4.1)correspondstothealgorithmthat

inputstwointegersfromtheuser,addstheseintegersand

displaystheirsum.Althoughweshowthecompletepseudocode

listinghere,wewillshowhowtocreatepseudocodefroma

problemstatementlaterinthechapter.

Figure4.1.PseudocodefortheadditionprogramofFig.

2.5.

(Thisitemisdisplayedonpage127intheprintversion)

1Prompttheusertoenterthefirstinteger

2Inputthefirstinteger

3

4Prompttheusertoenterthesecondinteger

5Inputthesecondinteger

6

7Addfirstintegerandsecondinteger,storeresult

8Displayresult



Lines12correspondtothestatementsinlines1314ofFig.2.5.

NoticethatthepseudocodestatementsaresimplyEnglish

statementsthatconveywhattaskistobeperformedinC++.

Likewise,lines45correspondtothestatementsinlines1617of

Fig.2.5andlines78correspondtothestatementsinlines19

and21ofFig.2.5.



[Page127]

ThereareafewimportantaspectsofthepseudocodeinFig.

4.1.Noticethatthepseudocodecorrespondstocodeonlyin

functionmain.Thisoccursbecausepseudocodeisnormallyused

foralgorithms,notcompleteprograms.Inthiscase,the

pseudocodeisusedtorepresentthealgorithm.Thefunctionin

whichthiscodeisplacedisnotimportanttothealgorithmitself.

Forthesamereason,line23ofFig.2.5(thereturnstatement)is

notincludedinthepseudocodethisreturnstatementisplacedat

theendofeverymainfunctionandisnotimportanttothe

algorithm.Finally,lines911ofFig.2.5arenotincludedinthe

pseudocodebecausethesevariabledeclarationsarenot

executablestatements.



[Page127(continued)]



4.4.ControlStructures

Normally,statementsinaprogramexecuteoneaftertheother

intheorderinwhichtheyarewritten.Thisiscalledsequential

execution.VariousC++statementswewillsoondiscuss

enabletheprogrammertospecifythatthenextstatementto

executemaybeotherthanthenextoneinsequence.Thisis

calledtransferofcontrol.

Duringthe1960s,itbecameclearthattheindiscriminateuseof

transfersofcontrolwastherootofmuchdifficultyexperienced

bysoftwaredevelopmentgroups.Thefingerofblamewas

pointedatthegotostatement,whichallowstheprogrammer

tospecifyatransferofcontroltooneofawiderangeof

possibledestinationsinaprogram(creatingwhatisoftencalled

"spaghetticode").Thenotionofso-calledstructured

programmingbecamealmostsynonymouswith"goto

elimination."

TheresearchofBöhmandJacopini[1]demonstratedthat

programscouldbewrittenwithoutanygotostatements.It

becamethechallengeoftheeraforprogrammerstoshifttheir

stylesto"goto-lessprogramming."Itwasnotuntilthe1970s

thatprogrammersstartedtakingstructuredprogramming

seriously.Theresultshavebeenimpressive,assoftware

developmentgroupshavereportedreduceddevelopmenttimes,

morefrequentontimedeliveryofsystemsandmorefrequent

within-budgetcompletionofsoftwareprojects.Thekeytothese

successesisthatstructuredprogramsareclearer,areeasierto

debug,testandmodifyandaremorelikelytobebug-freein

thefirstplace.

[1]Böhm,C.,andG.Jacopini,"FlowDiagrams,TuringMachines,andLanguageswithOnlyTwoFormation

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



BöhmandJacopini'sworkdemonstratedthatallprogramscould

bewrittenintermsofonlythreecontrolstructures,namely,

thesequencestructure,theselectionstructureandthe

repetitionstructure.Theterm"controlstructures"comes

fromthefieldofcomputerscience.WhenweintroduceC++'s

implementationsofcontrolstructures,wewillrefertothemin

theterminologyoftheC++standarddocument[2]as"control

statements."

[2]ThisdocumentismorespecificallyknownasNCITS/ISO/IEC14882-2003ProgramminglanguagesC++and

isavailablefordownload(forafee)at:webstore.ansi.org/ansidocstore/product.asp?

sku=INCITS%2FISO%2FIEC+14882%2D2003.



[Page128]



SequenceStructureinC++

ThesequencestructureisbuiltintoC++.Unlessdirected

otherwise,thecomputerexecutesC++statementsoneafter

theotherintheorderinwhichtheyarewrittenthatis,in

sequence.TheUnifiedModelingLanguage(UML)activity

diagramofFig.4.2illustratesatypicalsequencestructurein

whichtwocalculationsareperformedinorder.C++allowsusto

haveasmanyactionsaswewantinasequencestructure.As

wewillsoonsee,anywhereasingleactionmaybeplaced,we

mayplaceseveralactionsinsequence.



Figure4.2.Sequence-structureactivitydiagram.



[Viewfullsizeimage]



Inthisfigure,thetwostatementsinvolveaddingagradetoa

totalvariableandaddingthevalue1toacountervariable.Such

statementsmightappearinaprogramthattakestheaverage

ofseveralstudentgrades.Tocalculateanaverage,thetotalof

thegradesbeingaveragedisdividedbythenumberofgrades.

Acountervariablewouldbeusedtokeeptrackofthenumber

ofvaluesbeingaveraged.Youwillseesimilarstatementsinthe

programofSection4.8.

ActivitydiagramsarepartoftheUML.Anactivitydiagram

modelstheworkflow(alsocalledtheactivity)ofaportionof

asoftwaresystem.Suchworkflowsmayincludeaportionofan

algorithm,suchasthesequencestructureinFig.4.2.Activity

diagramsarecomposedofspecial-purposesymbols,suchas

actionstatesymbols(arectanglewithitsleftandrightsides

replacedwitharcscurvingoutward),diamondsandsmall

circles;thesesymbolsareconnectedbytransitionarrows,

whichrepresenttheflowoftheactivity.

Likepseudocode,activitydiagramshelpprogrammersdevelop

andrepresentalgorithms,althoughmanyprogrammersprefer

pseudocode.Activitydiagramsclearlyshowhowcontrol

structuresoperate.

Considerthesequence-structureactivitydiagramofFig.4.2.It

containstwoactionstatesthatrepresentactionstoperform.

Eachactionstatecontainsanactionexpressione.g.,"add



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

Chapter 4. Control Statements: Part 1

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

×