4.1 While Statements
In cooking, a recipe may tell us that, as long as there are lumps in a sauce, we should stir it. We can make these instructions more Processing-like by writing them in the form:
while (there are lumps)
give sauce a stir;
The idea here is that we repeatedly check for lumps and, if we find any, stir the sauce to try to get rid of them.
We can illustrate this process as we did with an ifstatement, by using a flow chart. Here is a flow chart for our cooking process. Perhaps you can see from the diagram why we call this structure a loop. As long as there is lumpiness, we follow the path that carries us to stirring and then back to testing for lumps.
The general form of Processing's while statement follows the same pattern as the Processing-like form we used for our cooking analogy:
while (<boolean expression>)
<statement>
Execution of a while statement is similar to execution of an if statement that has no else clause. The <boolean expression> (which must be inside parentheses) is evaluated and, if it is false, then control passes to the statement after the while. If, on the other hand, the <boolean expression> is true, then the <statement>, known as the body of the loop, is executed once. Unlike the if statement, the while statement repeats the process. The <boolean expression> is evaluated again and, if it is still true, the <statement> is executed one more time. This is repeated until the <boolean expression> is false, at which time control passes to the statement after the while.
A flow chart for a general while statement can be used to illustrate
this process.
The next example shows the use of a while statement in a complete
program.
Example 1
The following program reads integers and prints them along with their squares. It continues to read and print until the user provides a value of zero.
void setup()
{
int value = getInt("Give an integer (zero to stop)");
while(value != 0)
{
println(value + " " + value*value);
value = getInt("Next integer (zero to stop)");
}
}
|
|
There are a number of points that we should note in the use of a while statement in this program.
-
The statement int value = getInt("Give an integer (zero to stop)"); that precedes the while statement is necessary to initialize the variable value before the loop is entered for the first time. Without this initialization, value would be undefined the first time that the while statement was encountered and an error would occur. This pattern of initialization followed by a loop is one that we will see many times.
-
By using a compound statement with brace brackets, we can have more than one statement in the body of the loop, exactly as we did with if statements.
-
Because the statement(s) within the body of the loop will be executed repeatedly as long as the condition that controls the loop is true, there must be some action within the loop that will eventually cause the condition to become false. In the example this is accomplished by reading a value of zero. We say that zero acts as a sentinel to halt the loop.
-
If the boolean expression that controls the loop is false the first time that the while statement is encountered, then the statement(s) inside the loop will never be performed. Control will pass directly to the statement following the while. In the example, this would occur if the first value that a user entered were zero, the sentinel value.
-
If the expression that controls the loop is never changed to false, then the program will get stuck in the while, executing it for as long as the program is allowed to run. If this happens (and it will happen to you, sooner or later), we say that the program is caught in an infinite loop. The technique for stopping a program caught in an infinite loop varies from system to system. There is usually some combination of keys that will do the trick; your system supervisor should be able to tell you what to do.
-
If a statement in a while loop changes the boolean expression that controls the loop to false, the program does not immediately proceed to the statement following the loop. Once a program has entered the body of a while loop, the entire sequence of statements in the body of the loop is executed and only then is the boolean expression re-evaluated to see if the loop should be entered again.
-
Once the loop has been exited, the boolean expression that controls it must be false. (Otherwise we would never have left the loop.)
In many applications we want to find the total amount of some quantity. Loops enable us to do this easily and efficiently.
Example 2
The following program uses a loop to sum a set of values and find their average.
void setup()
{
/* This program reads the marks obtained for a */
/* student on an exam and finds the average mark. */
/* It prints the average mark, rounded to the */
/* nearest integer. */
int totalMarks = 0;
int numberOfMarks = 0;
int nextMark = getInt("Submit marks (value < 0 to stop");
while (nextMark >= 0)
{
totalMarks += nextMark;
numberOfMarks++;
nextMark = getInt("Next mark:");
}
if (numberOfMarks > 0)
{
int average = round((float)totalMarks/numberOfMarks);
println("Average for "+ numberOfMarks + " students is " + average);
}
} |
|
In this program, the initialization includes both setting the variables totalMarks and numberOfMarks to zero as well as reading the initial value of nextMark. As in the previous example, the statement
nextMark = getInt("Next mark:");
is repeated inside the loop to read subsequent values. In this way, the program will eventually read a sentinel value (here, any negative number) and conclude by finding the average. Notice also that the program only finds the average if there has been at least one mark entered; if only a sentinel was supplied, the program does not attempt to calculate an average.
Exercise 4.1
- What is the minimum number of times that the body of a while
statement can be executed?
-
What is the maximum number of times that the body of a while
statement can be executed?
-
What will be printed by this fragment?
int m = 10;
int n = 0;
while (m > n)
{
println(m + " " + n);
m--;
n += 2;
}
-
Write a program that reads a positive integer and then finds the smallest power of two that is greater than or equal to the number that was read. For example, if the program reads the value 25, it should note that 32 = 25 is the smallest power of two greater than or equal to 25.
-
Write a program that prompts the user for a sequence of integers, using zero as a sentinel. The program should count the number of times that consecutive values are equal. For example, if the input is
3 6 7 7 4 4 4 6 0
then the program should determine that there are three cases in which consecutive values are equal.
| |