递归求和计算
递归通过把问题拆解成更小、更易处理的子问题来求解。在本练习中,您将实现一个递归方法,用于计算从 1 到 n 的累加和。
本练习是课程的一部分
Java 中的输入/输出与流
练习说明
- 添加基本情况:当输入
n等于1时返回。 - 调用该方法。
- 发起第一次递归调用。
交互式实操练习
通过完成这段示例代码来试试这个练习。
public class SumCalculator {
static int sum(int n) {
// Base case: when n is the last number 1
if (____ ____ ____) return 1;
// Recursive step: add the current sum and call itself
return n + ____(n-1);
}
public static void main(String[] args) {
// start the recursive call
System.out.println(____(5));
}
}