#Tracing recursion
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
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
how please
stacking method
like how would you do it
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
as said, just execute the code step by step with pen and paper
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
check condition, n>3
yes. n is 3. so its true
doSomething(2)
Yes
so. java has to call a method
that means it has to pause the current method and park it
so. now we start doSomething(2)
2>0 yes
yes
yes. so doSomething(2) needs to be paused now
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
