Arecursivemethodisamethodthatcallsitselfeitherdirectlyor
indirectly
Therearetwokeyrequirementstomakesurethattherecursionissuccessful:
Everyrecursivecallmustsimplifythecomputationinsomeway.
Theremustbespecialcasestohandlethesimplestcomputations.
[Link]
Ifarecursivemethodiscalledwithabasecase,themethodreturnsaresult.
Ifamethodiscalledwithamorecomplexproblem,themethoddividesthe
problemintotwoormoreconceptualpieces:apiecethatthemethodknows
[Link]
newproblemlooksliketheoriginalproblem,themethodlaunchesarecursive
calltoworkonthesmallerproblem.
Forrecursiontoterminate,eachtimetherecursionmethodcallsitselfwitha
slightlysimplerversionoftheoriginalproblem,thesequenceofsmallerand
[Link]
recognizesthebasecase,theresultisreturnedtothepreviousmethodcall
andasequenceofreturnsensuresallthewayupthelineuntiltheoriginal
callofthemethodeventuallyreturnsthefinalresult.
Bothiterationandrecursionarebasedonacontrolstructure:Iterationuses
arepetitionstructurerecursionusesaselectionstructure.
Bothiterationandrecursioninvolverepetition:Iterationexplicitlyusesa
repetitionstructurerecursionachievesrepetitionthroughrepeatedmethod
calls.
Iterationandrecursioneachinvolveaterminationtest:Iterationterminates
whentheloopcontinuationconditionfailsrecursionterminateswhenabase
caseisrecognized.
Iterationandrecursioncanoccurinfinitely:Aninfiniteloopoccurswith
iterationiftheloopcontinuationtestneverbecomesfalseinfiniterecursion
occursiftherecursionstepdoesnotreducetheprobleminamannerthat
convergesonthebasecase.
Recursionrepeatedlyinvokesthemechanism,andconsequentlythe
overhead,[Link]
memoryspace.