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

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. Here is what the program prints:

count is: 0
count is: 2
count is: 4
count is: 6
Done counting 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 happens, step-by-step:


  1. count is initialized to 0.
  2. The condition, count <= 6 is evaluated, yielding TRUE.
  3. The loop body is executed:
    • It prints "count is: 0"
    • It adds 2 to count
    • count is now 2.
  4. The condition, count <= 6 is evaluated, yielding TRUE.
  5. The loop body is executed:
    • It prints "count is: 2"
    • It adds 2 to count
    • count is now 4.
  6. The condition, count <= 6 is evaluated, yielding TRUE.
  1. The loop body is executed:
    • It prints "count is: 4"
    • It adds 2 to count
    • count is now 6.
  2. The condition, count <= 6 is evaluated, yielding TRUE.
  3. The loop body is executed:
    • It prints "count is: 6"
    • It adds 2 to count
    • count is now 8.
  4. The condition, count <= 6 is evaluated, yielding FALSE.
  5. The body of the loop is skipped and the statement after the body is executed.
    • It prints "Done counting by two's."

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.)


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