count is 13 count is 14 count is 15 count is 16 count is 17 . . . . and so on without end
It is possible (and common!) to accidently create a counting loop that will never end. In the above example, this happened because the variable decrement had the value minus one. So the statement
count = count - decrement;
actually added one to count
.
So count
kept getting larger and larger, never reaching the zero that the
condition part was looking for:
while ( count >= 0 ) // GREATER-than-or-equal operator
Such loops are called infinite loops, or non-terminating loops and are sometimes easy to overlook when you are programming. Here is another program fragment:
int count = 20; int dec = -1; while ( count __________ 10 ) // what relational operator ? { System.out.println( "count is:" + count ); count = count + dec ; } System.out.println( "Count was " + count + " when it failed the test");