Nested Loops |
Suppose I want to draw a scarf where each row of the scarf is a sequence of overlapping ovals.
I can write each row (at y-coordinate given by y) as follows:
var numCols: Number := 0 var x := point.x // x position of the next "stitch" while {numCols < scarfWidth} do { def stitch: Graphic2D = framedOval.at(x @ y) size (diameter,diameter) on (canvas) stitch.color := scarfColor x := x + xSpace numCols := numCols + 1 }
What do we have to add to draw a lot of rows? Nested loops! See scarf.
Here are a few things that we mainly discussed Wednesday, but we'll include them in the notes for today anyway.
The key to developing programs involving nested loops is to understand first what the outer loop is doing (going through successive rows) and what the inner loop is drawing (drawing all circles of an inner loop. We can think of the general structure as:
while (rowNum < MAX_ROWS) { draw new row rowNum = rowNum+1 shift y coordinate of new row }
Drawing a new row now requires only initializing the starting x coordinate and a while loop to draw all of the circles.
Each time we start a new row, there are a number of things that we will need to take care of:
Suppose we wish to design a class to draw an American flag.
Notice how we used private methods in this example. The methods drawStripes and drawStars are called from inside the Flag constructor. They are not designed to be accessible from outside the class. They are designed only to be useful in breaking down the constructor into easier to understand pieces. drawStripes, is especially useful because it allows us to avoid duplicating code. Notice that it is used twice inside the constructor. Once to draw short stripes, and once to draw long stripes. Because we provide different parameters to it each time, it produces different results. If we did not use this private method, we would have to repeat the code in the method twice, once for each collection of values of the parameters.
Old, but interesting, things in the code include the nested while loop in the drawStars method as well as the fact that several items are changing each time through the while loops. Notice that in the outer while loop in drawStars, we must reinitialize both col and x each time through the loop.
Nested Loops |