// This program demonstrates several new concepts, including: // - fencepost loops // - String cumulative "sum" // - while loops import java.util.*; public class LoopPractice { public static void main(String[] args) { printPowers(2, 7); printPowers(10, 5); System.out.println(); printPowers2(2, 7); printPowers2(10, 5); System.out.println(); printPowersUntil(2, 100); printPowersUntil(10, 100000); System.out.println(); Scanner console = new Scanner(System.in); System.out.println(sumAll(console)); } // Print out the first num powers of base // e.g. 2, 7 -> 2, 4, 8, 16, 32, 64, 128 // // int base - the base of the powers to be printed // int num - the number of powers to print public static void printPowers(int base, int num) { // definite loop int power = base; System.out.print(power); for (int i = 2; i <= num; i++) { power *= base; System.out.print(", " + power); } System.out.println(); } // Print out the first num powers of base // e.g. 2, 7 -> 2, 4, 8, 16, 32, 64, 128 // // This alternate version uses the "last post last" approach. // // int base - the base of the powers to be printed // int num - the number of powers to print public static void printPowers2(int base, int num) { // definite loop int power = base; for (int i = 1; i <= num - 1; i++) { System.out.print(power + ", "); power *= base; } System.out.println(power); } // Print out the powers of base up to the first power of base that is // greater than last // e.g. 2, 10 -> 2, 4, 8, 16, 32, 64, 128 // // int base - the base of the powers to be printed // int last - the number after which to stop printing powers public static void printPowersUntil(int base, int last) { // indefinite loop int power = base; System.out.print(power); while (power < last) { System.out.print(", "); power *= base; System.out.print(power); } System.out.println(); } // Read in integers from the user until a -1 is typed, // then return the sum of all numbers typed (not including // the -1). // // Scanner console - the Scanner to use for input public static int sumAll(Scanner console) { int total = 0; System.out.print("Enter an integer (-1 to stop): "); int number = console.nextInt(); while (number != -1) { total += number; System.out.print("Enter an integer (-1 to stop): "); number = console.nextInt(); } return total; } }