開始使用免費開始

遞迴加總計算

遞迴能把問題拆解成更小、較易處理的子問題。在這個練習中,你要實作一個遞迴方法,用來計算從 1n 的總和。

本練習屬於課程

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)); 
    }
}
編輯並執行程式碼