| |
Loop Boundaries | page 4 of 9 |
The loop boundary is the Boolean expression that evaluates as true or false. We must consider two aspects as we devise the loop boundary:
- It must eventually become false, which allows the loop to exit.
- It must be related to the task of the loop. When the task is done, the loop boundary must become false.
There are a variety of loop boundaries of which two will be discussed in this section.
The first is the idea of attaining a certain count or limit. The code in section A.4 is an example of a count type of bounds.
Sample problem: write a program fragment that prints the even numbers 2-20. Use a while loop.
A second type of boundary construction involves the use of a sentinel value. In this category, the while loop continues until a specific value is entered as input. The loop watches out for this sentinel value, continuing to execute until this special value is input. For example, here is a loop that keeps a running total of positive integers, terminated by a negative value.
int total = 0;
int number = 1; // set to an arbitrary value
//to get inside the loop
while (number >= 0)
{
System.out.print ("Enter a number (-1 to quit) --> ");
number = console.getInt();
if (number >= 0)
total += number;
}
System.out.println("Total = " + total);
- Initialize
number to some positive value.
- The
if (number >= 0) expression is used to avoid adding the sentinel value into the running total.
|