// SumFromOneToN.java class SumFromOneToN { public static void main(String[] args) { // describe the program System.out.println("This program demonstrates using a 'for' loop"); System.out.println("to count from 1 to n."); // declare three integer variables int n, sum, counter; // loop forever while (true) { // read in a value for n System.out.println(); System.out.print("Enter an integer value [or <=0 to exit]: "); n = readInt(); // if the user entered a non-positive number, exit the program if (n <= 0) { System.exit(0); } // start with the sum set to 0 sum = 0; // use a "for" loop to count from 1 to n for (counter=1; counter<=n; counter++) { sum = sum + counter; } // report the sum System.out.print("The sum from 1 to "); System.out.print(n); System.out.print(" = "); System.out.println(sum); } } /////////////////////////////////// // readString, readInt, readDouble /////////////////////////////////// public static String readString() { java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in); java.io.BufferedReader d = new java.io.BufferedReader(isr); try { return d.readLine(); } catch (Exception e) { return "error"; } } public static int readInt() { return Integer.parseInt(readString()); } public static double readDouble() { return Double.valueOf(readString()).doubleValue(); } }