Perhaps the ultimate example of the usefulness of cycles is the ultimate machine — the wheel.
while
statement
Here is a program with a loop.
It contains a while
statement,
followed by a block of code.
A block is a group of statements enclosed in brackets
{
and }
.
// Example of a while loop public class LoopExample { public static void main (String[] args ) { // start count out at one int count = 1; // loop while count is <= 3 while ( count <= 3 ) { System.out.println( "count is:" + count ); // add one to count count = count + 1; } System.out.println( "Done with the loop" ); } }
The flowchart shows how the program works.
First, count
is set to one.
Then it is tested by the while
statement to see if it is less than or equal to three.
The test returns true so the statements in
the block following the while
are executed.
The current value of count
is printed, and
count
is incremented.
Then execution goes back to the while
statement
and the test is performed again.
count
is now two,
the test returns true and the block is executed again.
The last statement of the block increments count
to three,
then execution goes back to the while
statement.
count
is now three,
the test returns true and the block is executed again.
The last statement of the block increments count
to four,
then execution goes back to the while
statement.
After the block has executed three times,
count
is four.
Execution goes back to the while
statement,
but now the
test returns false, and
execution goes to the "Done with loop" statement.
Then the program ends.
Copy this program to a file and run it. Then play with it. See if you can change the program so it prints one through ten. Then change it so that it prints zero through ten.
What does this statement do:
count = count + 1;