|
| 1 | +--- |
| 2 | +title: FOR Loop |
| 3 | +description: Counting iterations with the FOR loop |
| 4 | +slug: for-loop |
| 5 | +--- |
| 6 | + |
| 7 | +In [Chapter II](/while), we learned about the `while` loop which repeats as long as a condition is true. But what if you know exactly how many times you want to repeat something? The `for` loop is designed for exactly that. |
| 8 | + |
| 9 | +## Syntax |
| 10 | + |
| 11 | +```sb |
| 12 | +for <variable> = <start> to <end> |
| 13 | + <body> |
| 14 | +end |
| 15 | +``` |
| 16 | + |
| 17 | +The loop variable starts at `<start>` and increases by `1` after each iteration until it passes `<end>`. |
| 18 | + |
| 19 | +For example, to add money to the player 5 times: |
| 20 | + |
| 21 | +```sb |
| 22 | +int i |
| 23 | +for i = 1 to 5 |
| 24 | + add_score 0 100 |
| 25 | + wait 250 |
| 26 | +end |
| 27 | +``` |
| 28 | + |
| 29 | +The variable `i` will take values `1`, `2`, `3`, `4`, `5`, and the loop body will execute 5 times. After the loop, the player has $500 more. |
| 30 | + |
| 31 | +## Counting Backwards with DOWNTO |
| 32 | + |
| 33 | +To count in the opposite direction, use `downto` instead of `to`. The loop variable decreases by `1` after each iteration: |
| 34 | + |
| 35 | +```sb |
| 36 | +int i |
| 37 | +for i = 5 downto 1 |
| 38 | + print_formatted_now "Countdown: %d" 1000 i |
| 39 | + wait 1000 |
| 40 | +end |
| 41 | +
|
| 42 | +print_string_now "Go!" 2000 |
| 43 | +``` |
| 44 | + |
| 45 | +This displays `5`, `4`, `3`, `2`, `1` and then `Go!`. |
| 46 | + |
| 47 | +## Custom Step |
| 48 | + |
| 49 | +By default, the loop variable changes by `1` on each iteration. You can change this with the `step` keyword: |
| 50 | + |
| 51 | +```sb |
| 52 | +int i |
| 53 | +for i = 0 to 100 step 10 |
| 54 | + print_formatted_now "Value: %d" 500 i |
| 55 | + wait 500 |
| 56 | +end |
| 57 | +``` |
| 58 | + |
| 59 | +This displays `0`, `10`, `20`, `30`, ..., `100`. |
| 60 | + |
| 61 | +`step` works with `downto` as well: |
| 62 | + |
| 63 | +```sb |
| 64 | +int i |
| 65 | +for i = 100 downto 0 step 25 |
| 66 | + print_formatted_now "Value: %d" 500 i |
| 67 | + wait 500 |
| 68 | +end |
| 69 | +``` |
| 70 | + |
| 71 | +## Using Constants with FOR |
| 72 | + |
| 73 | +Constants pair nicely with `for` loops to make the code easy to configure: |
| 74 | + |
| 75 | +```sb |
| 76 | +const MAX_ROUNDS = 10 |
| 77 | +const REWARD = 50 |
| 78 | +
|
| 79 | +int round |
| 80 | +for round = 1 to MAX_ROUNDS |
| 81 | + add_score 0 REWARD |
| 82 | + wait 500 |
| 83 | +end |
| 84 | +``` |
| 85 | + |
| 86 | +Changing `MAX_ROUNDS` or `REWARD` at the top of the script instantly adjusts the loop behavior. |
0 commit comments