Get startedGet started for free

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.

This exercise is part of the course

Input/Output and Streams in Java

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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)); 
    }
}
Edit and Run Code