How should the assignment statement be completed so that the loop terminates? (include the variable inc in your 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");
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, if the values for count
and inc
came from input data,
you might not have much control over what they will be, and it is important to
understand what your loop will do.
Here is a program fragment that is to count upward by tenths, that is,
0.0, 0.1, 0.2, 0.3, and so on up to 10.0.
These amounts are to be placed in the variable value
.
double value ; int tenths = 0; int inc = ____________ // pick an inc value while ( tenths <= ____________ ) // put in the limit amount { value = ____________ // calculate the current value System.out.println( "value:" + value ); tenths = tenths + inc ; } System.out.println( "done");
This program is an example of a common situation: the actual value you are interested in is not the loop control variable, but a value that is calculated from the loop control variable.