ActionScript supports three types of looping statements for, while and do while. A loop is used for repeatedly executing a set of statements.
for
For is the most common and popular looping statement used by the programmers. For executes the statements inside the for block for a predefined number of times or till an exit condition met. The syntax of for is
Here initiation is used for initializing the initial value of the counter in the loop. This would be the initial value of the expression. Condition is the exit condition for the for loop. Unless until we are explicitly breaking the loop by using break, continue or any such statement, loop would execute till the condition becomes false. And the increment/decrement is the next value for the loop counter.
Eg:
for(x=0; x <10; x++)
{
trace(x);
}
The above statement is unitizing the value of x as zero. The above loop would execute for 10 times. and every time the for complete the execution of statements it would increase the value of x by one. Finally when x becomes 10 the condition would return false and exit from the loop. So the above loop statement produces the following output.
0
1
2
3
4
5
6
7
8
9
While
While loop also executes till a predefined condition met. The difference between while and for loop is for is having an finalization expression and next expression, while while is having only condition. The syntax of while loop is
while(condition) {
statements
}
For eg:
var x=0;
while(x <10) {
trace(x);
x++;
}
The above while loop is equal to the for loop we have seen above and both produces the same output. But we have initialized x outside the while loop and incremented x inside the while loop body.
do while
do while loop also executes in the same way as the while loop executes. Except one major difference. The do while loop executes minimum one times even of the condition evaluates to a false value. But in while loop and for loop if the condition evaluates to a false value the loop body would not execute. The syntax of do while loop is
do {
statements
}
while(condition);
For eg:
var x=0;
do {
trace(x);
x++;
while(x < 10);