Loops and the While Statement

6. Semantics of the while statement


Answer:

Yes.

Semantics of the while statement


Here is the while statement, again:

while ( condition )
loop body // a statement or block statement

statement after the loop

Here is how the while statement works. In the following, the word control means "the statement that is executing".

  • When control reaches the while statement, the condition determines if the loop body is to be executed.
  • When the condition is true, the loop body is executed.
    • After the loop body is executed, control is sent back to the while, which again evaluates the condition.
  • When the condition is false, the loop body is skipped.
    • Control is sent to whatever statement follows the loop body.
  • Once execution has passed to the statement after the loop, the while statement is finished, at least for now.
  • If the condition is false the very first time it is evaluated, the loop body will not be executed even once.

Here is the while loop from the example program:

int count = 1;                                  // start count out at one
while ( count <= 3)                             // loop while count is <= 3
{
  System.out.println( "count is:" + count );
  count = count + 1;                            // add one to count
}
System.out.println( "Done with the loop" );     // statement after the loop           

This loop uses the variable count. It is started out at 1, then incremented each time the loop body is executed until it reaches 4 and the condition is false. Then the statement after the loop is executed.


Question 6:

The variable count is used in three different activities. It is initializedtested,
and 
changed. Where in the program does each of these events take place?