// HW08_2a.java // Tim Hilby // Created on April 12, 2006 import java.util.Scanner; public class HW08_2a { // calculates the sum from lo to hi (inclusive) public static int sum(int lo, int hi) { if (lo > hi) { // the range is not valid return 0; } else if (lo == hi) { // trivial base case // (the sum from x to x is x) return lo; } else { // sum of the whole is equal to // the sum of the left plus the right int avg = (lo + hi) / 2; return (sum(lo, avg) + sum(avg + 1, hi)); } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("This program calculates the "); System.out.println("sum of numbers from one to N."); int n; System.out.println("What is N? (type 0 to quit)"); n = scan.nextInt(); while (n != 0) { System.out.println("Answer: " + sum(1, n)); System.out.println("What is N? (type 0 to quit)"); n = scan.nextInt(); } } }