Say that during a run of a program,
the body of a loop was exectued 5 times.
How many times was the conditional part of the while
statement
evaluated?
Six times. For the loop body to have executed five times, the condition had to evaluate to true five times. Then the condition was evaluated one more time, this time yielding false.
The loop control variable in a counting loop can be changed by a negative value. Here is a program fragment that decrements the loop control variable at the bottom of each iteration:
int count = 2; // count is initialized while ( count >= 0 ) // count is tested { System.out.println( "count is:" + count ); count = count - 1; // count is changed by -1 } System.out.println( "Done counting down." );
Here is what the program will print:
count is: 2 count is: 1 count is: 0 Done counting down.
Here is what happens, step-by-tedious-step:
count
is initialized to 2.count >= 0
is evaluated, yielding TRUE.count
.
count
is now 1.count >= 0
is evaluated, yielding TRUE.count
.
count
is now 0.count >= 0
is evaluated, yielding TRUE.count
.
count
is now -1.count >= 0
is evaluated, yielding FALSE.Is it possible to count down by an amount other than one?