I'm trying to understand how this recursive code works, and I haven't found anything similar to it on the internet.
public void doSomething(int n)
{
if (n > 0)
{
doSomething(n-1);
System.out.println(n);
doSomething(n-1);
}
}
Why is the output 1213121?
It is quite simple.
You call doSomething(3)
-> doSomething(2)
-> doSomething(1)
-> doSomething(0)
-> condition is not met so you return
-> println(1)
-> doSomething(0)
-> condition is not met so you return
.
Now you are at the end of the function doSomething(1)
. println(2)
is called. And you call doSomething(1)
same as before.
When you return from doSomething(2)
, println(3)
is called...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.