Java Reference
In-Depth Information
Display 3.10 for Statement Syntax and Alternate Semantics (part 2 of 2)
Equivalent while Loop Syntax
Initialization ;
while ( Boolean_Expression )
{
Body ;
Update;
}
EQUIVALENT EXAMPLE
number = 100;
while (number >= 0)
{
System.out.println(number + " bottles of beer on the shelf.");
number--;
}
Sample Dialogue
100 bottles of beer on the shelf.
99 bottles of beer on the shelf.
.
.
.
0 bottles of beer on the shelf.
The Comma in for Statements
A for loop can contain multiple initialization actions. Simply separate the actions with
commas, as in the following:
for (term = 1, sum = 0; term <= 10; term++)
sum = sum + term;
This for loop has two initializing actions. The variable term is initialized to 1, and the
variable sum is also initialized to 0. Note that you use a comma, not a semicolon, to
separate the initialization actions.
You can also use commas to place multiple update actions in a for loop. This can lead
to a situation in which the for loop has an empty body but still does something useful.
For example, the previous for loop can be rewritten to the following equivalent version:
for (term = 1, sum = 0; term <= 10; sum = sum + term, term++)
//Empty body ;
 
 
Search WWH ::




Custom Search