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

Answer:

  1. The initial values must be set up correctly.
  2. The condition in the while loop must be correct.
  3. The change in variable(s) must be done correctly.

Counting Upwards by Two's

A change in one of these parts will change the behavior of the loop. Here is a program fragment that counts upwards by two's:

int count = 0;            // count is initialized
while ( count <= 6 )      // count is tested
{
  System.out.println( "count is:" + count );
  count = count + 2;      // count is increased by 2
}
System.out.println( "Done counting by two's." );      

Here is what the program prints:

count is: 0
count is: 2
count is: 4
count is: 6
Done counting by two's.

Here is what happens, step-by-tedious-step:

  1. count is initialized to 0.
  2. The condition, count <= 6 is evaluated, yielding TRUE.
  3. The loop body is executed, printing "count is: 0" and adding 2 to count.
    • count is now 2.
  4. The condition, count <= 6 is evaluated, yielding TRUE
  5. .
  6. The loop body is executed, printing "count is: 2" and adding 2 to count.
    • count is now 4.
  7. The condition, count <= 6 is evaluated, yielding TRUE.
  8. The loop body is executed, printing "count is: 4" and adding 2 to count.
    • count is now 6.
  9. The condition, count <= 6 is evaluated, yielding TRUE.
  10. The loop body is executed, printing "count is: 6" and adding 2 to count.
    • count is now 8.
  11. The condition, count <= 6 is evaluated, yielding FALSE.
  12. The body of the loop is skipped and the statement after the body is executed.

QUESTION 2:

Make just one change to the loop. Change the initialization to:

int count = 1; 

What does the program print out? (This is a slightly tricky question. Please take time to work out the answer.)