// This program has several examples of different kinds of loops. import java.util.*; public class Loops { public static void main(String[] args) { // prints 1, 2, 3, ..., 9, 10 printNumbers(10); simpleWhile(); Scanner console = new Scanner(System.in); sumNumbers(console); } // prints the numbers 1 to max separated by commas public static void printNumbers(int max) { // below is one solution to the fencepost problem that prints the first // number before the loop System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // below is a second solution to the fencepost problem that prints the // final number after the loop /* for (int i = 1; i <= max - 1; i++) { System.out.print(i + ", "); } System.out.println(max); */ } // simple while loop example that doubles a number until it is greater than // 200 public static void simpleWhile() { int number = 1; while (number <= 200) { System.out.print(number + " "); number = number * 2; } System.out.println(number); } // example of a sentinel loop; user is prompted for numbers to sum until // sentinel value of -1 is entered public static void sumNumbers(Scanner console) { int sum = 0; System.out.print("next int (-1 to quit)? "); int number = console.nextInt(); while (number != -1) { sum = sum + number; System.out.print("next int (-1 to quit)? "); number = console.nextInt(); } System.out.println("sum = " + sum); } }