Code Design 1 : works perfectly
public static void main (String[] args)
{
recursion(2);
}
public static void recursion(int num)
{
if (num > 0)
{
recursion( num - 1 );
System.out.println(num);
}
}
Code Design 2 : Infinite Loop. ?
public static void main (String[] args)
{
recursion(2);
}
public static void recursion(int num)
{
if (num == 0) return;
while (num > 0)
{
recursion( num - 1 );
System.out.println(num);
}
}
1. First of all if
is Not a Loop , we only have for
loop, for-each
, while
loop and do-while
loop.
2. The reason for the 2nd code to go in for a Infinite loop is that, you are never decrementing the value of num
.
Do this....
while (num > 0)
{
recursion( num - 1 );
System.out.println(num);
num = num - 1; // Decrementing the value of num by 1
}
输入while循环数大于零且其值不变。
the value
of the num
is not changed after it has been pass in the recursion
method.
if (num == 0) return;
while (num > 0)
{
recursion( num - 1 );
System.out.println(num);
num--; // add this line.
}
The value of num does not change inside the loop. So it keeps looping.
while (num > 0)
{
recursion( num - 1 );
System.out.println(num);
}
in your while loop you are passing 2 for num . 2 is always greater than 0 so it goes to infinite loop;
To avoid infinite loop you have change the value of num variable;
while (num > 0)
{
recursion( num - 1 );
System.out.println(num);
num--;
}
Whether use loop or recursion, not both of them at the same time.
Generally, if one can do his desired actions using loops, he does not consider recursion anymore as using loops are faster and has less overhead.
Back to your question:
1. Infinite loop is inevitable. As in the loop num
is not decreasing.
2. Of course there are some returns, but not from the case where you enter the recursion
with num = 2
and num = 1
.
Here is what happens: You enter the recursion
with num = 2
. It calls recursion
with num = 1
. There, there is infinite loop and of course infinite returns. But there is no return back to recursion(2)
.
The reason is that num is copied by-value, not as a reference in the call to
recursion( num - 1 );
Edit: Yeesh, people are happy to downvote, arent' they? True, reference vs. copy-by value wasn't the correct answer, but in my initial reading of his code example it looked like a misunderstanding of that particular problem. I stand corrected.
I don't know why you are going through all this to do a function like that? I apologize if I'm not getting your question but here is a good code I would suggest..
public static void main(String[] args){
countdown(10);
}
public void countdown(int num){
for(int i = num; i >= 0; i--){
System.out.println(num);
}
}
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.