While Loops Loop Patterns
While Loops Loop Patterns
should print:
1, 2, 3, 4, 5
Flawed solutions
public static void printNumbers(int max) {
for (int i = 1; i <= max; i++) {
System.out.print(i + ", ");
}
System.out.println(); // to end the line of output
}
Output from printNumbers(5): 1, 2, 3, 4, 5,
place a post.
for (length of fence - 1) {
place some wire.
place a post.
}
Fencepost method solution
public static void printNumbers(int max) {
System.out.print(1);
for (int i = 2; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
}
reading: 5.1
Categories of loops
definite loop: Executes a known number of times.
The for loops we have seen are definite loops.
Print "hello" 10 times.
Find all the prime numbers up to an integer n.
Print each odd number between 5 and 127.
indefinite loop: One where the number of times its
body repeats is not known in advance.
Prompt the user until they type a non-negative
number.
Print random numbers until a prime number is printed.
Repeat until the user has typed "q" to quit.
The while loop
while loop: Repeatedly executes its
body as long as a logical test is true.
while (<test>) {
<statement(s)>;
}
Example:
int num = 1; // initialization
while (num <= 200) { // test
System.out.print(num + " ");
num = num * 2; // update
}
// output: 1 2 4 8 16 32 64 128
Example while loop
// finds the first factor of 91, other than 1
int n = 91;
int factor = 2;
while (n % factor != 0) {
factor++;
}
System.out.println("First factor is " +
factor);
// output: First factor is 7
while (!response.equals("")) {
System.out.print("Type a line (or nothing to exit): ");
response = console.nextLine();
sum += response.length();
}
while (!response.equals("quit")) {
System.out.print("Type a line (or \"quit\" to exit): ");
response = console.nextLine();
sum += response.length();
}
System.out.println("You typed a total of " + sum + "
characters.");
while (!response.equals("quit")) {
sum += response.length(); // moved to top of loop
System.out.print("Type a line (or \"quit\" to exit):
");
response = console.nextLine();
}
while (!response.equals(SENTINEL)) {
sum += response.length(); // moved to top of loop
System.out.print("Type a line (or \"" + SENTINEL + "\" to exit): ");
response = console.nextLine();
}