SumIntegers.java

Download
1/*2 * SumIntegers.java3 *4 * Computer Science S-22, Harvard University5 *6 * A class that contains a recursive method for computing the sum of the7 * integers from 1 to n.8 *9 * The main method includes two examples of using this method.10 */11 12public class SumIntegers {13    public static int sum(int n) {14        // base case15        if (n == 0) {16            return 0;17        }18 19        // recursive case20        int total = n + sum(n - 1);    21        return total;   22 23        // Note: we could also have done this:24        //   return n + sum(n - 1);25    }26    27    public static void main(String[] args) {28        int firstSum = sum(3);29        System.out.println("sum(3) = " + firstSum);30        System.out.println("sum(10) = " + sum(10));31    }32}