For Loop
From Sputnik Wiki
(Difference between revisions)
(Created page with "= For As = === Description === Loop based on an expression. <pre> for ( <expression1> ; <expression2> ; <expression3> ) { statements ... } </pre> === Parameters === ...") |
(→Example) |
||
Line 84: | Line 84: | ||
{ | { | ||
println( "Value is $arr[$i]" ); | println( "Value is $arr[$i]" ); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | A perl style number to number for | ||
+ | |||
+ | <syntaxhighlight lang="sputnik"> | ||
+ | for( 0 .. 10 ) | ||
+ | { | ||
+ | println("Value $_"); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Another perl style but this time using variables | ||
+ | |||
+ | |||
+ | <syntaxhighlight lang="sputnik"> | ||
+ | $a = 1; | ||
+ | $b = 30; | ||
+ | |||
+ | for( $a..$b ) | ||
+ | { | ||
+ | println("Value $_"); | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
[[Category:Core Function]] | [[Category:Core Function]] |
Revision as of 23:39, 28 January 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.
expression2
An expression to evaulate and check if its TRUE.
If it is not TRUE the loop will end (Or not even begin).
expression3
An expression to execute after each cycle of the loop.
Usually $i++ or $i += something
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" ); }
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 $_"); }
Another perl style but this time using variables
$a = 1; $b = 30; for( $a..$b ) { println("Value $_"); }