The FOR Loop - 06ForLoop.fla

The For Loop is used when you need to repeat an operation several times.

Which kind of loop ???

  • If you know in advance how many repetitions you need - use FOR
  • If you need to repeat zero or more times - use WHILE
  • If you need to repeat one or more times - use DO

This program creates a movie clip and draws a graph with grid lines.

  • Input - Button press to trigger the processing
  • Process - Create a movie clip
  • Output -
        X axis grid lines (not yet implemented)
        Y axis grid lines
        Graph plot
  1. Start up Flash.
  2. Create a new Flash document.
  3. Save the file as 06ForLoop.fla.
  4. Place a button onto your canvas.

Set up your Flash MX environment like this ...

Enter this code


on (release)
{
    _root.createEmptyMovieClip("myGraph", 1);
  
    with (_root.myGraph) {
    lineStyle(1, 0x000000, 100);    // 1 thickness, 0x000000 colour, 100% alpha 
	
    // HORIZONTAL GRID LINES
    //   START--   STOP----  STEP--------
    for (yy = 50;  yy < 400; yy = yy + 20)
    {
        moveTo(  0, yy);                // Start position
        lineTo(500, yy);                // Straight line to this position
    }
	
    moveTo(0, 50 + (-250 / 13) * (-250 / 13)); // Start position
	
    // PLOT THE GRAPH
    //   START----   STOP----   STEP-------
    for (xx = -250;  xx < 250;  xx = xx + 1)
    {
        yy = (xx / 13) * (xx / 13);     // yy = xx squared
        lineTo(250 + xx, 50 + yy);
    }	
}

Here is the example movie

You can download the source code.

Tasks

  1. Draw the X axis grid lines.
  2. Turn the graph the right way up.
  3. Explain the co-ordinate system and why the graph was upside down in the first place.
  4. Plot a graph of y = 4 * x + 2
  5. Plot a graph of y = x * x * x

Notes

Example

//  START->  STOP-->   STEP------>
for(ii = 10; ii < 20;  ii = ii + 1)
{
  doThis();
}

The For Loop has three parts. These are start, stop and step. The example above counts from 10 to 19. On the first time round the loop, ii = 10. Next time round ii = 11. Each time round the loop, ii increases its value by one.

Start

This initialises a variable (ii) at the beginning of the repetition. In this example ii is set to 10.

Stop

This is a Boolean. It is a true or false value. The repetition continues as long as the Boolean is true. In this example the loop keeps going as long as ii is less than 20.

Step

This alters the (ii) variable. In this example one is added to ii on each repetition.

 

 

© C N Bauers (2004) - You may use these materials for your self education. Educational institutions may use these materials too.