4.2 Do Statements

In the last section, we suggested that a while loop was Processing's way of implementing commands of the form "as long as there are lumps in a sauce, we should stir it". If we rearrange this sentence a bit, we can rephrase it as "stir the sauce as long as there are lumps in it". The difference between the two statements is subtle but it is often important. In the first case, we repeatedly check for lumps first and then, if there are any, we stir. In the second case we repeatedly stir and then check for lumps. For these two kinds of repetitive instructions, Processing has two kinds of loops. As we saw in the last section, the while is appropriate for the first kind of situation. To handle the second we have the do statement. The general form of the do statement is:
   do 
      <statement>
   while (<boolean expression>);
To execute a do statement, Processing first executes the <statement> and then evaluates the <boolean expression> which must, as usual, be enclosed by parentheses. If the expression is true, the process is repeated.

A flow chart for a do statement takes the following form.

Since a do statement executes the statement in its body before evaluating the boolean expression that controls the loop, it is useful in situations where we know that we want to perform the loop at least once. Reading input and repeatedly checking to see that it is valid is a common example of this kind of situation, as the next example illustrates.

Example 1

This fragment forces a user to supply a value that lies in the range from one to ten.
   int value;
   do
   {
      value = getInt("Give an integer from one to ten");
   } while (value < 1 || value> 10); 

Notice in the example that the condition that controls the loop is the negation of what we want to happen. We want to get a value from one to ten so we force the user to stay in the loop as long as the user is providing values that are not in this interval.

Exercise 4.2

  1. For what kind of looping situations is a do usually preferable to a while?
  2. What would be written by the program fragment shown below if it were given the following input sequence?
    -5
    0
    26

    do
    {
       howMany = getInt("How many items to add?");
       if (howMany <= 0)
          println("Give a positive value.");
    } while (howMany <= 0); 
  3. Write a fragment that forces a user to supply either y or n in response to the question "Continue? Respond with y or n".
  4. Write a program fragment that asks the user to supply a letter of the alphabet, repeatedly rejecting responses until the user gives either an upper case or a lower case letter of the alphabet.
  5. Write a program that first forces the user to supply a positive integer and then prints the number and the sum of its digits.