| 1 | = Numeric For = |
| 2 | == Grammar == |
| 3 | {{{ |
| 4 | old-numeric-for-statement = |
| 5 | for <variable> = <start> .. <stop> [ ++ | -- <step> ] |
| 6 | <statements> |
| 7 | }}} |
| 8 | |
| 9 | {{{ |
| 10 | numeric-for-statement = |
| 11 | for <variable> in [<start>:]<stop>[:<step>] |
| 12 | <statements> |
| 13 | }}} |
| 14 | |
| 15 | The old-numeric-for syntax is deprecated. |
| 16 | |
| 17 | If <start> is not specified it defaults to 0.[[BR]] |
| 18 | |
| 19 | If <step> is not specified it defaults to 1. |
| 20 | |
| 21 | For each iteration <variable> gets a value beginning at <start> incrementing by <step> and ending when the <stop> value is reached or exceeded ( or a '''break''' statement is encountered). |
| 22 | |
| 23 | the loop iteration is equivalent to |
| 24 | {{{ |
| 25 | <variable> = start |
| 26 | while <variable> < <stop> |
| 27 | ... statements.. |
| 28 | <variable> = <variable> + <step> |
| 29 | }}} |
| 30 | i.e The <stop> value is exclusive to the loop counter range. |
| 31 | |
| 32 | Inside the statements, a '''break''' statement will exit the loop and a '''continue''' statement will skip the remaining statements. In either case, an if statement is used to control when the loop is broken or continued (otherwise it would be pointless to have further statements in the loop). |
| 33 | |
| 34 | == Examples == |
| 35 | {{{ |
| 36 | for i in 1:10 |
| 37 | print i # prints values 1,2,3,4,5,6,7,8,9 |
| 38 | |
| 39 | for i in 5 |
| 40 | print i # prints values 0,1,2,3,4 |
| 41 | |
| 42 | for i in 7:5:-1 |
| 43 | print i # prints values 7,6 |
| 44 | |
| 45 | for e in 20:31:2 |
| 46 | print i # prints even numbers between 20 and 30 inclusive |
| 47 | |
| 48 | for f in 7:5 |
| 49 | print f # never executed |
| 50 | }}} |
| 51 | |