#Tracing recursion

1 messages · Page 1 of 1 (latest)

visual shore
#

How do I trace this I get really confused

weary basinBOT
#

<@&987246399047479336> please have a look, thanks.

fleet path
#

pen and paper

#

play "dumb java robot", executing the code step by step by hand

#

its to demystify recursion. to show u that recursion is no magic at all and that java simple executes a method when being told to execute one

visual shore
#

stacking method

#

like how would you do it

wind compass
#

dosomething gets called with 3, so what does it do?

#

0 won't work, so let's say that 1 is the last number that does anything
1 prints just 1 as both calls to dosomething when the argument is 1, turns those into 0, which we just said doesn't do anything

#
dosomething 2
 bigger than 0, yes
 dosomething 1
  bigger than 0, yes
  print 1
 print 2
 dosomething 1
  bigger than 0, yes
  print 1
#

So dosomething 2 has 3 prints

#

first one prints 1, then 2, then 1 again

#

so the output for dosomething 2 is 121

#

Then the output for dosomething 3 is dosomething2 twice, with a 3 in between

#

So the output is 1213121

#

dosomething 4 would be 121312141213121

#

etc

fleet path
#

like, literally

#

dont try to be smart about it

#

just do it and it will be crystal clear

#

doSomething(3) starts. what is the very first thing that happens?

#

whats the first thing in the method

visual shore
#

check condition, n>3

fleet path
#

yes. n is 3. so its true

visual shore
#

doSomething(2)

fleet path
#

it enters the if

#

now it says doSomething(2)

visual shore
#

Yes

fleet path
#

so. java has to call a method

#

that means it has to pause the current method and park it

visual shore
#

OH

#

Ok

#

Now

#

n is 2

fleet path
#

so. now we start doSomething(2)

visual shore
#

2>0 yes

fleet path
#

yes

visual shore
#

doSomething(1)

#

stop everything and call doSomething(1)

fleet path
#

yes. so doSomething(2) needs to be paused now

visual shore
#

1>0 yes

#

doSomething(0), does not enter if

#

now where do i go

fleet path
#

the method is done. so java goes back to who called it and resumes that paused method

#

who called it? it was doSomething(1)

#

so we continue there now

#

where did it pause? inside the if, at that doSomething(0)

#

so whats the next statement

#

to java its just method calls. it doesnt know anything about recursion, its "dumb". it just plays the normal java rules step by step

visual shore
fleet path
#

a method calls a method, pause it.
a method is done, go back to who called it.

#

easy 🙂

#

and now its just continuing with it step by step until ur done