2. The while statement


Answer:

Some Machines that Use Cycles

      • Bicycle — your legs drive the pedals connected to a gear which spins.
      • DVD Player — the disk spins (cycles) as the laser moves across it.
      • TV Set — pictures are put one the screen one after another as long as the set is on.
      • Water Pump — often a piston repeatedly moves in and out of a cylinder.
      • Laundry Dryer — rotating drum.
      • Clock — shows the same times every day. If the clock is mechanical, its insides are gears and
        springs with many mechanical cycles.
        If the clock is electronic the cycles are still there, but harder to see.
      • Sun and the Earth — endlessly cycling, seasons flowing one into the next.

Perhaps the ultimate example of the usefulness of cycles is the ultimate machine — the wheel.

The 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" ); } }

while

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.


Question 2:

What does this statement do:

    count = count + 1;