Next: Using methods. Up: Expressions and loops. Previous: Comparisons.


The while statement

Textbook: Section 4.6

A computer needs to be able to do something repeatedly if it's going to be useful. We can do this in Java using the while statement.

Loops

A while statement looks like the following.

while(expression) statement
For example:
while(i * 2 < n) i *= 2;
Say i holds 1 and n holds 23 before the computer reaches this while statement. The computer then does the following steps.
  1. The computer checks whether i*2<n. Yes, it's true that 2<23, so the computer executes ``i *= 2;.'' The value of i is now 2.
  2. The computer checks whether 2*2<23. It's true, so the computer executes ``i *= 2;'' again. The value of i is now 4.
  3. The computer checks whether 4*2<23. It's true; the value of i becomes 8.
  4. The computer checks whether 8*2<23. It's true; the value of i becomes 16.
  5. The computer checks whether 16*2<23. That's false. So the computer is done with the while statement, and it continues to whatever follows.

If we want to repeat a sequence of several statements, you can use braces to combine them. The computer repeatedly checks whether the condition is true and then executes all the statements listed in the braces.

import csbsju.cs160.*;

public class WhileExample {
    public static void run() {
        int i = 1;
        int n = 23;
        while(i * 2 < n) {
            i *= 2;
            IO.println(i);
        }
    }
}
Notice how we indented the body of the while loop! This isn't necessary from the Java compiler's point of view, but it's good form, to keep the program less confusing. We will deduct points if you don't adhere to good form.

In this example, the computer would print the following.

2
4
8
16
Notice that, just before it prints 16, i*2<n is no longer true. But the computer prints the number anyway, since it checks the condition until all the statements (including the call to IO.println()) are done.

Counting loops

One particularly popular loop arrangement is to count. You'll see this sort of thing quite a bit.

int i = 1;
while(i <= 100) {
    System.out.print("Now I'm at ");
    System.out.println(i);
    i += 1;
}
This program counts from 1 to 100.

In fact, counting is so popular that Java provides some convenient abbreviations. One abbreviation is the ++ and -- operators to increment or decrement a variable.

int i = 1;
while(i <= 100) {
    System.out.print("Now I'm at ");
    System.out.println(i);
    i++;   // <-- Note the change to i++ in place of i += 1
}
This is slightly more convenient for those times when you want to do it.


Next: Using methods. Up: Expressions and loops. Previous: Comparisons.