Skip to main content
Engineering LibreTexts

15.1: The while Statement

  • Page ID
    15249
  • Using a while statement, we can rewrite countdown like this:

    public static void countdown(int n) {
        while (n > 0) {
            System.out.println(n);
            n = n - 1;
        }
        System.out.println("Blastoff!");
    }
    

    You can almost read the while statement like English: “While n is greater than zero, print the value of n and then reduce the value of n by 1. When you get to zero, print Blastoff!”

    The expression in parentheses is called the condition. The statements in braces are called the body. The flow of execution for a while statement is:

    1. Evaluate the condition, yielding true or false.
    2. If the condition is false, skip the body and go to the next statement.
    3. If the condition is true, execute the body and go back to step 1.

    This type of flow is called a loop, because the last step loops back around to the first.

    The body of the loop should change the value of one or more variables so that, eventually, the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. An endless source of amusement for computer scientists is the observation that the directions on shampoo, “Lather, rinse, repeat,” are an infinite loop.

    In the case of countdown, we can prove that the loop terminates when n is positive. But in general, it is not so easy to tell whether a loop terminates. For example, this loop continues until n is 1 (which makes the condition false):

    public static void sequence(int n) {
        while (n != 1) {
            System.out.println(n);
            if (n % 2 == 0) { // n is even
                n = n / 2;
            } else { // n is odd
                n = n * 3 + 1;
            }
        }
    }
    

    Each time through the loop, the program displays the value of n and then checks whether it is even or odd. If it is even, the value of n is divided by two. If it is odd, the value is replaced by 3n+1. For example, if the starting value (the argument passed to sequence) is 3, the resulting sequence is 3, 10, 5, 16, 8, 4, 2, 1.

    Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1 and that the program will ever terminate. For some values of n, we can prove that it terminates. For example, if the starting value is a power of two, then the value of n will be even every time through the loop until we get to 1. The previous example ends with such a sequence, starting when n is 16.

    The hard question is whether this program terminates for all values of n. So far, no one has been able to prove it or disprove it! For more information, see https://en.Wikipedia.org/wiki/Collatz_conjecture.

    • Was this article helpful?