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

Say that during a run of a program, the body of a loop was executed 5 times. How many times was the condition part of the while statement evaluated?

Answer:

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 prints:

count is: 2
count is: 1
count is: 0
Done counting down.

Here is what happens:


  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.
  1. The condition, count >= 0 is evaluated, yielding TRUE.
  2. The loop body is executed, printing "count is: 0" and subtracting 1 from count.
    • count is now -1.
  3. The condition, count >= 0 is evaluated, yielding FALSE.
  4. 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?


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