for

A practical example of using a for loop is shown below. The function calcAvgScore calculates the mean average score for all of the scores stored in the Array named score. The way in which the for loop has been written means that you can keep adding new scores to the array and you will still get the correct mean average. For example, if you added 20 new elements to the array, the loop will know there are 24 elements in the array (score.length calculates the number of elements in an array) and the for loop will repeat the list of statements 24 times.

Function calcAvgScore()
{
var score = new Array()
score[0] = 8
score[1] = 8
score[2] = 9
score[3] = 9
averageScore = 0
scoreTotal = 0
for (loop = 0;loop<score.length;loop++)
{
 scoreTotal += score[loop]
}
averageScore = scoreTotal / score.length
Debug.trace(averageScore)]
}

The for loop expression works as follows:

  1. loop = 0 is the initialise section of the for loop. This is executed before the first time (iteration) through the loop.

  2. loop <score.length is the test section of the for loop. This is evaluated at the beginning of the loop, if the expression is true, then the list of statements in the loop are run. The first time this is evaluated it reads like this. loop is equal to 0 – which is less than score.length because score.length is 4 (i.e. the number of elements in the Array score) – therefore the answer is true. The loop statements are run because the answer is true.

  3. Loop++ is the increment section of the for loop. This is done after all of the statements in the loop have been executed, this adds 1 to the variable loop.

The steps above are repeated until loop is equal to 4, at which point the test becomes false and the loop is complete and the statements are not run.

Close