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?

A good answer might be:

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.

Decrementing the Loop Control Variable

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:

  1. count is initialized to 2.
  2. The condition, count >= 0 is evaluated, yielding TRUE.
  3. The loop body is executed, printing "count is: 2" and subtracting 1 from count.
    • count is now 1.

  4. The condition, count >= 0 is evaluated, yielding TRUE.
  5. The loop body is executed, printing "count is: 1" and subtracting 1 from count.
    • count is now 0.

  6. The condition, count >= 0 is evaluated, yielding TRUE.
  7. The loop body is executed, printing "count is: 0" and subtracting 1 from count.
    • count is now -1.

  8. The condition, count >= 0 is evaluated, yielding FALSE.
  9. The statement after the loop, is executed, printing "Done counting down."

QUESTION 6:

Is it possible to count down by an amount other than one?