Laboratory 7

Lets go looping now, everybody is learning how

Week of Wednesday, 12 October, 2005

Home | Resources | Homeworks | Slides | Labs | Contacts | Submit | Forums


Being able to repeatedly execute statements of interest is a powerful programming mechanism. In this laboratory you will gain practice with the Java for statement.


Key Concepts


Getting Started

Using the procedures in the previous laboratories, copy the files,,,, and for your manipulation.  Three of these files (,, and will need to be submitted.


For looping

A for statement has the following form:

for ( ForInit ; ForExpression ; ForUpdate ) { Action }

The execution of the ForInit initialization step begins the execution of a for loop. The initialization step is executed only once, regardless of how many times we iterate through the for loop.

The ForExpression is the test expression for the for loop. If the test expression evaluates to true, the body of the loop (i.e., the Action) is executed. After the body of the loop is executed (iterated), the ForUpdate step is executed.

The test expression is then reevaluated. If the test expression again evaluates to true, the body of the loop (i.e., the Action) is repeated. After the body of the loop iterates, the ForUpdate step is executed again. This process continues until the test expression evaluates to false.



Improper initialization statements and termination conditions often are causes of incorrect program behavior. The following example illustrates some common mistakes.

System.out.println("total: " + total + " fraction: " + fraction + " loopCounter: " + loopCounter);



Rectangle rendering

The next exercise shows how loops can accomplish a significant amount of work using a small number of statements. You will develop a program to draw a geometric picture that should resemble the following figure. The picture has five elements and each element is a series of concentric rectangles that alternate in color.  Note that it is not as important to understand how Java creates the GUI window - instead, focus on the details of the for loop.

IMPORTANT: If you can't complete this section of the lab during the lab session, that's fine. Do as much as you can during the lab session, and turn in what you have completed (even if it is just the skeleton code). If you spent all your time in lab session on the other parts of this lab, then you can just turn in the skeleton code for



Finishing up

Copy any files you wish to keep to your own drive.

Delete all of the files you copied or created on the laboratory machine.