For Loop
(→Example) |
(→expression2) |
||
Line 28: | Line 28: | ||
You can add multiple expressions by separating them with a , | You can add multiple expressions by separating them with a , | ||
+ | |||
+ | If you have multiple expressions to be checked here it will require ALL of them to be true | ||
==== expression3 ==== | ==== expression3 ==== |
Revision as of 08:41, 29 September 2013
Contents |
For As
Description
Loop based on an expression.
for ( <expression1> ; <expression2> ; <expression3> ) { statements ... }
Parameters
expression1
An expression to execute before starting the loop.
You can add multiple expressions by separating them with a ,
expression2
An expression to evaulate and check if its TRUE.
If it is not TRUE the loop will end (Or not even begin).
You can add multiple expressions by separating them with a ,
If you have multiple expressions to be checked here it will require ALL of them to be true
expression3
An expression to execute after each cycle of the loop.
Usually $i++ or $i += something
You can add multiple expressions by separating them with a ,
Remarks
For statements may be nested.
The expression2 can contain the boolean operators of &&, ||, ! as well as the logical operators <, <=, >, >=, ==, !=, <>, eq, eqi, neq and neqi as needed grouped with parentheses as needed.
Example
Count up to from 1 to 10
for ( $i = 1; $i <= 10; $i++ ) { println( "Value is $i" ); }
Count down to from 10 to 1
for ( $i = 10; $i > 0; $i-- ) { println( "Value is $i" ); }
Count up to from 2 to 20 counting in 2s
for ( $i = 2; $i <= 20; $i += 2 ) { println( "Value is $i" ); }
Using multiple expressions
for ( $i = 0, $j = 3; $i < 10; $i++, $j++ ) { println( "Value is $i -- $j" ); }
Using multiple expressions with multiple comparison it will print the same as the one above since it will only continue looping if *all* the comparisons are *true*
# basically this is equal to using # $i < 10 && $j < 20 for ( $i = 0, $j = 3; $i < 10, $j < 20; $i++, $j++ ) { println( "Value is $i -- $j" ); }
Print all array elements Method 1
$arr = array( "One", "Two", "Three", "Four", "Five" ); for ( $i = 0; $i < UBound($arr); $i++ ) { $item = $arr[$i]; println( "Value is " . $item ); }
Print all array elements Method 2
$arr = array( "One", "Two", "Three", "Four", "Five" ); for ( $i = 0; $i < UBound($arr); $i++ ) { println( "Value is $arr[$i]" ); }
A perl style number to number for
for( 0 .. 10 ) { println("Value $_"); // Yes the $_ gets set just like in Perl } // or for( 0 .. 10 as $i ) { println("Value $i"); // Yes the $_ gets set just like in Perl } // A Reverse style my $x = 5; println("Hello $_") for(3..$x);
Another perl style but this time using variables
$a = 1; $b = 30; for( $a..$b ) { println("Value $_"); // Yes the $_ gets set just like in Perl } // or for( $a..$b as $i ) { println("Value $i"); // Yes the $_ gets set just like in Perl } // A Reverse style println("Hello $k") for(3..$x as $k);