Answer:
- The initial values must be set up correctly.
- The condition in the
whileloop must be correct. - 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:
countis initialized to 0.- The condition,
count <= 6is evaluated, yielding TRUE. - The loop body is executed, printing "count is: 0" and adding 2 to
count.countis now 2.
- The condition,
count <= 6is evaluated, yielding TRUE .
- The loop body is executed, printing "count is: 2" and adding 2 to
count.countis now 4.
- The condition,
count <= 6is evaluated, yielding TRUE. - The loop body is executed, printing "count is: 4" and adding 2 to
count.countis now 6.
- The condition,
count <= 6is evaluated, yielding TRUE. - The loop body is executed, printing "count is: 6" and adding 2 to count.
countis now 8.
- The condition,
count <= 6is evaluated, yielding FALSE. - 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.)