Browse Source

docs: document for loops

assignment-operators
Garrit Franke 3 years ago
parent
commit
c319f8fddc
  1. 48
      docs/concepts/control-flow.md

48
docs/concepts/control-flow.md

@ -100,3 +100,51 @@ fn main() {
println("LIFTOFF!!!")
}
```
### Looping Through a Collection with `for`
You could use the `while` construct to loop over the elements of a collection, such as an array. For example:
```
fn main() {
let a = [10, 20, 30, 40, 50]
let index = 0
while index < 5 {
println("the value is: " + a[index])
index = index + 1
}
}
```
Here, the code counts up through the elements in the array. It starts at index `0`, and then loops until it reaches the final index in the array (that is, when `index < 5` is no longer true). Running this code will print every element in the array:
```
$ sabre run main.sb
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
```
All five array values appear in the terminal, as expected. Even though index will reach a value of 5 at some point, the loop stops executing before trying to fetch a sixth value from the array.
But this approach is error prone; we could cause the program to crash if the index length is incorrect. It's also slow, because the compiler adds runtime code to perform the conditional check on every element on every iteration through the loop.
As a more concise alternative, you can use a `for` loop and execute some code for each item in a collection. A `for` loop looks like the following:
```
fn main() {
let a = [10, 20, 30, 40, 50]
for element in a {
println("the value is: " + element)
}
}
```
When we run this code, we’ll see the same output as in the previous example. More importantly, the code is faster and less prone to errors.
For example, in the code in the previous example, if you changed the definition of the a array to have four elements but forgot to update the condition to `while index < 4`, the program would crash. Using the `for` loop, you wouldn’t need to remember to change any other code if you changed the number of values in the array.

Loading…
Cancel
Save