Today's Quiz
The "while" loopToday's quiz was a brief overview of booleans and if statements.
- (5>6) has the boolean value false
- booleans can hold the values true or false
- Given
this will print out World when number1 is less than or equal to number2if(number1 > number2) System.out.println("Hello"); else System.out.println("World"); This will print out Goodnight!, World, End of Question 4. Remember that if statements will automatically assume the next line of code is part of the statement when the brackets are missing, so hello was part of the else statement, while world was not.if(true) System.out.println("Goodnight!"); else System.out.println("Hello"); System.out.println("World"); System.out.println("End of Question 4");
It is often times useful to repeat an operation until certain criteria are met. We see this in the real world every day. As long as you can see dirt, keep vacuming. While the roast is below safe tempurature, keep cooking.We also see this in computer programs. For example, we might continue to read from a file as long as we haven't gotten to the end. Or, we might process user input so long as they don't select "Q" for quit.
Java has a langauge feature for exactly this -- the "while" loop. It is one of Java's three loop constructs. It is, perhaps, the most fundamental loop -- and the first that we'll study. Its syntax is strikingly similar to that of the "if" statement:
while (predicate) { // This body is "gated" by the predicate above. // After it completes, control "loops" back to the evaluation // of the predicate }Consider the following example, which prints number 1, 2, 3, 4, ..., 10.
int number=1; while (number <= 10) { System.out.println (number); number++; // number = number +1; } // For reference, notice number is 11 after the loop. // (11 > 10) broke the loop, so it stopped after reaching 11, but // before re-entering the loop System.out.println (number);
The "do...while" loop
The "while loop" is a "precondition" loop. It checks a predicate before entering the loop the first time, and before entering each time thereafter.Java has a similar loop, called the "do while" loop. It resembles the "while loop", except it checks the predicate after completing the body of the loop. As a result, the loop is guaranteed to run at least once.
Let's reconsider the userinput example from above -- this time as a do-while loop:
import java.io.*; import java.util.*; class FriSep15 { public static void main (String[] args) { Scanner keyboard = new Scanner(System.in); String input; do { System.out.print ("Give it to me: "); input = keyboard.next(); System.out.println ("You typed: " + input); } while (!input.equalsIgnoreCase("Q")); System.out.println ("All done!"); } }The code above is guaranteed to run the do while loop at least once, this way you don't have to have a seperate line of code before asking for an initial input
The for loop
Let's consider the example of the quiz one more time. Take another look at it. Notice that there are really four parts:
- Initialization:
int number=1;- Body (what we want to repeat):
System.out.println(number);- Increment (to set up for next time):
number++;- Predicate (to end the loop):
number<=10This idiom is extremely common in programming. As a result, Java has a special loop construct to support it, the "for loop". The for loop is no more or less powerful than the while loop. In the mathematical sense, it is completely equivalent. But, as a matter of practice, choosing the right loop can make our code much more readable.
Let me introduce the for loop by way of example. Consider the following rewritten version of the loop above:
for (int number=0; number <= 10; number++) { System.out.println (number); }Do you see the relationship between the elements of the for loop and those of the while loop? Below is the general form of the for loop:
for (initialization; predicate; increment) { body }It is perfectly legal for any or all of the initialization, predicate, or increment to be empty. For example, consider the following example of a degenerate form of the for loop, which is exactly equivalent to the while loop:
int number = 10; for ( ; number <= 10; ) { System.out.println (number); number++; }
Choosing the Right Loop
By selecting a for loop, when appropriate, we can make immediately clear to the reader:
- The conditions at the time the loop begins, and
- The condition that cause the loop to end, and
- What moves the loop from beginning to end, and
- What the loop does through each pass
By choosing a while loop, where appropriate, we can make immediately clear to the reader that:
- The initialization isn't a simple state variable, and/or
- The way the state changes isn't necessarily the same each time, and
- The condition that cause the loop to end