1.代码:
package yrx;
public class Recursion {
/**
*********************
* Sum to N. No loop, however a stack is used.(运用了栈)
*
* @param paraN The given value.
* @return The sum.
*********************
*/
public static int sumToN(int paraN) {// 递归
if (paraN <= 0) {// N不合法或N等于0时(返回的第一个数)
// Basis.
return 0;
} // Of if
return sumToN(paraN - 1) + paraN;
}// Of sumToN
/**
*********************
* Fibonacci sequence.
*
* @param paraN The given value.
* @return The sum.
*********************
*/
public static int fibonacci(int paraN) {
if (paraN <= 0) {
// Negative values are invalid. Index 0 corresponds to the first element 0.
return 0;
}
if (paraN == 1) {
// Basis.
return 1;
} // Of if
return fibonacci(paraN - 1) + fibonacci(paraN - 2);
}// Of fibonacci
/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
int tempValue = 5;
System.out.println("0 sum to " + tempValue + " = " + sumToN(tempValue));
tempValue = -1;
System.out.println("0 sum to " + tempValue + " = " + sumToN(tempValue));
for (int i = 0; i < 10; i++) {
System.out.println("Fibonacci " + i + ": " + fibonacci(i));
} // Of for i
}// Of main
}
2.运行结果:
3.注意 :
递归的重点是找到出口,将复杂的事情转化为简单的形式,并且用一个栈来保存前面循环的数据信息,最里层的循环处于栈顶。