Decrementing the Loop Control Variable

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Say that during a run of a program, the body of a loop was exectued 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, 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?