ComeçarComece de graça

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.

Este exercício faz parte do curso

Input/Output and Streams in Java

Ver curso

Instruções do exercício

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

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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)); 
    }
}
Editar e executar o código