Main Content

You are here:

For loops

Hello and welcome. Today we shall be leaning about one concept of Flash, for loops. For loops are very useful for looping through lots of information quickly, or trying out lots of possibilities quickly.

The downside of for loops is that you really have to know how many times they are going to run. This is not a problem if you want a loop to generate 10 bullets, but if you need condition checking at the end of your block of things to do, different sorts of loops would probably suit you better.

In addition, for loops are particularly useful when working with arrays and are also very simple to use: they have a built in counter, so the loop knows how many times it has repeated, for example. You write the for statement using the following basic format:

for (init; condition; update) { // statements; }

You must supply three expressions to a for statement:

By convention, 'i' is used as the variable where possible, as it is the first letter of the word iteration: the techincal term for one "run-through" of the loop. The condition is most commonly "i <" or "i >" and the update generally i++ (add 1 to i) or i-- (subtract 1 from i). The order of the procedures is also important to knowing how the loop works: initialise --> check condition --> do the stuff --> update --> check --> do etc.

Examples

The following code loops five times. The value of the variable i starts at 0 and ends at 4. In this example, the first expression (i = 0) is the initial expression that evaluates before the first iteration. The second expression (i < 5) is the condition that you check each time before the loop runs. The third expression (i++) is called the post expression and is evaluated each time after the loop runs.

var i;  
for (i = 0; i < 5; i++) {
        trace(i);
}

Which will output the exact same thing as this loop:

for (var i = 0; i < 5; i++) {
        trace(i);
}

This is also a legitimate loop:

var a = 0; var b = 5; var c = 1;
for (var i = a; i < b; i = i + c) {
        trace(i);
}
With Arrays

By utilising the length property of an array, you can quickly loop through all the elements in the array: strings for example.This is an example of a message writer, though you can do so much more, as demonstrated in some of our tutorials:

var myArr:Array = new Array();
myArr[0] = "H";
myArr[1] = "e";
myArr[2] = "l";
myArr[3] = "l";
myArr[4] = "o";
for (var i = 0; i < myArr.length; i++) {
        trace(myArr[i]);
}

For loops do have incredibly versatile application: the combination with arrays, however, makes them even more useful. Hopefully now, at the end of this free ActionScript tutorial, you will know a little more about for loops. Well done!

Harry.

Comments