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

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.

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

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


// Note: GREATER-than-or-equal operator
//       SUBTRACTION of the decrement value

int count =  ;

int decrement =  ;

while ( count >= 0 )  
{
  System.out.println( "count is:" + count );
  count = count - decrement;
}

System.out.println( "Count was " + count 
    + " when it failed the test");
     

Puzzles:

Find an initial value for count and a value for decrement so that:

1. the loop body is only executed once.

2. the loop body is executed exactly twice.

3. the loop body is not executed at all.

4. the loop goes on forever.

5. the loop body prints only "6" .


QUESTION 7:

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


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