[英]How does having 2 recursive statements within the same conditional work?
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
.你调用
doSomething(3)
-> doSomething(2)
-> doSomething(1)
-> doSomething(0)
-> 条件不满足所以你return
-> println(1)
-> doSomething(0)
-> 条件不满足遇见所以你return
。
Now you are at the end of the function doSomething(1)
.现在您处于函数
doSomething(1)
的末尾。 println(2)
is called. println(2)
被调用。 And you call doSomething(1)
same as before.你像以前一样调用
doSomething(1)
。
When you return from doSomething(2)
, println(3)
is called...当你从
doSomething(2)
返回时, println(3)
被调用......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.