Tải bản đầy đủ - 0 (trang)
Chapter 6. Functions and an Introduction to Recursion

Chapter 6. Functions and an Introduction to Recursion

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

Chapter6.FunctionsandanIntroduction

toRecursion

Formeverfollowsfunction.

LouisHenriSullivan

Epluribusunum.(Onecomposedofmany.)

Virgil

O!callbackyesterday,bidtimereturn.

WilliamShakespeare

CallmeIshmael.

HermanMelville

Whenyoucallmethat,smile!

OwenWister

Answermeinoneword.

WilliamShakespeare

Thereisapointatwhichmethodsdevour

themselves.

FrantzFanon

Lifecanonlybeunderstoodbackwards;butitmust

belivedforwards.



SorenKierkegaard

OBJECTIVES

Inthischapteryouwilllearn:

Toconstructprogramsmodularlyfromfunctions.

TousecommonmathfunctionsavailableintheC++

StandardLibrary.

Tocreatefunctionswithmultipleparameters.

Themechanismsforpassinginformationbetweenfunctions

andreturningresults.

Howthefunctioncall/returnmechanismissupportedbythe

functioncallstackandactivationrecords.

Touserandomnumbergenerationtoimplementgameplayingapplications.

Howthevisibilityofidentifiersislimitedtospecificregions

ofprograms.

Towriteanduserecursivefunctions,i.e.,functionsthatcall

themselves.



[Page239]

Outline

6.1Introduction

6.2ProgramComponentsinC++



6.3MathLibraryFunctions

6.4FunctionDefinitionswithMultipleParameters

6.5FunctionPrototypesandArgumentCoercion

6.6C++StandardLibraryHeaderFiles

6.7CaseStudy:RandomNumberGeneration

6.8CaseStudy:GameofChanceandIntroducingenum

6.9StorageClasses

6.10ScopeRules

6.11FunctionCallStackandActivationRecords

6.12FunctionswithEmptyParameterLists

6.13InlineFunctions

6.14ReferencesandReferenceParameters

6.15DefaultArguments

6.16UnaryScopeResolutionOperator

6.17FunctionOverloading

6.18FunctionTemplates

6.19Recursion

6.20ExampleUsingRecursion:FibonacciSeries

6.21Recursionvs.Iteration

6.22(Optional)SoftwareEngineeringCaseStudy:Identifying

ClassOperationsintheATMSystem



6.23Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page239(continued)]



6.1.Introduction

Mostcomputerprogramsthatsolvereal-worldproblemsare

muchlargerthantheprogramspresentedinthefirstfew

chaptersofthisbook.Experiencehasshownthatthebestway

todevelopandmaintainalargeprogramistoconstructitfrom

small,simplepieces,orcomponents.Thistechniqueiscalled

divideandconquer.Weintroducedfunctions(asprogram

pieces)inChapter3.Inthischapter,westudyfunctionsinmore

depth.Weemphasizehowtodeclareandusefunctionsto

facilitatethedesign,implementation,operationand

maintenanceoflargeprograms.

WewilloverviewaportionoftheC++StandardLibrary'smath

functions,showingseveralthatrequiremorethanone

parameter.Next,youwilllearnhowtodeclareafunctionwith

morethanoneparameter.Wewillalsopresentadditional

informationaboutfunctionprototypesandhowthecompiler

usesthemtoconvertthetypeofanargumentinafunctioncall

tothetypespecifiedinafunction'sparameterlist,ifnecessary.

Next,we'lltakeabriefdiversionintosimulationtechniqueswith

randomnumbergenerationanddevelopaversionofthecasino

dicegamecalledcrapsthatusesmostoftheprogramming

techniquesyouhavelearnedtothispointinthebook.



[Page240]

WethenpresentC++'sstorageclassesandscoperules.These

determinetheperiodduringwhichanobjectexistsinmemory

andwhereitsidentifiercanbereferencedinaprogram.Youwill

alsolearnhowC++isabletokeeptrackofwhichfunctionis

currentlyexecuting,howparametersandotherlocalvariables

offunctionsaremaintainedinmemoryandhowafunction



knowswheretoreturnafteritcompletesexecution.Wediscuss

twotopicsthathelpimproveprogramperformanceinline

functionsthatcaneliminatetheoverheadofafunctioncalland

referenceparametersthatcanbeusedtopasslargedataitems

tofunctionsefficiently.

Manyoftheapplicationsyoudevelopwillhavemorethanone

functionofthesamename.Thistechnique,calledfunction

overloading,isusedbyprogrammerstoimplementfunctions

thatperformsimilartasksforargumentsofdifferenttypesor

possiblyfordifferentnumbersofarguments.Weconsider

functiontemplatesamechanismfordefiningafamilyof

overloadedfunctions.Thechapterconcludeswithadiscussion

offunctionsthatcallthemselves,eitherdirectly,orindirectly

(throughanotherfunction)atopiccalledrecursionthatis

discussedatlengthinupper-levelcomputersciencecourses.







[Page240(continued)]



6.2.ProgramComponentsinC++

C++programsaretypicallywrittenbycombiningnewfunctions

andclassestheprogrammerwriteswith"prepackaged"

functionsandclassesavailableintheC++StandardLibrary.In

thischapter,weconcentrateonfunctions.

TheC++StandardLibraryprovidesarichcollectionoffunctions

forperformingcommonmathematicalcalculations,string

manipulations,charactermanipulations,input/output,error

checkingandmanyotherusefuloperations.Thismakesthe

programmer'sjobeasier,becausethesefunctionsprovidemany

ofthecapabilitiesprogrammersneed.TheC++Standard

LibraryfunctionsareprovidedaspartoftheC++programming

environment.



SoftwareEngineeringObservation6.1

Readthedocumentationforyourcompilertofamiliarize

yourselfwiththefunctionsandclassesintheC++

StandardLibrary.



Functions(calledmethodsorproceduresinother

programminglanguages)allowtheprogrammertomodularizea

programbyseparatingitstasksintoself-containedunits.You

haveusedfunctionsineveryprogramyouhavewritten.These

functionsaresometimesreferredtoasuser-defined

functionsorprogrammer-definedfunctions.The

statementsinthefunctionbodiesarewrittenonlyonce,are

reusedfromperhapsseverallocationsinaprogramandare



hiddenfromotherfunctions.

Thereareseveralmotivationsformodularizingaprogramwith

functions.Oneisthedivide-and-conquerapproach,which

makesprogramdevelopmentmoremanageablebyconstructing

programsfromsmall,simplepieces.Anotherissoftware

reusabilityusingexistingfunctionsasbuildingblockstocreate

newprograms.Forexample,inearlierprograms,wedidnot

havetodefinehowtoreadalineoftextfromthekeyboardC++

providesthiscapabilityviathegetlinefunctionofthe

headerfile.Athirdmotivationistoavoidrepeatingcode.Also,

dividingaprogramintomeaningfulfunctionsmakesthe

programeasiertodebugandmaintain.



[Page241]

SoftwareEngineeringObservation6.2

Topromotesoftwarereusability,everyfunctionshouldbe

limitedtoperformingasingle,well-definedtask,andthe

nameofthefunctionshouldexpressthattaskeffectively.

Suchfunctionsmakeprogramseasiertowrite,test,

debugandmaintain.



Error-PreventionTip6.1

Asmallfunctionthatperformsonetaskiseasiertotest

anddebugthanalargerfunctionthatperformsmany

tasks.



SoftwareEngineeringObservation6.3

Ifyoucannotchooseaconcisenamethatexpressesa

function'stask,yourfunctionmightbeattemptingto

performtoomanydiversetasks.Itisusuallybestto

breaksuchafunctionintoseveralsmallerfunctions.



Asyouknow,afunctionisinvokedbyafunctioncall,andwhen

thecalledfunctioncompletesitstask,iteitherreturnsaresult

orsimplyreturnscontroltothecaller.Ananalogytothis

programstructureisthehierarchicalformofmanagement

(Figure6.1).Aboss(similartothecallingfunction)asksa

worker(similartothecalledfunction)toperformataskand

reportback(i.e.,return)theresultsaftercompletingthetask.

Thebossfunctiondoesnotknowhowtheworkerfunction

performsitsdesignatedtasks.Theworkermayalsocallother

workerfunctions,unbeknownsttotheboss.Thishidingof

implementationdetailspromotesgoodsoftwareengineering.

Figure6.1showsthebossfunctioncommunicatingwithseveral

workerfunctionsinahierarchicalmanner.Thebossfunction

dividestheresponsibilitiesamongthevariousworkerfunctions.

Notethatworker1actsasa"bossfunction"toworker4andworker5.



Figure6.1.Hierarchicalbossfunction/worker

functionrelationship.



[Viewfullsizeimage]







[Page241(continued)]



6.3.MathLibraryFunctions

Asyouknow,aclasscanprovidememberfunctionsthat

performtheservicesoftheclass.Forexample,inChapters35,

youhavecalledthememberfunctionsofvariousversionsofa

GradeBookobjecttodisplaytheGradeBook'swelcomemessage,to

setitscoursename,toobtainasetofgradesandtocalculate

theaverageofthosegrades.

Sometimesfunctionsarenotmembersofaclass.Such

functionsarecalledglobalfunctions.Likeaclass'smember

functions,thefunctionprototypesforglobalfunctionsare

placedinheaderfiles,sothattheglobalfunctionscanbe

reusedinanyprogramthatincludestheheaderfileandthat

canlinktothefunction'sobjectcode.Forexample,recallthat

weusedfunctionpowoftheheaderfiletoraiseavalueto

apowerinFigure5.6.Weintroducevariousfunctionsfromthe

headerfileheretopresenttheconceptofglobal

functionsthatdonotbelongtoaparticularclass.Inthis

chapterandinsubsequentchapters,weuseacombinationof

globalfunctions(suchasmain)andclasseswithmember

functionstoimplementourexampleprograms.



[Page242]

Theheaderfileprovidesacollectionoffunctionsthat

enableyoutoperformcommonmathematicalcalculations.For

example,youcancalculatethesquarerootof900.0withthe

functioncall

sqrt(900.0)



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

Chapter 6. Functions and an Introduction to Recursion

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

×