go to previous page   go to home page   go to next page hear noise highlighting

How should the assignment statement be completed so that the loop terminates?

Answer:

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");

Better Version

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.


QUESTION 11:

Are you always going to want to change a variable by an integer amount?


go to previous page   go to home page   go to next page