递归:指方法调用自身
先不使用递归计算 1+2+3+4+5 的和,要求程序设计灵活,如果传入一个 5 过求出 1+2+。。。
+5 的和
不使用递归求和
public class RecursionTest01 {
public static void main(String[] args) {
int retValue = method1(5);
System.out.println(retValue);
}
//给指定的值求和
public static int method1(int n) {
int s = 0;
for (int i=1; i<=n; i++) {
//s=s+i;
s+=i;
}
return s;
}
}
使用递归求和
public class RecursionTest02 {
public static void main(String[] args) {
int retValue = method1(5);
System.out.println(retValue);
}
//采用递归求和
public static int method1(int n) {
if (n == 1) {
return 1;
}else {
//递归调用,调用自身
return n + method1(n-1);
}
}
}