The for loop is used to execute a statement or a series of statements inside the loop block as long as a particular condition remains true. It comprises three parts: initialization, condition, and increment.
The initialization portion is generally an expression that sets the value of the loop control variable. The loop control variable acts as a counter and controls the execution of the loop. The initialization portion executes only once.
The condition portion must be a boolean expression. It tests before the statement inside the loop block is executed. If the condition is true, the statement is executed. But if the condition is false, the statement is skipped and the next statement following the for loop will be executed.
The increment portion is usually an expression that increments or decrements the loop control variable.
The syntax of the for loop is as follows:
statement(s);
}
The loop performs the following 4 steps until the condition returns false:
- When the loop starts, the initialization expression is executed.
- The condition is evaluated. If condition returns true, go to step 3. Otherwise, execute the next statement following the for loop.
- Run the statement inside the loop block.
- The increment expression executes and then go back to step 2.
In the following example, the for loop executes till the value of the variable rs is less than 20.
trace(”I have Rs. “+x+” in my pocket. I can expend Rs. “+rs+” of them.”);
}
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.