Completion requirements
Read this chapter, which explains while loops. This is in contrast to how a do-while loop works, which we will discuss later. In a do-while loop, the body of the loop is executed at least one time, whereas in a while loop, the loop may never execute if the loop condition is false.
6. Semantics of the while statement
Answer:
Yes.
Semantics of the while
statement
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.
- After the loop body is executed, control is sent back to the
- 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 |
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 initialized, tested,
and changed. Where in the program does each of these events take place?