Java:递归-While Loop Vs If Loop [英] Java : Recursion -While Loop Vs If Loop
本文介绍了Java:递归-While Loop Vs If Loop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码设计1:完美运行
public static void main (String[] args)
{
recursion(2);
}
public static void recursion(int num)
{
if (num > 0)
{
recursion( num - 1 );
System.out.println(num);
}
}
代码设计2:无限循环。 ?
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。首先如果
非循环,我们只有用于
循环, for-each
, while
循环和 do-while
循环。
1. First of all if
is Not a Loop, we only have for
loop, for-each
, while
loop and do-while
loop.
2。第二个代码进入无限循环的原因是,从不递减值 num
。
2. The reason for the 2nd code to go in for a Infinite loop is that, you are never decrementing the value of num
.
这样做....
while (num > 0)
{
recursion( num - 1 );
System.out.println(num);
num = num - 1; // Decrementing the value of num by 1
}
这篇关于Java:递归-While Loop Vs If Loop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文