1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
Loops
=====
While loops
-----------
In a while loop, you execute a certain block of code while a condition is true. The syntax is as follows:
```
while(condition) {
// block of code
// to be executed
}
```
The example below counts from 1 to 10:
```
i = 1;
while(i <= 10) {
Console.print(i);
i = i + 1;
}
```
For loops
---------
A for loop is a more controlled repetition structure when compared to the while loop. For loops support an initialization command, a condition and an increment command. The syntax is as follows:
```
for(initialization; condition; increment) {
// block of code
// to be executed
}
```
The code just displayed is equivalent to:
```
initialization;
while(condition) {
// block of code
// to be executed
increment;
}
```
The example below counts from 1 to 10:
```
for(i = 1; i <= 10; i++) {
Console.print(i);
}
```
Foreach
-------
Foreach loops are used to iterate throughout iterable collections (such as [Arrays](/reference/array) and [Dictionaries](/reference/dictionary)). Basically: for each element `x` in the iterable collection, do something with `x`. The syntax is as follows:
```
foreach(element in collection) {
// block of code
// to be executed
}
```
The example below counts from 1 to 10:
```
collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
foreach(x in collection) {
Console.print(x);
}
```
The example below iterates over a [Dictionary](/reference/dictionary):
```
dictionary = { "a": 1, "b": 2, "c": 3 };
foreach(entry in dictionary) {
Console.print(entry.key);
Console.print(entry.value);
}
```
> **Implementing your own iterable collections**
>
> The foreach loop can be used with any iterable collections, not only [Arrays](/reference/array) and [Dictionaries](/reference/dictionary). You may even [implement your own!](/tutorials/advanced_features#iterators)
|