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 above is an example of a count type of boundary.
Sample problem: In the margin to the left, 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 and then breaking out from the loop. You have already used the break statement for switch statements, and it has a similar use here. Once the loop encounters the break statement, all further checks of the boundary condition are ignored and code execution continues after the end of the while loop. For example, here is a loop that keeps a running total of non-zero integers, terminated by a value of zero.
Scanner in = new Scanner(System.in);
int total = 0;
int number;
while (true){
System.out.print ("Enter a number (0 to quit) --> ");
number = in.nextInt();
if(number == 0){
break;
}else{
total += number;
}
}
System.out.println("Total = " + total);
Notice that because we don’t know how many times we want the loop to run, we simply declare the boundary condition as always true. This means the loop will run until we tell it to stop with the break command.
A similar construct to the break statement is the continue statement. When a loop encounters a continue statement, every statement left to execute in that specific iteration is ignored. The loop will then go back to check its boundary condition like normal. Continue statements can be useful for ignoring special cases (such as if you want to ignore an entry of zero in a loop that may use that number as a divisor).
Last modified: December 12, 2022
Back to The While Loop