
|
The for statement runs a statement or code block continuously as long as a condition is true. The condition must eventually become false or the loop will not end.
Syntax:
for ([statement1[, statement1]]; [condition]; statement2[, statement2]) // code to run
statement1: Optional. These statements at the beginning of the for loop are executed only once before the loop begins. More than one statement can be written by seperating the statements with a comma. These first statements are usually used to initialize a counting variable. For example, i=0.
condition: Optional. Before executing the loop's code, this condition is checked. If the condition is true, then the loop's code will be executed. If the condition is false, then the loop will end. If you do not enter a condition, then the condition will be always true. Then loop's code will keep running until a return or break (in MotS) command is executed.
statement2: After the loop's code has been run, the last group of statements in the for loop will be executed. Unlike the first statements, at least one statement must be entered. But like the first statements, you may have more than one statement by seperating them with a comma. These statements are usually used to increment a counting variable. For example, i = i + 1.
Although the for loop is usually used to loop code, this is not always the case. The for loop may be ended with a semicolon and no loop code will be expected. The for loop is a versatile tool, but it is easy to write a for loop that is difficult to read. The last example below is an example of what not to do. It's hard to tell by reading it that the output would be 5, 1, 2, 3.
Examples:
for (i = 0; i < 5; i = i + 1) PrintInt(i);
for (; i < 5; i = i + 1)
{
PrintInt(i);
x = x + i;
}
for (; i < x; i = i + 1, PrintInt(i));
// Do NOT do this kind of structure inside the parens of the for statement,
// because it is hard to understand.
x = 5;
for (i = 1, j = 1, PrintInt(x); i = i + 1, PrintInt(i), j = j + 2)
{
PrintInt(j);
if (i > 1) return;
}