public class Factorial {
int fact(int n) {
int result;
if (n == 1) {
return 1;
}
result = fact(n - 1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("3的阶乘是 " + f.fact(3));
System.out.println("4的阶乘是 " + f.fact(4));
System.out.println("5的阶乘是 " + f.fact(5));
}
}
该程序产生的输出如下所示:
3的阶乘是 6
4的阶乘是 24
5的阶乘是 120
class RecTest {
int values[];
RecTest(int i) {
values = new int[i];
}
void printArray(int i) {
if (i == 0){
return;
} else {
printArray(i - 1);
}
System.out.println("[" + (i - 1) + "] " + values[i - 1]);
}
}
class Recursion2 {
public static void main(String args[]) {
RecTest ob = new RecTest(10);
int i;
for (i = 0; i < 10; i++) {
ob.values[i] = i;
}
ob.printArray(10);
}
}
该程序产生如下的输出:
[0] 0
[1] 1
[2] 2
[3] 3
[4] 4
[5] 5
[6] 6
[7] 7
[8] 8
[9] 9
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有