Java Reference
In-Depth Information
The following is an example of an infinite loop:
int count = 1;
while (count <= 25) // Warning: this is an infinite loop!
{
System.out.println (count);
count = count - 1;
}
If you execute this loop, you should be prepared to interrupt it. On most systems,
pressing the Control-C keyboard combination (hold down the Control key and
press C) terminates a running program.
In this example, the initial value of count is 1, and it is decremented in the
loop body. The while loop will continue as long as count is less than or equal to
25 . Because count gets smaller with each iteration, the condition will
always be true, or at least until the value of count gets so small that
an underflow error occurs. The point is that the logic of the code is
clearly wrong.
Let's look at some other examples of infinite loops:
KEY CONCEPT
We must design our programs care-
fully to avoid infinite loops.
int count = 1;
while (count != 50) // infinite loop
count += 2;
In this code fragment, the variable count is initialized to 1 and is moving in a
positive direction. However, note that it is being incremented by 2 each time. This
loop will never terminate because count will never equal 50. It begins at 1 and
then changes to 3, then 5, and so on. Eventually it reaches 49, then changes to 51,
then 53, and continues forever.
Now consider the following situation:
double num = 1.0;
while (num != 0.0) // infinite loop
num = num - 0.1;
Once again, the value of the loop control variable seems to be moving in the
correct direction. And, in fact, it seems like num will eventually take on the
value 0.0 . However, this loop is infinite (at least on most systems), because
num will never have a value exactly equal to 0.0 . This situation is similar to
one we discussed earlier in this chapter when we explored the idea of compar-
ing floating point values in the condition of an if statement. Because of the
way the values are represented in binary, minute computational errors occur
internally, making it problematic to compare two floating point values for
equality.
 
Search WWH ::




Custom Search