Live Code!

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

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

Answer:

Sure. The loop control variable could be decremented by any integer amount.

Live Code!

Here is some code that illustrates changing the loop control variable by an amount other than one.


// Note: GREATER-than-or-equal operator
//

count =  ;

decrement =  ;

while ( count >= 0 )  
{
  System.out.println( "count is:" + count );
  count = count - decrement;
}
System.out.println( "Count was " + count 
    + " when it failed the test");
     

(The output window sometimes shows messages that would not be printed by the example code.)


Each iteration of the loop subtracts a positive value (called a decrement) from the loop control variable.

QUESTION 7:

Could you do exactly the same thing by adding a negative value to the loop control variable?