9Java Recursion-WPS Office
9Java Recursion-WPS Office
aRecur
sion
I
nthi
stut
ori
al,
youwi
l
llear
naboutJav
arecur
siv
efunct
ion,
itsadv
ant
agesanddi
sadv
ant
ages.
I
nJava,amet
hodt
hatcal
l
sit
sel
fisknownasar
ecur
siv
emet
hod.And,
thi
spr
ocessi
sknownas
r
ecur
sion.
Aphysi
calwor
ldexampl
ewouldbetoplacetwopar
all
elmi
rr
orsf
aci
ngeachot
her
.Anyobj
ecti
n
bet
weenthem woul
dberef
lect
edr
ecursiv
ely
.
HowRecur
sionwor
ks?
Af
unct
ioni
scal
l
ingi
tsel
f
Wor
kingofJav
aRecur
sion
I
ntheabov eexample,wehav ecal
l
edt
herecurse(
)methodfr
om i
nsidet
hemainmet
hod.
(
normal methodcall
).And,i
nsidet
her
ecur
se()method,wear
eagaincal
li
ngt
hesamerecur
se
method.Thisisarecursi
vecall
.
I
nor dertostopt
herecur
siv
ecall
,weneedtoprov
idesomecondi
ti
onsi
nsi
det
hemet
hod.
Otherwise,
themethodwil
lbecal
ledi
nfi
nit
ely
.
Hence,
weusethei
f.
..
elsest
atement(
orsi
mil
arappr
oach)t
oter
minat
ether
ecur
siv
ecal
li
nsi
de
t
hemet hod.
Exampl
e:Fact
ori
alofaNumberUsi
ngRecur
sion
cl
assFact
ori
al{
st
ati
cintf
act
ori
al(i
ntn){
i
f(n!
=0)/
/ter
minat
ioncondi
ti
on
r
etur
nn*f
act
ori
al(
n-1)
;//r
ecur
siv
ecal
l
el
se
r
etur
n1;
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){
i
ntnumber=4,
resul
t;
r
esul
t=f
act
ori
al(
number
);
Sy
stem.
out
.pr
int
ln(
number+"f
act
ori
al="+r
esul
t)
;
RunCode
Out
put
:
4f
act
ori
al=24
I
ntheabov
eexample,wehav
eamethodnamedfact
ori
al()
.Thef
act
ori
al(
)iscal
l
edf
rom t
he
mai
n()met
hod.wi
ththenumberv
ari
abl
epassedasanargument
.
Her
e,not
icet
hest
atement
,
r
etur
nn*f
act
ori
al(
n-1)
;
Thefact
orial
()methodi
scalli
ngit
self
.Ini
ti
all
y,thev
alueofnis4insi
defact
ori
al(
).Dur
ingthe
nextr
ecursiv
ecall
,3ispassedtothefact
ori
al()method.Thi
spr
ocessconti
nuesunti
lnisequal
to0.
Whennisequalt
o0,thei
fstat
ementr
etur
nsf
alsehence1i
sret
urned.Fi
nal
l
y,t
heaccumul
ated
r
esul
tispassedt
othemain(
)method.
Wor
kingofFact
ori
alPr
ogr
am
Theimagebel
owwi
l
lgi
vey
ouabet
teri
deaofhowt
hef
act
ori
alpr
ogr
am i
sexecut
edusi
ng
recur
sion.
Fi
ndi
ngt
hef
act
ori
alofanumberusi
ngr
ecur
sion
Fact
ori
alPr
ogr
am usi
ngRecur
sion
Adv
ant
agesandDi
sadv
ant
agesofRecur
sion
Whenar ecursi
vecalli
smade,newstoragelocat
ionsforvari
abl
esar
eall
ocatedonthestack.As,
eachrecur
sivecallr
etur
ns,
theoldv
ariablesandparametersarer
emovedfr
om thestack.Hence,
recur
siongeneral
l
yusesmor ememoryandi sgeneral
lysl
ow.
Ont
heotherhand,
arecur
siv
esol
uti
oni
smuchsi
mpl
erandt
akesl
esst
imet
owr
it
e,debugand
mai
ntai
n.
RecommendedReadi
ng:
Whatar
etheadv
ant
agesanddi
sadv
ant
agesofr
ecur
sion?