LoslegenKostenlos loslegen

Recursive sum calculation

Recursion is useful for solving problems by breaking them down into smaller subproblems. In this exercise, you will implement a recursive method to compute the sum of numbers from 1 to n.

Diese Übung ist Teil des Kurses

Input/Output and Streams in Java

Kurs anzeigen

Anleitung zur Übung

  • Add the base case, when the input n equals 1.
  • Call the method.
  • Start the first recursive call.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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 calling itself
        return n + ____(n-1); 
    }
    public static void main(String[] args) {
    	// start the recursive call
        System.out.println(____(5)); 
    }
}
Code bearbeiten und ausführen