How should the assignment statement be completed so that the loop terminates?
int count = 10;
int inc = -1;
while ( count < 100 ) // check the relational operator
{
System.out.println( "count is:" + count );
count = count - inc;
}
System.out.println( "Count was " + count + " when it failed the test");
The above program fragment is logically correct, but poorly written because it is harder to understand (and therefore more error-prone) than the following version that does exactly the same thing:
int count = 10; int inc = 1; while ( count < 100 ) // check the relational operator { System.out.println( "count is:" + count ); count = count + inc; } System.out.println( "Count was " + count + " when it failed the test");
However, you might not have control over the
values for count
and inc
.
The values
might come from input data.
You might need to write a loop that deals with them correctly.
Are you always going to want to change a variable by an integer amount?