Iteration
Iterations allow you to do a set of expressions over and over again. Similar to selection statements, iteration statements also evaluate to a value. In this case it evaluates to the value of the expression of the last iteration.
while
while <expression> do (
<expressions>
)
do-while
do (
<expressions>
) while <expression>
for
The for loop is a counting loop. In max, other than standard counting loop, it also allows you to work with thing arrays or a set of objects as part of the for loop syntax. In this section we will only talk about for as a counting loop. We will look at the usage of for loops that iterate through collections in the array section of the notes
for <variable> = <expr> to <expr> [by expr>] [while<expr>] [where <expr>] do
(
<expressions>
)
So, here are some examples of the equivalent C/C++ for loop and max for loop Example 1: simple counting loop:
/* C/C++*/
for(i=1;i<=5;i++){
...
}
/* max*/
for i = 1 to 5 do (
...
)
Example 2: counting loop that counts by 2's
for(i=1;i<=5;i+=2){
...
}
for i = 1 to 5 by 2 (
...
)
Example 3: counting loop with additional termination condition.
for(i=1;i<=5 && x>3;i++){
...
}
for i = 1 to 5 while x>3 (
...
)
Note that while it is possible to break out of loops early using exit, doing so has significant performance hits.
Example 4: counting loop where statements are only done when a condition is met (but loop continues regardless)
for(i=1;i<5;i++){
if(x>3){
...
}
}
for i=1 to 5 where x>3(
...
)