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.
Cet exercice fait partie du cours
Input/Output and Streams in Java
Instructions
- Add the base case, when the input
nequals1. - Call the method.
- Start the first recursive call.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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));
}
}